Skip to main content

micromegas_analytics/lakehouse/
jit_partitions.rs

1//! Just-in-time (JIT) partition generation groups a view's source blocks (queried from
2//! `blocks_view` in `ORDER BY insert_time, block_id` order) into `SourceDataBlocksInMemory`
3//! partitions no larger than `JitPartitionConfig::max_nb_objects`.
4//!
5//! `JitPartitionConfig::block_order` (see `BlockOrder`) picks between two orderings for the
6//! blocks a partition ends up holding: `InsertTime` (the SQL order, unchanged) for views that
7//! decode blocks independently, and `EventTime` for views that build cross-block trees or rely on
8//! event-time-sorted rows within a partition file. `group_blocks_into_partitions` is the single
9//! place both variants are cut, and it upholds one invariant regardless of ordering: every emitted
10//! partition's `[min_insert_time, max_insert_time]` range is non-overlapping with, and
11//! non-decreasing relative to, every other emitted partition's -- the precondition the
12//! `lakehouse_partitions_no_overlap` exclusion constraint enforces at insert time. See
13//! `group_blocks_into_partitions`'s own docs for how that invariant is upheld under
14//! `BlockOrder::EventTime`, where the natural size-based cut point is not always safe, and for
15//! the one (production-unreachable) shape it does not cover.
16//!
17//! Note that this is an *insert-time* invariant only. It says nothing about partitions'
18//! *event-time* ranges, which for the block-derived views are computed from block
19//! `begin_ticks`/`end_ticks`. By design both `micromegas_tracing` and the Unreal producer now stamp
20//! a single shared timestamp per flush, used for both the outgoing block's close and the
21//! replacement block's `begin`, so consecutive blocks touch exactly and adjacent partitions' event
22//! bounds do not overlap by construction. Data from producer versions predating that fix can still
23//! carry strictly-overlapping block ticks; `ThreadSpansView`'s recorded `max_sort_key_time` is what
24//! makes that harmless to the `Concatenated` scan check (`partitioned_execution_plan::partition_bounds`
25//! prefers it over the looser `max_event_time`) rather than requiring every source block to be
26//! re-ingested. See the ordering-invariant notes on `View::get_scan_output_ordering` and
27//! `tasks/completed/thread_spans_segment_boundary_overlap_plan.md`.
28
29use super::{
30    block_partition_spec::{BlockPartitionSpec, BlockProcessorMap},
31    blocks_view::BlocksView,
32    jit_promotion::{promote_closed_buckets, promotion_candidates},
33    lakehouse_context::LakehouseContext,
34    partition_cache::{LivePartitionProvider, QueryPartitionProvider},
35    partition_ladder::{
36        BucketCount, LADDER, PlannedBucket, align_outward, plan_buckets, select_rung,
37    },
38    partition_source_data::{PartitionSourceBlock, SourceDataBlocksInMemory},
39    view::{View, ViewMetadata},
40    write_partition::{PartitionOverlapConflict, RetireMatch},
41};
42use crate::{
43    dfext::{
44        string_column_accessor::string_column_by_name,
45        typed_column::{get_single_row_primitive_value, typed_column_by_name},
46    },
47    lakehouse::{
48        partition_cache::PartitionCache, partition_source_data::hash_to_object_count,
49        query::query_partitions, view::PartitionSpec,
50    },
51    metadata::{
52        ProcessMetadata, StreamMetadata, block_from_batch_row, stream_metadata_from_batch_row,
53    },
54    response_writer::ResponseWriter,
55    time::TimeRange,
56};
57use anyhow::{Context, Result};
58use chrono::{DateTime, TimeDelta, Utc};
59use datafusion::arrow::array::{Int64Array, TimestampNanosecondArray};
60use datafusion::arrow::datatypes::{Schema, TimestampNanosecondType};
61use micromegas_ingestion::data_lake_connection::DataLakeConnection;
62use micromegas_telemetry::types::block::BlockMetadata;
63use micromegas_tracing::prelude::*;
64use sqlx::Row;
65use std::collections::HashMap;
66use std::sync::Arc;
67use uuid::Uuid;
68
69/// How source blocks are ordered before being cut into JIT partitions.
70///
71/// The choice matters because `generate_stream_jit_partitions_segment` and the batched block
72/// queries driven by `generate_stream_jit_partitions` / `generate_process_jit_partitions` fetch
73/// blocks with `ORDER BY insert_time, block_id`, and that SQL order is what
74/// `group_blocks_into_partitions` starts from.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum BlockOrder {
77    /// Registration order (`insert_time`, `block_id`), i.e. the SQL order is kept as-is. Correct
78    /// for views that decode each block independently and declare no scan ordering: cutting an
79    /// insert-ordered list always yields insert-time ranges that are non-decreasing and
80    /// non-overlapping across partitions, by construction.
81    InsertTime,
82    /// Event order (`begin_ticks`, `end_ticks`). Required by views that build cross-block trees or
83    /// derive event-time bounds from the list endpoints, and by any view declaring
84    /// `ScanOrdering::Concatenated` over an event-time column. Sorting by event time can put blocks
85    /// with out-of-order `insert_time` inside one partition or straddling a cut point, so
86    /// `group_blocks_into_partitions` additionally enforces insert-safe cut points (see its docs)
87    /// to keep JIT partitions' insert-time ranges non-overlapping.
88    EventTime,
89}
90
91/// How insert-time buckets are sized.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub enum BucketSizing {
94    /// Every bucket is the same width and treated as closed, with no descent on object count.
95    Fixed(TimeDelta),
96    /// The bucket width follows the query range along `partition_ladder::LADDER`. `grace` is how
97    /// long after a bucket ends it is still considered open.
98    RangeDriven { grace: TimeDelta },
99}
100
101/// Configuration for Just-In-Time (JIT) partition generation.
102pub struct JitPartitionConfig {
103    pub max_nb_objects: i64,
104    pub bucket_sizing: BucketSizing,
105    pub block_order: BlockOrder,
106    /// Soft row-count target for a single batched block query (see `batch_windows`). Consecutive
107    /// insert-time buckets are packed into one query up to this many blocks, derived from a
108    /// per-bucket count query run before the batch queries themselves. A config field rather
109    /// than a bare constant so DB-gated tests can lower it to force a run to split into more than
110    /// one batch.
111    pub target_rows_per_query: i64,
112}
113
114impl Default for JitPartitionConfig {
115    fn default() -> Self {
116        JitPartitionConfig {
117            max_nb_objects: 20 * 1024 * 1024,
118            bucket_sizing: BucketSizing::RangeDriven {
119                grace: TimeDelta::seconds(90),
120            },
121            block_order: BlockOrder::InsertTime,
122            target_rows_per_query: 250_000,
123        }
124    }
125}
126
127impl JitPartitionConfig {
128    /// `(rung, finest)`: the width the query's buckets start at, and the narrowest the planner
129    /// may descend to. Also the resolution of the per-bucket counts.
130    fn rungs(&self, query_range: &TimeRange) -> (TimeDelta, TimeDelta) {
131        match self.bucket_sizing {
132            BucketSizing::Fixed(slice) => (slice, slice),
133            BucketSizing::RangeDriven { .. } => (select_rung(*query_range), LADDER[0]),
134        }
135    }
136
137    fn plan(
138        &self,
139        insert_range: TimeRange,
140        rung: TimeDelta,
141        finest: TimeDelta,
142        counts: &[BucketCount],
143    ) -> Vec<PlannedBucket> {
144        let (now, grace) = match self.bucket_sizing {
145            // Every bucket is closed under fixed sizing.
146            BucketSizing::Fixed(_) => (DateTime::<Utc>::MAX_UTC, TimeDelta::zero()),
147            BucketSizing::RangeDriven { grace } => (Utc::now(), grace),
148        };
149        plan_buckets(
150            insert_range,
151            rung,
152            finest,
153            now,
154            grace,
155            counts,
156            self.max_nb_objects,
157        )
158    }
159}
160
161/// A planned bucket with the partition specs grouped from its blocks.
162pub struct JitBucket {
163    pub planned: PlannedBucket,
164    pub specs: Vec<SourceDataBlocksInMemory>,
165}
166
167/// Returns the real `[min, max]` `insert_time` range covered by `blocks`, independent of list
168/// order. Always use this instead of reading `blocks[0]`/`blocks[last]`: under
169/// `BlockOrder::EventTime` the list is sorted by event time, not insert time, so its endpoints are
170/// no longer the insert-time extremes.
171pub fn blocks_insert_time_range(blocks: &[Arc<PartitionSourceBlock>]) -> Result<TimeRange> {
172    let mut blocks_iter = blocks.iter();
173    let first = blocks_iter
174        .next()
175        .with_context(|| "blocks_insert_time_range: empty block list")?;
176    let mut min_insert_time = first.block.insert_time;
177    let mut max_insert_time = first.block.insert_time;
178    for block in blocks_iter {
179        min_insert_time = min_insert_time.min(block.block.insert_time);
180        max_insert_time = max_insert_time.max(block.block.insert_time);
181    }
182    Ok(TimeRange::new(min_insert_time, max_insert_time))
183}
184
185/// Splits an event-time-ordered block list into maximal chains whose tick coverage is unbroken, so
186/// each chain can be decoded into one cross-block tree (a call tree for `thread_spans`, a net span
187/// tree for `net_spans`).
188///
189/// A chain breaks only on a *gap* -- `begin_ticks` strictly after the running `end_ticks`, meaning
190/// blocks are missing in between and a tree built across the seam would be nonsense. An *overlap*
191/// (`begin_ticks` at or before the running end) still means unbroken coverage and keeps the chain
192/// open. The chain rule stays tolerant of overlap (not just equality) deliberately: by design both
193/// `micromegas_tracing::dispatch`'s flush paths and the Unreal producer now stamp one shared
194/// timestamp per flush, so consecutive blocks from a healthy producer touch exactly
195/// (`begin_ticks == running end_ticks`) -- but blocks from producer versions predating that fix
196/// (or any other producer stamping two separate timestamps) can still carry a real, small overlap,
197/// and those legacy blocks are exactly the ones this function must keep chaining correctly. An
198/// equality-only test would incorrectly break the chain on every such legacy seam.
199///
200/// The running end is a max, not just the previous block's `end_ticks`: a chain must not be broken
201/// by a short block fully contained in an earlier, longer one.
202pub fn group_contiguous_block_chains(
203    blocks: &[Arc<PartitionSourceBlock>],
204) -> Vec<Vec<BlockMetadata>> {
205    let mut chains: Vec<Vec<BlockMetadata>> = vec![];
206    let mut chain: Vec<BlockMetadata> = vec![];
207    let mut chain_end: Option<i64> = None;
208    for block in blocks {
209        match chain_end {
210            // A gap: close the chain and re-seed from this block.
211            Some(end) if block.block.begin_ticks > end => {
212                chains.push(std::mem::take(&mut chain));
213                chain_end = Some(block.block.end_ticks);
214            }
215            // Touching or overlapping: extend the chain.
216            Some(end) => chain_end = Some(end.max(block.block.end_ticks)),
217            None => chain_end = Some(block.block.end_ticks),
218        }
219        chain.push(block.block.clone());
220    }
221    if !chain.is_empty() {
222        chains.push(chain);
223    }
224    chains
225}
226
227/// Emits one partition (if it holds any objects) from `blocks[start..end]`, logging once if the
228/// window genuinely grew past `max_nb_objects` because no insert-safe cut point was available.
229fn emit_partition(
230    out: &mut Vec<SourceDataBlocksInMemory>,
231    blocks: &[Arc<PartitionSourceBlock>],
232    start: usize,
233    end: usize,
234    nb_objects: i64,
235    grown_past_limit: i64,
236    max_nb_objects: i64,
237) {
238    // A window whose blocks all report nb_objects == 0 is dropped rather than emitted as a
239    // rows-free partition. No *in-repo* producer emits a zero-object block --
240    // `micromegas_tracing::dispatch`'s flush paths skip empty streams, the Unreal sink does the
241    // same, and OTLP ingestion returns no block for a zero-record batch -- but nothing enforces it
242    // (`nb_objects` has no CHECK constraint and the ingestion API does not validate it). Dropping
243    // is safe: such blocks carry no rows, and each partition's DB range is derived per-spec from
244    // `blocks_insert_time_range`, not from full block coverage.
245    if nb_objects == 0 {
246        return;
247    }
248    if grown_past_limit > 0 {
249        // process_id only: under the process-level path (`generate_process_jit_partitions`) a
250        // partition can span several streams, and after the event-time sort `blocks[start]` is an
251        // arbitrary one of them.
252        //
253        // debug!, not warn!: grouping re-runs on every query over the view (jit_update is called
254        // from every scan, and the stable sort makes cut decisions deterministic), so a persistent
255        // inversion would re-emit the same message on every query forever.
256        let process_id = blocks[start].process.process_id;
257        debug!(
258            "group_blocks_into_partitions: process={process_id} emitted a partition of \
259             {nb_objects} objects (soft limit max_nb_objects={max_nb_objects}) after \
260             {grown_past_limit} cut(s) deferred by insert-time inversions with no insert-safe cut \
261             point available"
262        );
263    }
264    out.push(SourceDataBlocksInMemory {
265        blocks: blocks[start..end].to_vec(),
266        block_ids_hash: nb_objects.to_le_bytes().to_vec(),
267    });
268}
269
270/// Groups a segment's source blocks into JIT partitions.
271///
272/// Two invariants must both hold across the returned partitions:
273/// - **Size** -- `max_nb_objects` is a soft, whole-block-granularity limit (a block is never
274///   split, so a single oversized block already exceeds it).
275/// - **Insert-time non-overlap** -- the `lakehouse_partitions_no_overlap` exclusion constraint
276///   requires each partition's `[min_insert_time, max_insert_time]` to be non-overlapping with
277///   (and non-decreasing relative to) every other partition's. Adjacent partitions may *touch*
278///   (one's max equals the next's min): the constraint's `tstzrange` is half-open `[)`, so that
279///   is not an overlap. The one shape this does not cover is two or more partitions sharing an
280///   *identical degenerate* range (every block in both carrying the same `insert_time`), which
281///   requires more than `max_nb_objects` objects at a single microsecond and so does not occur in
282///   production; `tstzrange(t, t)` is empty, so the constraint stays quiet, but the
283///   up-to-date check (`spec_is_up_to_date`) would see more than one row for that range and never
284///   report the partitions up to date.
285///
286/// Under `BlockOrder::InsertTime` both invariants hold for free: `blocks` is already sorted by
287/// `insert_time`, so every candidate cut point is insert-safe and this function cuts at exactly
288/// `max_nb_objects` -- identical to a naive greedy cut except that an all-zero-object window emits
289/// nothing rather than a rows-free partition (see `emit_partition`; unreachable in practice).
290///
291/// Under `BlockOrder::EventTime`, `blocks` is stable-sorted by `(begin_ticks, end_ticks)` first
292/// (ties keep the incoming, insert-ordered position, so grouping stays deterministic); a cut point
293/// is then only taken where it is *insert-safe*: every block already in the partition being closed
294/// must have an `insert_time` no later than every remaining block's, computed via a suffix-minimum
295/// over the event-time-sorted list. When the natural `max_nb_objects` cut point isn't safe, the cut
296/// looks back to the most recent safe index; when no safe index exists in the window, the window
297/// grows past the soft limit and a `debug!` logs it.
298pub fn group_blocks_into_partitions(
299    config: &JitPartitionConfig,
300    mut blocks: Vec<Arc<PartitionSourceBlock>>,
301) -> Vec<SourceDataBlocksInMemory> {
302    if config.block_order == BlockOrder::EventTime {
303        // Stable sort: ties keep the incoming (insert_time, block_id) order.
304        blocks.sort_by(|a, b| {
305            (a.block.begin_ticks, a.block.end_ticks).cmp(&(b.block.begin_ticks, b.block.end_ticks))
306        });
307    }
308    let n = blocks.len();
309    if n == 0 {
310        return vec![];
311    }
312
313    // suffix_min[i] = min(insert_time of blocks[i..n]) over the (possibly event-time-sorted)
314    // list; suffix_min[n] = DateTime::<Utc>::MAX_UTC so a cut at n (the tail) is always safe.
315    let mut suffix_min = vec![DateTime::<Utc>::MAX_UTC; n + 1];
316    for i in (0..n).rev() {
317        suffix_min[i] = suffix_min[i + 1].min(blocks[i].block.insert_time);
318    }
319
320    let mut out = vec![];
321    let mut start = 0usize;
322    let mut nb_objects: i64 = 0;
323    let mut prefix_max_insert = DateTime::<Utc>::MIN_UTC;
324    // (index, nb_objects of blocks[start..index]) of the most recent safe cut point seen since
325    // the current window started.
326    let mut last_safe: Option<(usize, i64)> = None;
327    // Counts only the "no safe cut point exists" (grow-past-limit) events below; the look-back
328    // branch logs about itself directly and does not feed this counter (its emitted prefix is
329    // provably <= max_nb_objects, so it must not carry the soft-limit wording).
330    let mut grown_past_limit: i64 = 0;
331
332    let mut i = 0usize;
333    while i < n {
334        // A cut at i is safe iff every block already accumulated (blocks[start..i]) was
335        // inserted no later than every remaining block (blocks[i..]): the emitted partition's
336        // insert range then cannot overlap any later partition's.
337        let safe_here = prefix_max_insert <= suffix_min[i];
338        if safe_here && i > start {
339            last_safe = Some((i, nb_objects));
340        }
341        let block_nb_objects = blocks[i].block.nb_objects as i64;
342        let full = nb_objects + block_nb_objects > config.max_nb_objects && i > start;
343        if full {
344            if safe_here {
345                // The natural cut point is insert-safe: cut here, <= max_nb_objects.
346                emit_partition(
347                    &mut out,
348                    &blocks,
349                    start,
350                    i,
351                    nb_objects,
352                    grown_past_limit,
353                    config.max_nb_objects,
354                );
355                start = i;
356                nb_objects = 0;
357                prefix_max_insert = DateTime::<Utc>::MIN_UTC;
358                last_safe = None;
359                grown_past_limit = 0;
360                continue;
361            } else if let Some((j, j_nb_objects)) = last_safe {
362                // Look back to the most recent safe index: emit the already-safe prefix (which is
363                // provably <= max_nb_objects, since `full` only trips once nb_objects already
364                // fits under the limit), then re-seed the window from j and replay blocks[j..i)
365                // to recompute running state before reprocessing block i (which may itself still
366                // be unsafe -- a straggler's window is not bounded by this rule, see the module
367                // docs).
368                // process_id only -- see the note in `emit_partition`. debug!, not warn!: this is
369                // the designed, insert-safe path and re-fires on every query over the view for as
370                // long as the inversion exists in the source blocks.
371                let process_id = blocks[start].process.process_id;
372                debug!(
373                    "group_blocks_into_partitions: process={process_id} cut moved back from index \
374                     {i} to {j} ({} block(s) looked back)",
375                    i - j
376                );
377                emit_partition(
378                    &mut out,
379                    &blocks,
380                    start,
381                    j,
382                    j_nb_objects,
383                    0,
384                    config.max_nb_objects,
385                );
386                start = j;
387                nb_objects = 0;
388                prefix_max_insert = DateTime::<Utc>::MIN_UTC;
389                last_safe = None;
390                grown_past_limit = 0;
391                // No last_safe recomputation while replaying: no index in (j, i] can be safe
392                // after the re-seed. j was the most recent safe index, so every block before j
393                // has insert_time <= suffix_min[j] <= suffix_min[m] for any m > j -- meaning a
394                // cut at m is safe in the re-seeded window iff it was safe in the original one,
395                // and the original pass already found all of (j, i] unsafe (otherwise last_safe
396                // would have pointed there instead of j).
397                for replayed in &blocks[start..i] {
398                    nb_objects += replayed.block.nb_objects as i64;
399                    prefix_max_insert = prefix_max_insert.max(replayed.block.insert_time);
400                }
401                continue;
402            } else {
403                // No safe cut point exists anywhere in this window: grow past the soft limit
404                // rather than emit a partition whose insert range could overlap a later one.
405                grown_past_limit += 1;
406            }
407        }
408        nb_objects += block_nb_objects;
409        prefix_max_insert = prefix_max_insert.max(blocks[i].block.insert_time);
410        i += 1;
411    }
412    emit_partition(
413        &mut out,
414        &blocks,
415        start,
416        n,
417        nb_objects,
418        grown_past_limit,
419        config.max_nb_objects,
420    );
421    out
422}
423
424/// Packs consecutive planned buckets into batch query windows, greedily closing a window just
425/// before it would exceed `target_rows_per_query`.
426///
427/// A bucket whose own block count already exceeds `target_rows_per_query` still forms one batch on
428/// its own -- the loop never splits a bucket.
429///
430/// Batch edges are always bucket edges and batches tile from the first bucket's start to the last
431/// bucket's end with no gaps or overlaps (the gaps between planned buckets hold no blocks), so
432/// which width is picked cannot change the specs `group_blocks_into_partitions` later emits per
433/// bucket -- only how many SQL queries it takes to gather them. `buckets` must be ascending; an
434/// empty `buckets` yields no window.
435pub fn batch_windows(
436    buckets: &[PlannedBucket],
437    target_rows_per_query: i64,
438) -> impl Iterator<Item = TimeRange> {
439    let mut windows = Vec::new();
440    let Some(first) = buckets.first() else {
441        return windows.into_iter();
442    };
443    let mut running: i64 = 0;
444    let mut batch_begin = first.range.begin;
445    for bucket in buckets {
446        if running > 0 && running + bucket.nb_blocks > target_rows_per_query {
447            windows.push(TimeRange::new(batch_begin, bucket.range.begin));
448            running = 0;
449            batch_begin = bucket.range.begin;
450        }
451        running += bucket.nb_blocks;
452    }
453    if let Some(last) = buckets.last() {
454        windows.push(TimeRange::new(batch_begin, last.range.end));
455    }
456    windows.into_iter()
457}
458
459/// Renders a `TimeDelta` as arrow-parsable interval text (e.g. `"3600 seconds"`) for use with
460/// DataFusion's `date_bin`. `TimeDelta`'s own `Display` yields ISO-8601 (`PT3600S`), which
461/// `date_bin` cannot parse.
462fn interval_literal(slice: TimeDelta) -> String {
463    format!("{} seconds", slice.num_seconds())
464}
465
466/// Distributes an insert-time-sorted block list over `buckets` (ascending, parallel to the
467/// result). The SQL feeding this is `ORDER BY insert_time, block_id`, so each bucket's blocks are a
468/// contiguous run. A block outside every bucket (committed between the count query and the fetch)
469/// is left for the next run to plan.
470fn split_into_buckets(
471    blocks: Vec<Arc<PartitionSourceBlock>>,
472    buckets: &[PlannedBucket],
473) -> Vec<Vec<Arc<PartitionSourceBlock>>> {
474    let mut split: Vec<Vec<Arc<PartitionSourceBlock>>> = vec![vec![]; buckets.len()];
475    let mut idx = 0usize;
476    for block in blocks {
477        let insert_time = block.block.insert_time;
478        while idx < buckets.len() && buckets[idx].range.end <= insert_time {
479            idx += 1;
480        }
481        if idx < buckets.len() && buckets[idx].range.begin <= insert_time {
482            split[idx].push(block);
483        }
484    }
485    split
486}
487
488/// Runs the `COUNT(*), SUM(nb_objects) ... GROUP BY date_bin(slice, insert_time)` query over
489/// `insert_range`, under `identity_predicate` (the batch queries' own identity filter -- process +
490/// stream-tag, or stream id) so the returned counts match what the batch queries themselves will
491/// return -- the event-time predicate of the MIN/MAX pre-query would not do. Returns one
492/// `(bucket_start, nb_blocks, nb_objects)` entry per non-empty bucket, ascending.
493async fn fetch_bucket_counts(
494    lakehouse: Arc<LakehouseContext>,
495    blocks_view: &BlocksView,
496    partitions: &PartitionCache,
497    insert_range: TimeRange,
498    slice: TimeDelta,
499    identity_predicate: &str,
500) -> Result<Vec<BucketCount>> {
501    let slice_literal = interval_literal(slice);
502    let begin_iso = insert_range.begin.to_rfc3339();
503    let end_iso = insert_range.end.to_rfc3339();
504    let sql = format!(
505        r#"SELECT date_bin('{slice_literal}', insert_time) as bucket,
506                  COUNT(*) as nb_blocks,
507                  SUM(nb_objects) as nb_objects
508             FROM source
509             WHERE {identity_predicate}
510             AND insert_time >= '{begin_iso}'
511             AND insert_time < '{end_iso}'
512             GROUP BY bucket
513             ORDER BY bucket;"#
514    );
515    let filtered = partitions.filter_insert_range(insert_range).partitions;
516    let df = instrument_named!(
517        query_partitions(
518            &lakehouse,
519            blocks_view.get_file_schema(),
520            Arc::new(filtered),
521            &sql,
522        ),
523        "query_partitions"
524    )
525    .await?;
526    let rbs = instrument_named!(df.collect(), "collect_bucket_counts").await?;
527    let mut counts = vec![];
528    for rb in &rbs {
529        let bucket_column: &TimestampNanosecondArray = typed_column_by_name(rb, "bucket")?;
530        let nb_blocks_column: &Int64Array = typed_column_by_name(rb, "nb_blocks")?;
531        let nb_objects_column: &Int64Array = typed_column_by_name(rb, "nb_objects")?;
532        for i in 0..rb.num_rows() {
533            counts.push((
534                DateTime::from_timestamp_nanos(bucket_column.value(i)),
535                nb_blocks_column.value(i),
536                nb_objects_column.value(i),
537            ));
538        }
539    }
540    Ok(counts)
541}
542
543/// The process-variant batch query: block columns plus `stream_id` only -- **no stream-level
544/// column** (`streams.dependencies_metadata`/`objects_metadata`/`tags`/`properties`/`format`) may
545/// be added to the `SELECT` list. Re-adding one would reintroduce the per-row stream-blob-copy
546/// memory hazard the lean projection removes, with no test failing except the projection guard in
547/// `analytics/tests/jit_batch_windows_tests.rs`. `array_has("streams.tags", ...)` stays in the
548/// `WHERE` clause: filtering needs no projection.
549pub fn process_batch_sql(process_id: &Uuid, stream_tag: &str, range: &TimeRange) -> String {
550    let begin_iso = range.begin.to_rfc3339();
551    let end_iso = range.end.to_rfc3339();
552    format!(
553        r#"SELECT block_id, stream_id, process_id, begin_time, end_time, begin_ticks, end_ticks, nb_objects, object_offset, payload_size, insert_time
554             FROM source
555             WHERE process_id = '{process_id}'
556             AND array_has( "streams.tags", '{stream_tag}' )
557             AND insert_time >= '{begin_iso}'
558             AND insert_time < '{end_iso}'
559             ORDER BY insert_time, block_id;"#
560    )
561}
562
563/// Fetches and parses one batch window's worth of process-scoped blocks (`process_batch_sql`),
564/// looking up each block's stream metadata in `stream_metadata` (built once per call to
565/// `generate_process_jit_partitions` by `fetch_stream_metadata_map`) rather than rebuilding it per
566/// row -- this is the lean projection's fetch-and-parse half.
567///
568/// A `stream_id` missing from `stream_metadata` is a hard error: the metadata pre-query and this
569/// query share the same identity predicate and insert range, so it cannot happen unless something
570/// is wrong.
571pub async fn fetch_process_blocks(
572    lakehouse: Arc<LakehouseContext>,
573    blocks_view: &BlocksView,
574    partitions: &PartitionCache,
575    range: &TimeRange,
576    process: Arc<ProcessMetadata>,
577    stream_tag: &str,
578    stream_metadata: &HashMap<Uuid, (Arc<StreamMetadata>, String)>,
579) -> Result<Vec<Arc<PartitionSourceBlock>>> {
580    let filtered = partitions.filter_insert_range(*range).partitions;
581    let sql = process_batch_sql(&process.process_id, stream_tag, range);
582    let df = instrument_named!(
583        query_partitions(
584            &lakehouse,
585            blocks_view.get_file_schema(),
586            Arc::new(filtered),
587            &sql,
588        ),
589        "query_partitions"
590    )
591    .await?;
592    let rbs = instrument_named!(df.collect(), "collect_partition_blocks").await?;
593    let mut blocks = vec![];
594    for rb in &rbs {
595        let stream_id_column = string_column_by_name(rb, "stream_id")?;
596        for ir in 0..rb.num_rows() {
597            let block = block_from_batch_row(rb, ir).with_context(|| "block_from_batch_row")?;
598            let stream_id = Uuid::parse_str(stream_id_column.value(ir)?)
599                .with_context(|| "parsing stream_id")?;
600            let (stream, format) = stream_metadata.get(&stream_id).with_context(|| {
601                format!(
602                    "fetch_process_blocks: missing stream metadata for stream {stream_id} \
603                     (same predicate, same range as the metadata pre-query -- this should not \
604                     happen)"
605                )
606            })?;
607            blocks.push(Arc::new(PartitionSourceBlock {
608                block,
609                stream: stream.clone(),
610                process: process.clone(),
611                format: format.clone(),
612            }));
613        }
614    }
615    Ok(blocks)
616}
617
618/// Pre-query 3 (process variant only): fetches every stream's metadata once for the whole insert
619/// range (stream metadata is immutable after registration), so the batched block queries can look
620/// it up per block instead of rebuilding it. Mirrors `streams_view.rs`'s transform query, and
621/// reads the result with the shared `stream_metadata_from_batch_row` helper -- `format` is kept
622/// alongside in the map since it is not part of `StreamMetadata`.
623async fn fetch_stream_metadata_map(
624    lakehouse: Arc<LakehouseContext>,
625    blocks_view: &BlocksView,
626    partitions: &PartitionCache,
627    insert_range: TimeRange,
628    process: &ProcessMetadata,
629    stream_tag: &str,
630) -> Result<HashMap<Uuid, (Arc<StreamMetadata>, String)>> {
631    let process_id = &process.process_id;
632    let begin_iso = insert_range.begin.to_rfc3339();
633    let end_iso = insert_range.end.to_rfc3339();
634    let sql = format!(
635        r#"SELECT stream_id,
636               first_value("process_id")                    as process_id,
637               first_value("streams.dependencies_metadata") as dependencies_metadata,
638               first_value("streams.objects_metadata")      as objects_metadata,
639               first_value("streams.tags")                  as tags,
640               first_value("streams.properties")            as properties,
641               first_value("streams.format")                as format
642        FROM source
643        WHERE process_id = '{process_id}'
644        AND array_has( "streams.tags", '{stream_tag}' )
645        AND insert_time >= '{begin_iso}'
646        AND insert_time < '{end_iso}'
647        GROUP BY stream_id;"#
648    );
649    let filtered = partitions.filter_insert_range(insert_range).partitions;
650    let df = instrument_named!(
651        query_partitions(
652            &lakehouse,
653            blocks_view.get_file_schema(),
654            Arc::new(filtered),
655            &sql,
656        ),
657        "query_partitions"
658    )
659    .await?;
660    let rbs = instrument_named!(df.collect(), "collect_stream_metadata").await?;
661    let mut map = HashMap::new();
662    for rb in &rbs {
663        let format_column = string_column_by_name(rb, "format")?;
664        for ir in 0..rb.num_rows() {
665            let stream = stream_metadata_from_batch_row(rb, ir)
666                .with_context(|| "stream_metadata_from_batch_row")?;
667            let format = format_column.value(ir)?.to_string();
668            map.insert(stream.stream_id, (Arc::new(stream), format));
669        }
670    }
671    Ok(map)
672}
673
674async fn get_insert_time_range(
675    lakehouse: Arc<LakehouseContext>,
676    blocks_view: &BlocksView,
677    query_time_range: &TimeRange,
678    stream: Arc<StreamMetadata>,
679) -> Result<Option<TimeRange>> {
680    // we would need a PartitionCache built from event time range and then filtered for insert time range
681    let part_provider = LivePartitionProvider::new(lakehouse.lake().db_pool.clone());
682    let partitions = part_provider
683        .fetch(
684            &blocks_view.get_view_set_name(),
685            &blocks_view.get_view_instance_id(),
686            Some(*query_time_range),
687            blocks_view.get_file_schema_hash(),
688        )
689        .await?;
690    let stream_id = &stream.stream_id;
691    let begin_range_iso = query_time_range.begin.to_rfc3339();
692    let end_range_iso = query_time_range.end.to_rfc3339();
693    let sql = format!(
694        r#"SELECT MIN(insert_time) as min_insert_time, MAX(insert_time) as max_insert_time
695        FROM source
696        WHERE stream_id = '{stream_id}'
697        AND begin_time <= '{end_range_iso}'
698        AND end_time >= '{begin_range_iso}';"#
699    );
700    let rbs = query_partitions(
701        &lakehouse,
702        blocks_view.get_file_schema(),
703        Arc::new(partitions),
704        &sql,
705    )
706    .await?
707    .collect()
708    .await?;
709    if rbs.is_empty() {
710        return Ok(None);
711    }
712    if rbs[0].num_rows() == 0 {
713        return Ok(None);
714    }
715    let min_insert_time = get_single_row_primitive_value::<TimestampNanosecondType>(&rbs, 0)?;
716    let max_insert_time = get_single_row_primitive_value::<TimestampNanosecondType>(&rbs, 1)?;
717    Ok(Some(TimeRange::new(
718        DateTime::from_timestamp_nanos(min_insert_time),
719        DateTime::from_timestamp_nanos(max_insert_time),
720    )))
721}
722
723/// Generates a segment of JIT partitions.
724pub async fn generate_stream_jit_partitions_segment(
725    config: &JitPartitionConfig,
726    lakehouse: Arc<LakehouseContext>,
727    blocks_view: &BlocksView,
728    partitions: &PartitionCache,
729    insert_time_range: &TimeRange,
730    stream: Arc<StreamMetadata>,
731    process: Arc<ProcessMetadata>,
732) -> Result<Vec<SourceDataBlocksInMemory>> {
733    let partitions = partitions
734        .filter_insert_range(*insert_time_range)
735        .partitions;
736
737    let stream_id = &stream.stream_id;
738    let begin_range_iso = insert_time_range.begin.to_rfc3339();
739    let end_range_iso = insert_time_range.end.to_rfc3339();
740    let sql = format!(
741        r#"SELECT block_id, stream_id, process_id, begin_time, end_time, begin_ticks, end_ticks, nb_objects, object_offset, payload_size, insert_time, "streams.format"
742             FROM source
743             WHERE stream_id = '{stream_id}'
744             AND insert_time >= '{begin_range_iso}'
745             AND insert_time < '{end_range_iso}'
746             ORDER BY insert_time, block_id;"#
747    );
748
749    let rbs = query_partitions(
750        &lakehouse,
751        blocks_view.get_file_schema(),
752        Arc::new(partitions),
753        &sql,
754    )
755    .await?
756    .collect()
757    .await?;
758
759    let mut blocks = vec![];
760    for rb in rbs {
761        let format_column = string_column_by_name(&rb, "streams.format")?;
762        for ir in 0..rb.num_rows() {
763            let block = block_from_batch_row(&rb, ir).with_context(|| "block_from_batch_row")?;
764            let format = format_column.value(ir)?.to_string();
765            blocks.push(Arc::new(PartitionSourceBlock {
766                block,
767                stream: stream.clone(),
768                process: process.clone(),
769                format,
770            }));
771        }
772    }
773
774    Ok(group_blocks_into_partitions(config, blocks))
775}
776
777/// generate_stream_jit_partitions lists the partitiions that are needed to cover a time span
778/// these partitions may not exist or they could be out of date
779/// Generates JIT partitions for a given time range.
780///
781/// Requires `BucketSizing::Fixed`. Batches its block queries: `batch_windows`, derived from
782/// per-bucket block counts, picks how many insert-time buckets one query covers, and each batch's
783/// rows are then split back into per-bucket runs (`split_into_buckets`) and grouped independently
784/// -- byte-identical to running `generate_stream_jit_partitions_segment` once per bucket, just
785/// fewer, wider queries to get there. `generate_stream_jit_partitions_segment` itself is kept, not
786/// called from here anymore.
787#[span_fn]
788pub async fn generate_stream_jit_partitions(
789    config: &JitPartitionConfig,
790    lakehouse: Arc<LakehouseContext>,
791    blocks_view: &BlocksView,
792    query_time_range: &TimeRange,
793    stream: Arc<StreamMetadata>,
794    process: Arc<ProcessMetadata>,
795) -> Result<Vec<SourceDataBlocksInMemory>> {
796    let BucketSizing::Fixed(slice) = config.bucket_sizing else {
797        anyhow::bail!("generate_stream_jit_partitions requires BucketSizing::Fixed");
798    };
799    let insert_time_range = get_insert_time_range(
800        lakehouse.clone(),
801        blocks_view,
802        query_time_range,
803        stream.clone(),
804    )
805    .await?;
806    if insert_time_range.is_none() {
807        return Ok(vec![]);
808    }
809    let insert_time_range = insert_time_range.with_context(|| "missing insert_time_range")?;
810    let insert_time_range = align_outward(insert_time_range, slice)?;
811    let source_partitions = instrument_named!(
812        PartitionCache::fetch_overlapping_insert_range_for_view(
813            &lakehouse.lake().db_pool,
814            blocks_view.get_view_set_name(),
815            blocks_view.get_view_instance_id(),
816            insert_time_range,
817        ),
818        "fetch_overlapping_insert_range_for_view"
819    )
820    .await?;
821
822    let stream_id = stream.stream_id;
823    let identity_predicate = format!("stream_id = '{stream_id}'");
824    // A single-bucket insert_time_range can only ever produce one batch window, regardless of
825    // the counts, so skip the COUNT(*) round trip entirely in that case.
826    let bucket_counts = if insert_time_range.end - insert_time_range.begin <= slice {
827        vec![]
828    } else {
829        fetch_bucket_counts(
830            lakehouse.clone(),
831            blocks_view,
832            &source_partitions,
833            insert_time_range,
834            slice,
835            &identity_predicate,
836        )
837        .await?
838    };
839    let planned = config.plan(insert_time_range, slice, slice, &bucket_counts);
840
841    let windows: Vec<TimeRange> = batch_windows(&planned, config.target_rows_per_query).collect();
842    debug!(
843        "generate_stream_jit_partitions: stream={stream_id}: derived {} batch window(s) from {} \
844         non-empty bucket(s) (~{} row(s) total, target_rows_per_query={})",
845        windows.len(),
846        planned.len(),
847        planned.iter().map(|b| b.nb_blocks).sum::<i64>(),
848        config.target_rows_per_query
849    );
850
851    let mut partitions = vec![];
852    for batch_range in windows {
853        let filtered = source_partitions
854            .filter_insert_range(batch_range)
855            .partitions;
856        let begin_iso = batch_range.begin.to_rfc3339();
857        let end_iso = batch_range.end.to_rfc3339();
858        let sql = format!(
859            r#"SELECT block_id, stream_id, process_id, begin_time, end_time, begin_ticks, end_ticks, nb_objects, object_offset, payload_size, insert_time, "streams.format"
860                 FROM source
861                 WHERE stream_id = '{stream_id}'
862                 AND insert_time >= '{begin_iso}'
863                 AND insert_time < '{end_iso}'
864                 ORDER BY insert_time, block_id;"#
865        );
866        let df = instrument_named!(
867            query_partitions(
868                &lakehouse,
869                blocks_view.get_file_schema(),
870                Arc::new(filtered),
871                &sql,
872            ),
873            "query_partitions"
874        )
875        .await?;
876        let rbs = instrument_named!(df.collect(), "collect_partition_blocks").await?;
877
878        let mut blocks = vec![];
879        for rb in rbs {
880            let format_column = string_column_by_name(&rb, "streams.format")?;
881            for ir in 0..rb.num_rows() {
882                let block =
883                    block_from_batch_row(&rb, ir).with_context(|| "block_from_batch_row")?;
884                let format = format_column.value(ir)?.to_string();
885                blocks.push(Arc::new(PartitionSourceBlock {
886                    block,
887                    stream: stream.clone(),
888                    process: process.clone(),
889                    format,
890                }));
891            }
892        }
893        let window_buckets: Vec<PlannedBucket> = planned
894            .iter()
895            .filter(|b| b.range.begin >= batch_range.begin && b.range.end <= batch_range.end)
896            .copied()
897            .collect();
898        for bucket_blocks in split_into_buckets(blocks, &window_buckets) {
899            partitions.append(&mut group_blocks_into_partitions(config, bucket_blocks));
900        }
901    }
902    Ok(partitions)
903}
904
905/// generate_process_jit_partitions lists the partitions that are needed to cover a time span for a specific process
906/// these partitions may not exist or they could be out of date
907/// Generates JIT partitions for a given time range filtered by process, grouped by the insert-time
908/// bucket `plan_buckets` assigned them to.
909///
910/// The bucket width comes from `JitPartitionConfig::bucket_sizing`: a fixed slice, or the rung
911/// `select_rung(query_time_range)` picks. Batches its block queries the same way
912/// `generate_stream_jit_partitions` does, and additionally applies the lean projection:
913/// `fetch_stream_metadata_map` fetches every stream's metadata once for the whole insert range,
914/// and each batch's `fetch_process_blocks` call looks it up per block instead of projecting stream
915/// blobs onto every row and rebuilding `StreamMetadata` per row. The grouping call is inlined
916/// into the batch loop below.
917#[span_fn]
918pub async fn generate_process_jit_partitions(
919    config: &JitPartitionConfig,
920    lakehouse: Arc<LakehouseContext>,
921    blocks_view: &BlocksView,
922    query_time_range: &TimeRange,
923    process: Arc<ProcessMetadata>,
924    stream_tag: &str,
925) -> Result<Vec<JitBucket>> {
926    let (rung, finest) = config.rungs(query_time_range);
927    // Get insert time range for all blocks in this process
928    let part_provider = LivePartitionProvider::new(lakehouse.lake().db_pool.clone());
929    let view_set_name = blocks_view.get_view_set_name();
930    let view_instance_id = blocks_view.get_view_instance_id();
931    let partitions = instrument_named!(
932        part_provider.fetch(
933            &view_set_name,
934            &view_instance_id,
935            Some(*query_time_range),
936            blocks_view.get_file_schema_hash(),
937        ),
938        "live_partition_provider_fetch"
939    )
940    .await?;
941
942    let process_id = &process.process_id;
943    let begin_range_iso = query_time_range.begin.to_rfc3339();
944    let end_range_iso = query_time_range.end.to_rfc3339();
945    let sql = format!(
946        r#"SELECT MIN(insert_time) as min_insert_time, MAX(insert_time) as max_insert_time
947        FROM source
948        WHERE process_id = '{process_id}'
949        AND array_has( "streams.tags", '{stream_tag}' )
950        AND begin_time <= '{end_range_iso}'
951        AND end_time >= '{begin_range_iso}';"#
952    );
953
954    let df = instrument_named!(
955        query_partitions(
956            &lakehouse,
957            blocks_view.get_file_schema(),
958            Arc::new(partitions),
959            &sql,
960        ),
961        "query_partitions"
962    )
963    .await?;
964    let rbs = instrument_named!(df.collect(), "collect_insert_time_range").await?;
965
966    if rbs.is_empty() || rbs[0].num_rows() == 0 {
967        return Ok(vec![]);
968    }
969
970    let min_insert_time = get_single_row_primitive_value::<TimestampNanosecondType>(&rbs, 0)?;
971    let max_insert_time = get_single_row_primitive_value::<TimestampNanosecondType>(&rbs, 1)?;
972
973    if min_insert_time == 0 || max_insert_time == 0 {
974        return Ok(vec![]);
975    }
976
977    let insert_time_range = align_outward(
978        TimeRange::new(
979            DateTime::from_timestamp_nanos(min_insert_time),
980            DateTime::from_timestamp_nanos(max_insert_time),
981        ),
982        rung,
983    )?;
984
985    let source_partitions = instrument_named!(
986        PartitionCache::fetch_overlapping_insert_range_for_view(
987            &lakehouse.lake().db_pool,
988            blocks_view.get_view_set_name(),
989            blocks_view.get_view_instance_id(),
990            insert_time_range,
991        ),
992        "fetch_overlapping_insert_range_for_view"
993    )
994    .await?;
995
996    let identity_predicate =
997        format!(r#"process_id = '{process_id}' AND array_has( "streams.tags", '{stream_tag}' )"#);
998    // A single-bucket insert_time_range can only ever produce one batch window, regardless of
999    // the counts, so skip the COUNT(*) round trip entirely in that case.
1000    let bucket_counts = if insert_time_range.end - insert_time_range.begin <= finest {
1001        vec![]
1002    } else {
1003        fetch_bucket_counts(
1004            lakehouse.clone(),
1005            blocks_view,
1006            &source_partitions,
1007            insert_time_range,
1008            finest,
1009            &identity_predicate,
1010        )
1011        .await?
1012    };
1013    let planned = config.plan(insert_time_range, rung, finest, &bucket_counts);
1014
1015    let stream_metadata = fetch_stream_metadata_map(
1016        lakehouse.clone(),
1017        blocks_view,
1018        &source_partitions,
1019        insert_time_range,
1020        &process,
1021        stream_tag,
1022    )
1023    .await?;
1024
1025    let windows: Vec<TimeRange> = batch_windows(&planned, config.target_rows_per_query).collect();
1026    debug!(
1027        "generate_process_jit_partitions: process={process_id} stream_tag={stream_tag}: derived \
1028         {} batch window(s) from {} planned bucket(s) (~{} row(s) total, \
1029         target_rows_per_query={})",
1030        windows.len(),
1031        planned.len(),
1032        planned.iter().map(|b| b.nb_blocks).sum::<i64>(),
1033        config.target_rows_per_query
1034    );
1035
1036    let mut buckets = vec![];
1037    for batch_range in windows {
1038        let blocks = fetch_process_blocks(
1039            lakehouse.clone(),
1040            blocks_view,
1041            &source_partitions,
1042            &batch_range,
1043            process.clone(),
1044            stream_tag,
1045            &stream_metadata,
1046        )
1047        .await?;
1048        let window_buckets: Vec<PlannedBucket> = planned
1049            .iter()
1050            .filter(|b| b.range.begin >= batch_range.begin && b.range.end <= batch_range.end)
1051            .copied()
1052            .collect();
1053        for (planned, bucket_blocks) in window_buckets
1054            .iter()
1055            .zip(split_into_buckets(blocks, &window_buckets))
1056        {
1057            let specs = group_blocks_into_partitions(config, bucket_blocks);
1058            if !specs.is_empty() {
1059                buckets.push(JitBucket {
1060                    planned: *planned,
1061                    specs,
1062                });
1063            }
1064        }
1065    }
1066    Ok(buckets)
1067}
1068
1069/// One `lakehouse_partitions` candidate row, as fetched by `fetch_freshness_candidates`:
1070/// `(begin_insert_time, end_insert_time, file_schema_hash, source_data_hash, file_size)`. Fields
1071/// are `pub` so `analytics/tests/` can build rows directly, without a live database.
1072#[derive(Debug, Clone)]
1073pub struct PartitionFreshnessRow {
1074    pub begin_insert_time: DateTime<Utc>,
1075    pub end_insert_time: DateTime<Utc>,
1076    pub file_schema_hash: Vec<u8>,
1077    pub source_data_hash: Vec<u8>,
1078    pub file_size: i64,
1079}
1080
1081/// Fetches every `lakehouse_partitions` row for `view_meta` whose insert range *inclusively
1082/// overlaps* `range` (`begin_insert_time <= range.end AND end_insert_time >= range.begin`), with
1083/// the narrowing applied in Rust by the caller (`spec_is_up_to_date`, `resolve_bucket_coverage`).
1084pub async fn fetch_freshness_candidates(
1085    pool: &sqlx::PgPool,
1086    view_meta: &ViewMetadata,
1087    range: TimeRange,
1088) -> Result<Vec<PartitionFreshnessRow>> {
1089    let rows = sqlx::query(
1090        "SELECT begin_insert_time, end_insert_time, file_schema_hash, source_data_hash, file_size
1091         FROM lakehouse_partitions
1092         WHERE view_set_name = $1
1093         AND view_instance_id = $2
1094         AND begin_insert_time <= $3
1095         AND end_insert_time >= $4
1096         ;",
1097    )
1098    .bind(&*view_meta.view_set_name)
1099    .bind(&*view_meta.view_instance_id)
1100    .bind(range.end)
1101    .bind(range.begin)
1102    .fetch_all(pool)
1103    .await
1104    .with_context(|| "fetching freshness candidates")?;
1105    rows.into_iter()
1106        .map(|r| {
1107            Ok(PartitionFreshnessRow {
1108                begin_insert_time: r.try_get("begin_insert_time")?,
1109                end_insert_time: r.try_get("end_insert_time")?,
1110                file_schema_hash: r.try_get("file_schema_hash")?,
1111                source_data_hash: r.try_get("source_data_hash")?,
1112                file_size: r.try_get("file_size")?,
1113            })
1114        })
1115        .collect()
1116}
1117
1118/// Filters `candidates` down to the rows with exactly the spec's insert range, then applies the
1119/// `rows.len() == 1` / `file_schema_hash` / exact object-count checks. Used by the
1120/// `BlockOrder::EventTime` views (`thread_spans`/`net_spans`) only: their cut points can move
1121/// between `jit_update` runs, so a later run's spec can be narrower than an already-written
1122/// partition that still overlaps it, and an overlap test would call that stale, wider partition up
1123/// to date and leave it in place forever. Exact equality reports "not up to date" instead, so the
1124/// write falls through to `RetireMatch::Overlap` (see `write_partition.rs`). The `InsertTime` views
1125/// judge freshness per bucket with `resolve_bucket_coverage`.
1126pub fn spec_is_up_to_date(
1127    view_meta: &ViewMetadata,
1128    spec: &SourceDataBlocksInMemory,
1129    candidates: &[PartitionFreshnessRow],
1130) -> Result<bool> {
1131    let (min_insert_time, max_insert_time) =
1132        get_part_insert_time_range(spec).with_context(|| "get_event_time_range")?;
1133    let desc = format!(
1134        "[{}, {}] {} {}",
1135        min_insert_time.to_rfc3339(),
1136        max_insert_time.to_rfc3339(),
1137        *view_meta.view_set_name,
1138        *view_meta.view_instance_id,
1139    );
1140
1141    let matches: Vec<&PartitionFreshnessRow> = candidates
1142        .iter()
1143        .filter(|r| r.begin_insert_time == min_insert_time && r.end_insert_time == max_insert_time)
1144        .collect();
1145    if matches.len() != 1 {
1146        debug!("{desc}: found {} partitions (expected 1)", matches.len());
1147        for (i, r) in matches.iter().enumerate() {
1148            let source_row_count = hash_to_object_count(&r.source_data_hash)?;
1149            debug!(
1150                "{desc}: partition {}: file_schema_hash={:?}, source_rows={}",
1151                i, r.file_schema_hash, source_row_count
1152            );
1153        }
1154        info!("{desc}: found {} partitions", matches.len());
1155        return Ok(false);
1156    }
1157    let r = matches[0];
1158    if r.file_schema_hash != view_meta.file_schema_hash {
1159        // this is dangerous because we could be creating a new partition smaller than the old one, which is not supported.
1160        // let's make sure there is no old data loitering
1161        warn!("{desc}: found matching partition with different file schema");
1162        return Ok(false);
1163    }
1164    let existing_count = hash_to_object_count(&r.source_data_hash)?;
1165    let required_count = hash_to_object_count(&spec.block_ids_hash)?;
1166    if existing_count != required_count {
1167        info!(
1168            "{desc}: existing partition object count differs \
1169             (existing={existing_count}, required={required_count}): creating a new partition"
1170        );
1171        return Ok(false);
1172    }
1173    info!("{desc}: partition up to date");
1174    Ok(true)
1175}
1176
1177/// is_jit_partition_up_to_date compares a partition spec with the partitions that exist to know if it should be recreated
1178/// Checks if a JIT partition is up to date.
1179///
1180/// Fetches the spec's own candidate range (`fetch_freshness_candidates`) and runs the shared
1181/// matcher (`spec_is_up_to_date`) against it. Used by the `BlockOrder::EventTime` callers
1182/// (`net_spans`/`thread_spans`), whose checks stay per-spec, interleaved with retire logic inside
1183/// their own `update_partition`.
1184#[span_fn]
1185pub async fn is_jit_partition_up_to_date(
1186    pool: &sqlx::PgPool,
1187    view_meta: ViewMetadata,
1188    spec: &SourceDataBlocksInMemory,
1189) -> Result<bool> {
1190    let (min_insert_time, max_insert_time) =
1191        get_part_insert_time_range(spec).with_context(|| "get_event_time_range")?;
1192    let candidates = instrument_named!(
1193        fetch_freshness_candidates(
1194            pool,
1195            &view_meta,
1196            TimeRange::new(min_insert_time, max_insert_time),
1197        ),
1198        "sql_select_matching_partitions"
1199    )
1200    .await?;
1201    spec_is_up_to_date(&view_meta, spec, &candidates)
1202}
1203
1204/// What a bucket needs: nothing, or its specs written with the given retire mode.
1205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1206pub enum Coverage {
1207    Covered,
1208    Stale { retire_match: RetireMatch },
1209}
1210
1211/// What to do after a mandatory write lost an overlap race.
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213pub enum ConflictRetry {
1214    /// A concurrent writer already covers the bucket.
1215    Drop,
1216    /// Write again, retiring with this mode.
1217    Retry { retire_match: RetireMatch },
1218}
1219
1220/// A bucket's specs boiled down to what coverage needs.
1221struct BucketFacts {
1222    range: TimeRange,
1223    spec_hulls: Vec<TimeRange>,
1224    hull: TimeRange,
1225    required: i64,
1226}
1227
1228fn bucket_facts(bucket: &JitBucket) -> Result<BucketFacts> {
1229    let mut spec_hulls = vec![];
1230    let mut required = 0;
1231    for spec in &bucket.specs {
1232        spec_hulls
1233            .push(blocks_insert_time_range(&spec.blocks).with_context(|| "empty partition spec")?);
1234        required += hash_to_object_count(&spec.block_ids_hash)?;
1235    }
1236    let begin = spec_hulls
1237        .iter()
1238        .map(|h| h.begin)
1239        .min()
1240        .with_context(|| "bucket without specs")?;
1241    let end = spec_hulls
1242        .iter()
1243        .map(|h| h.end)
1244        .max()
1245        .with_context(|| "bucket without specs")?;
1246    Ok(BucketFacts {
1247        range: bucket.planned.range,
1248        spec_hulls,
1249        hull: TimeRange::new(begin, end),
1250        required,
1251    })
1252}
1253
1254/// How a partition row's insert range relates to a half-open bucket, which depends on who wrote
1255/// the row.
1256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1257pub enum RangeConvention {
1258    /// Block-driven partitions: the row is the inclusive `[min, max]` of its blocks' insert
1259    /// times, which never touches a bucket edge from outside.
1260    BlockHull,
1261    /// Bucket-aligned partitions (SQL views): the row's range is its bucket, so `end` equals the
1262    /// next bucket's `begin`.
1263    Aligned,
1264}
1265
1266impl RangeConvention {
1267    pub fn row_intersects(&self, row: &PartitionFreshnessRow, bucket: TimeRange) -> bool {
1268        match self {
1269            RangeConvention::BlockHull => {
1270                row.begin_insert_time < bucket.end && row.end_insert_time >= bucket.begin
1271            }
1272            RangeConvention::Aligned => {
1273                row.begin_insert_time < bucket.end && row.end_insert_time > bucket.begin
1274            }
1275        }
1276    }
1277
1278    pub fn row_inside(&self, row: &PartitionFreshnessRow, bucket: TimeRange) -> bool {
1279        match self {
1280            RangeConvention::BlockHull => {
1281                row.begin_insert_time >= bucket.begin && row.end_insert_time < bucket.end
1282            }
1283            RangeConvention::Aligned => {
1284                row.begin_insert_time >= bucket.begin && row.end_insert_time <= bucket.end
1285            }
1286        }
1287    }
1288}
1289
1290/// Judges one bucket against `rows` (the rows that count as present). The retire mode of a stale
1291/// verdict is derived from `raw_rows`: a row that the bucket's own write will not retire through
1292/// `Containment` must be retired through `Overlap`, or the insert trips the no-overlap constraint,
1293/// even when `rows` no longer lists it because another write is about to retire it.
1294fn judge_bucket(
1295    facts: &BucketFacts,
1296    view_meta: &ViewMetadata,
1297    rows: &[PartitionFreshnessRow],
1298    raw_rows: &[PartitionFreshnessRow],
1299) -> Result<Coverage> {
1300    let (inner, outer): (Vec<&PartitionFreshnessRow>, Vec<&PartitionFreshnessRow>) = rows
1301        .iter()
1302        .filter(|r| RangeConvention::BlockHull.row_intersects(r, facts.range))
1303        .partition(|r| RangeConvention::BlockHull.row_inside(r, facts.range));
1304    let schema_ok = |r: &&PartitionFreshnessRow| r.file_schema_hash == view_meta.file_schema_hash;
1305    let covered = if outer.is_empty() {
1306        // Fine-or-equal rungs: the bucket's own rows must cover every required object. A surplus
1307        // is harmless: retention deletes blocks before it retires the rows that hold them, so a
1308        // surviving row can count more objects than the blocks that remain. Rewriting would
1309        // trip the no-overlap constraint, because the retire misses the row (it lies outside the
1310        // remaining specs' hull).
1311        let mut inner_count = 0;
1312        for r in &inner {
1313            inner_count += hash_to_object_count(&r.source_data_hash)?;
1314        }
1315        !inner.is_empty() && inner_count >= facts.required && inner.iter().all(schema_ok)
1316    } else if inner.is_empty() && outer.len() == 1 {
1317        // Coarser rung: one row written while its bucket was closed, so it holds everything.
1318        let r = outer[0];
1319        r.begin_insert_time <= facts.hull.begin
1320            && r.end_insert_time >= facts.hull.end
1321            && schema_ok(&r)
1322            && hash_to_object_count(&r.source_data_hash)? >= facts.required
1323    } else {
1324        false
1325    };
1326    if covered {
1327        return Ok(Coverage::Covered);
1328    }
1329    let raw_has_outer = raw_rows.iter().any(|r| {
1330        RangeConvention::BlockHull.row_intersects(r, facts.range)
1331            && !RangeConvention::BlockHull.row_inside(r, facts.range)
1332    });
1333    Ok(Coverage::Stale {
1334        retire_match: if raw_has_outer {
1335            RetireMatch::Overlap
1336        } else {
1337            RetireMatch::Containment
1338        },
1339    })
1340}
1341
1342/// Judges every bucket against the candidate rows and cascades: writing a stale bucket retires
1343/// rows (those inside its spec hulls for `Containment`, those intersecting them for `Overlap`),
1344/// which can strip coverage from a bucket that relied on one of them. Verdicts only move from
1345/// covered to stale, so the loop ends in at most `buckets.len()` passes, and the query that
1346/// triggers the writes never reads a bucket its own writes just emptied.
1347///
1348/// `buckets` are ascending and non-overlapping; returns verdicts parallel to them. Does no I/O.
1349pub fn resolve_bucket_coverage(
1350    buckets: &[JitBucket],
1351    view_meta: &ViewMetadata,
1352    candidates: &[PartitionFreshnessRow],
1353) -> Result<Vec<Coverage>> {
1354    let facts: Vec<BucketFacts> = buckets.iter().map(bucket_facts).collect::<Result<_>>()?;
1355    let mut verdicts: Vec<Coverage> = facts
1356        .iter()
1357        .map(|f| judge_bucket(f, view_meta, candidates, candidates))
1358        .collect::<Result<_>>()?;
1359    loop {
1360        let mut doomed = vec![false; candidates.len()];
1361        for (f, verdict) in facts.iter().zip(&verdicts) {
1362            let Coverage::Stale { retire_match } = verdict else {
1363                continue;
1364            };
1365            for hull in &f.spec_hulls {
1366                for (row, doomed) in candidates.iter().zip(doomed.iter_mut()) {
1367                    *doomed |= match retire_match {
1368                        RetireMatch::Containment => {
1369                            row.begin_insert_time >= hull.begin && row.end_insert_time <= hull.end
1370                        }
1371                        RetireMatch::Overlap => {
1372                            row.begin_insert_time <= hull.end && row.end_insert_time >= hull.begin
1373                        }
1374                    };
1375                }
1376            }
1377        }
1378        let remaining: Vec<PartitionFreshnessRow> = candidates
1379            .iter()
1380            .zip(&doomed)
1381            .filter(|(_, doomed)| !**doomed)
1382            .map(|(row, _)| row.clone())
1383            .collect();
1384        let mut changed = false;
1385        for (f, verdict) in facts.iter().zip(verdicts.iter_mut()) {
1386            if *verdict == Coverage::Covered {
1387                let rejudged = judge_bucket(f, view_meta, &remaining, candidates)?;
1388                if rejudged != Coverage::Covered {
1389                    *verdict = rejudged;
1390                    changed = true;
1391                }
1392            }
1393        }
1394        if !changed {
1395            return Ok(verdicts);
1396        }
1397    }
1398}
1399
1400/// Decides what to do with a bucket whose write hit the no-overlap constraint, from the rows
1401/// fetched again afterwards. A concurrent writer that committed after the first retire SELECT is
1402/// listed in `refetched`, so the retry's retire mode is derived from it.
1403pub fn decide_conflict_retry(
1404    bucket: &JitBucket,
1405    view_meta: &ViewMetadata,
1406    refetched: &[PartitionFreshnessRow],
1407) -> Result<ConflictRetry> {
1408    let facts = bucket_facts(bucket)?;
1409    Ok(
1410        match judge_bucket(&facts, view_meta, refetched, refetched)? {
1411            Coverage::Covered => ConflictRetry::Drop,
1412            Coverage::Stale { retire_match } => ConflictRetry::Retry { retire_match },
1413        },
1414    )
1415}
1416
1417#[allow(clippy::too_many_arguments)]
1418async fn write_spec_with_conflict_retry(
1419    lakehouse: &LakehouseContext,
1420    view: &dyn View,
1421    view_meta: &ViewMetadata,
1422    bucket: &JitBucket,
1423    spec: &SourceDataBlocksInMemory,
1424    retire_match: RetireMatch,
1425    same_run_ranges: &[TimeRange],
1426    block_processors: &Arc<BlockProcessorMap>,
1427) -> Result<()> {
1428    let attempt = |retire_match: RetireMatch| {
1429        write_partition_from_blocks(
1430            lakehouse.lake().clone(),
1431            view_meta.clone(),
1432            view.get_file_schema(),
1433            spec.clone(),
1434            block_processors.clone(),
1435            retire_match,
1436            same_run_ranges.to_vec(),
1437        )
1438    };
1439    let err = match attempt(retire_match).await {
1440        Ok(()) => return Ok(()),
1441        Err(err) => err,
1442    };
1443    if !err
1444        .chain()
1445        .any(|e| e.downcast_ref::<PartitionOverlapConflict>().is_some())
1446    {
1447        return Err(err);
1448    }
1449    let facts = bucket_facts(bucket)?;
1450    let refetched = fetch_freshness_candidates(
1451        &lakehouse.lake().db_pool,
1452        view_meta,
1453        TimeRange::new(
1454            facts.range.begin.min(facts.hull.begin),
1455            facts.range.end.max(facts.hull.end),
1456        ),
1457    )
1458    .await?;
1459    match decide_conflict_retry(bucket, view_meta, &refetched)? {
1460        ConflictRetry::Drop => {
1461            info!(
1462                "bucket [{}, {}) is now covered by a concurrent writer: dropping write",
1463                facts.range.begin.to_rfc3339(),
1464                facts.range.end.to_rfc3339()
1465            );
1466            Ok(())
1467        }
1468        ConflictRetry::Retry { retire_match } => attempt(retire_match).await,
1469    }
1470}
1471
1472/// Brings an `InsertTime` JIT view of one process up to date for `query_range`: sizes buckets from
1473/// the range, writes the stale ones, then promotes closed history to the range's rung.
1474///
1475/// `view` is owned because promotion hands it to `create_merged_partition`.
1476#[span_fn]
1477pub async fn update_insert_time_jit_view(
1478    lakehouse: Arc<LakehouseContext>,
1479    view: Arc<dyn View>,
1480    process: Arc<ProcessMetadata>,
1481    query_range: TimeRange,
1482    stream_tag: &str,
1483    block_processors: Arc<BlockProcessorMap>,
1484) -> Result<()> {
1485    let config = JitPartitionConfig::default();
1486    let query_rung = select_rung(query_range);
1487    let blocks_view = BlocksView::new(lakehouse.default_audience())?;
1488    let buckets = generate_process_jit_partitions(
1489        &config,
1490        lakehouse.clone(),
1491        &blocks_view,
1492        &query_range,
1493        process,
1494        stream_tag,
1495    )
1496    .await
1497    .with_context(|| "generate_process_jit_partitions")?;
1498    let (Some(first), Some(last)) = (buckets.first(), buckets.last()) else {
1499        return Ok(());
1500    };
1501    let view_meta = view.get_meta();
1502    let candidates = instrument_named!(
1503        fetch_freshness_candidates(
1504            &lakehouse.lake().db_pool,
1505            &view_meta,
1506            TimeRange::new(first.planned.range.begin, last.planned.range.end),
1507        ),
1508        "sql_select_freshness_candidates"
1509    )
1510    .await?;
1511    let verdicts = resolve_bucket_coverage(&buckets, &view_meta, &candidates)
1512        .with_context(|| "resolve_bucket_coverage")?;
1513
1514    // Insert ranges this run already handled, so a later `Overlap` retire never retires a row of
1515    // this same run -- see `RetireMatch::Overlap`'s docs.
1516    let mut same_run_ranges: Vec<TimeRange> = vec![];
1517    for (bucket, verdict) in buckets.iter().zip(&verdicts) {
1518        for spec in &bucket.specs {
1519            if let Coverage::Stale { retire_match } = verdict {
1520                write_spec_with_conflict_retry(
1521                    &lakehouse,
1522                    view.as_ref(),
1523                    &view_meta,
1524                    bucket,
1525                    spec,
1526                    *retire_match,
1527                    &same_run_ranges,
1528                    &block_processors,
1529                )
1530                .await
1531                .with_context(|| "write_partition_from_blocks")?;
1532            }
1533            same_run_ranges.push(blocks_insert_time_range(&spec.blocks)?);
1534        }
1535    }
1536
1537    let targets = promotion_candidates(
1538        &buckets,
1539        &verdicts,
1540        &candidates,
1541        query_rung,
1542        config.max_nb_objects,
1543    );
1544    promote_closed_buckets(
1545        lakehouse,
1546        view,
1547        targets,
1548        config.max_nb_objects,
1549        i64::MAX,
1550        RangeConvention::BlockHull,
1551    )
1552    .await;
1553    Ok(())
1554}
1555
1556/// get_event_time_range returns the time range covered by a partition spec
1557/// Returns the insert time range covered by a partition spec.
1558fn get_part_insert_time_range(
1559    spec: &SourceDataBlocksInMemory,
1560) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
1561    let range = blocks_insert_time_range(&spec.blocks)
1562        .with_context(|| "empty partition should not exist")?;
1563    Ok((range.begin, range.end))
1564}
1565
1566/// Writes a partition from a set of blocks, retiring the rows `retire_match` selects (see
1567/// `RetireMatch`; `same_run_ranges` is only meaningful for `Overlap`).
1568///
1569/// `block_processors` keys per-block dispatch on the source block's `format`;
1570/// see `BlockPartitionSpec::write` for the unknown-format behavior.
1571#[span_fn]
1572pub async fn write_partition_from_blocks(
1573    lake: Arc<DataLakeConnection>,
1574    view_metadata: ViewMetadata,
1575    schema: Arc<Schema>,
1576    source_data: SourceDataBlocksInMemory,
1577    block_processors: Arc<BlockProcessorMap>,
1578    retire_match: RetireMatch,
1579    same_run_ranges: Vec<TimeRange>,
1580) -> Result<()> {
1581    if source_data.blocks.is_empty() {
1582        anyhow::bail!("empty partition spec");
1583    }
1584    let insert_range = blocks_insert_time_range(&source_data.blocks)
1585        .with_context(|| "blocks_insert_time_range")?;
1586    let block_spec = BlockPartitionSpec {
1587        view_metadata,
1588        schema,
1589        insert_range,
1590        source_data: Arc::new(source_data),
1591        block_processors,
1592        retire_match,
1593        same_run_ranges,
1594    };
1595    let null_response_writer = Arc::new(ResponseWriter::new(None));
1596    block_spec
1597        .write(lake, null_response_writer)
1598        .await
1599        .with_context(|| "block_spec.write")?;
1600    Ok(())
1601}