Skip to main content

micromegas_analytics/lakehouse/
on_demand_jit.rs

1//! Query-driven materialization of on-demand SQL views (DDL views with no `update_group`).
2//!
3//! A query over `query_range` fills and refreshes the partitions covering that range, so nothing
4//! is materialized for ranges nobody reads. The range is cut along the bucket ladder (see
5//! `partition_ladder`), each bucket's freshness is probed with the view's own authored
6//! `count_src_query`, and the stale ones are rewritten with its `extract_query`.
7//!
8//! No partition is built from more source data than the view's byte cap (`max_jit_src_data`),
9//! except at the finest rung: a stale unit whose source bytes exceed the cap is rewritten as finer
10//! ladder buckets, committed together with the retire of the unit's rows, and promotion never
11//! merges rows into a partition that would exceed the cap in bytes or in source bytes.
12//!
13//! A bucket grows into a [`Unit`] that contains every partition row it intersects (an earlier
14//! query at a coarser rung, a promotion, or rows left by the daemon before a view was converted),
15//! so a write's containment retire always replaces everything it overlaps and the verdict of a
16//! unit never depends on another unit.
17
18use super::{
19    jit_partitions::{
20        BucketSizing, JitPartitionConfig, PartitionFreshnessRow, RangeConvention,
21        fetch_freshness_candidates,
22    },
23    jit_promotion::{PromotionTarget, is_promotable, promote_closed_buckets},
24    lakehouse_context::LakehouseContext,
25    partition::Partition,
26    partition_cache::PartitionCache,
27    partition_ladder::{
28        BytesFn, LADDER, PlannedBucket, align_outward, finer_rung, plan_by_source_bytes,
29        plan_dense_buckets, select_rung,
30    },
31    partition_source_data::hash_to_object_count,
32    view::{PartitionSpec, View, ViewMetadata},
33    write_partition::{PartitionOverlapConflict, delete_if_orphan, insert_partitions_replacing},
34};
35use crate::{response_writer::ResponseWriter, time::TimeRange};
36use anyhow::{Context, Result};
37use chrono::{DurationRound, TimeDelta, Utc};
38use micromegas_tracing::prelude::*;
39use std::sync::Arc;
40
41/// A planned bucket, grown until it contains every partition row it intersects, and coalesced
42/// with the units it came to overlap.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Unit {
45    pub range: TimeRange,
46    /// Indices into the rows the unit was planned from. All of them lie fully inside `range`.
47    pub rows: Vec<usize>,
48    /// Every bucket the unit absorbed was closed.
49    pub closed: bool,
50    /// `Some(rung)` when the unit is exactly one planned bucket, not grown.
51    pub planned_rung: Option<TimeDelta>,
52}
53
54/// Whether a unit's rows already hold what its probe counted.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum UnitVerdict {
57    Covered,
58    Stale,
59}
60
61struct GrownBucket {
62    range: TimeRange,
63    original: TimeRange,
64    rung: TimeDelta,
65    closed: bool,
66    nb_buckets: usize,
67}
68
69/// Grows each planned bucket until it contains every row that intersects it, then coalesces the
70/// units that came to overlap. `planned` is ascending and non-overlapping. Rows are half-open
71/// against the unit (`Aligned`): SQL partitions touch at bucket edges, and a neighbor that merely
72/// touches is not absorbed.
73pub fn plan_units(planned: &[PlannedBucket], rows: &[PartitionFreshnessRow]) -> Vec<Unit> {
74    let convention = RangeConvention::Aligned;
75    let mut grown: Vec<GrownBucket> = planned
76        .iter()
77        .map(|bucket| {
78            let mut range = bucket.range;
79            loop {
80                let mut next = range;
81                for row in rows.iter().filter(|r| convention.row_intersects(r, range)) {
82                    next.begin = next.begin.min(row.begin_insert_time);
83                    next.end = next.end.max(row.end_insert_time);
84                }
85                if next == range {
86                    break;
87                }
88                range = next;
89            }
90            GrownBucket {
91                range,
92                original: bucket.range,
93                rung: bucket.rung,
94                closed: bucket.closed,
95                nb_buckets: 1,
96            }
97        })
98        .collect();
99    grown.sort_by_key(|g| g.range.begin);
100    let mut merged: Vec<GrownBucket> = vec![];
101    for g in grown {
102        match merged.last_mut() {
103            Some(last) if g.range.begin < last.range.end => {
104                last.range.end = last.range.end.max(g.range.end);
105                last.closed &= g.closed;
106                last.nb_buckets += g.nb_buckets;
107            }
108            _ => merged.push(g),
109        }
110    }
111    merged
112        .into_iter()
113        .map(|g| Unit {
114            rows: rows
115                .iter()
116                .enumerate()
117                .filter(|(_, r)| convention.row_intersects(r, g.range))
118                .map(|(i, _)| i)
119                .collect(),
120            planned_rung: (g.nb_buckets == 1 && g.range == g.original).then_some(g.rung),
121            closed: g.closed,
122            range: g.range,
123        })
124        .collect()
125}
126
127/// `Covered` when the unit has rows, every row was written with the view's current schema, and
128/// the rows' summed `source_data_hash` equals the count the probe returned. This is the
129/// maintenance daemon's freshness rule (equality, summed), so a definition gets the same verdicts
130/// under either writer.
131pub fn judge_unit(
132    unit: &Unit,
133    rows: &[PartitionFreshnessRow],
134    file_schema_hash: &[u8],
135    probed_count: i64,
136) -> UnitVerdict {
137    if unit.rows.is_empty() {
138        return UnitVerdict::Stale;
139    }
140    let mut sum: i64 = 0;
141    for &index in &unit.rows {
142        let row = &rows[index];
143        if row.file_schema_hash != file_schema_hash {
144            return UnitVerdict::Stale;
145        }
146        match hash_to_object_count(&row.source_data_hash) {
147            Ok(count) => sum += count,
148            Err(_) => return UnitVerdict::Stale,
149        }
150    }
151    if sum == probed_count {
152        UnitVerdict::Covered
153    } else {
154        UnitVerdict::Stale
155    }
156}
157
158/// Whether `partition` belongs to one of `sources`: same view set, instance and file schema.
159fn is_source_partition(partition: &Partition, sources: &[ViewMetadata]) -> bool {
160    sources.iter().any(|s| {
161        partition.view_metadata.view_set_name == s.view_set_name
162            && partition.view_metadata.view_instance_id == s.view_instance_id
163            && partition.view_metadata.file_schema_hash == s.file_schema_hash
164    })
165}
166
167/// Bytes of source data an extract over `range` reads: the `file_size` of the `sources`'
168/// partitions, each prorated by the share of its insert range that lies in `range`. A zero-width
169/// partition counts whole when its insert time is in `[begin, end)`. Prorating assumes data is
170/// spread evenly in insert time, which is good enough for a cap: extracts filter their sources by
171/// insert time. Partitions of other views, or of a source under another file schema, count for
172/// nothing.
173pub fn source_bytes(partitions: &[Partition], sources: &[ViewMetadata], range: TimeRange) -> i64 {
174    let mut total: i64 = 0;
175    for partition in partitions {
176        if !is_source_partition(partition, sources) {
177            continue;
178        }
179        let (begin, end) = (partition.begin_insert_time(), partition.end_insert_time());
180        if begin == end {
181            if range.begin <= begin && begin < range.end {
182                total = total.saturating_add(partition.file_size);
183            }
184            continue;
185        }
186        let overlap = end.min(range.end) - begin.max(range.begin);
187        if overlap <= TimeDelta::zero() {
188            continue;
189        }
190        let width = (end - begin).num_microseconds().unwrap_or(i64::MAX).max(1);
191        let shared = overlap.num_microseconds().unwrap_or(i64::MAX);
192        let prorated = i128::from(partition.file_size) * i128::from(shared) / i128::from(width);
193        total = total.saturating_add(i64::try_from(prorated).unwrap_or(i64::MAX));
194    }
195    total
196}
197
198/// Restricts a source snapshot to the partitions of `sources`, so repeated `source_bytes` calls
199/// don't scan every view's partitions.
200fn source_partitions(cache: &PartitionCache, sources: &[ViewMetadata]) -> Vec<Partition> {
201    cache
202        .partitions
203        .iter()
204        .filter(|p| is_source_partition(p, sources))
205        .cloned()
206        .collect()
207}
208
209/// What to do with a unit judged stale.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub enum StaleUnitPlan {
212    /// Write the unit as one partition.
213    WriteWhole,
214    /// Replace every row of `range` (the unit's) with partitions over `leaves`.
215    Replace {
216        range: TimeRange,
217        leaves: Vec<PlannedBucket>,
218    },
219}
220
221/// A unit within the byte cap is written whole. Otherwise it is rebuilt as the leaves
222/// `plan_by_source_bytes` picks, which replace the unit's rows in one commit, however coarse those
223/// rows were. A unit that is itself one finest-rung bucket has nothing to split, so it is written
224/// whole whatever its size.
225pub fn plan_stale_unit(unit: &Unit, bytes: BytesFn<'_>, cap: i64) -> StaleUnitPlan {
226    if bytes(unit.range) <= cap {
227        return StaleUnitPlan::WriteWhole;
228    }
229    let leaves: Vec<PlannedBucket> = plan_by_source_bytes(unit.range, bytes, cap)
230        .into_iter()
231        .map(|leaf| PlannedBucket {
232            closed: unit.closed,
233            ..leaf
234        })
235        .collect();
236    match leaves.as_slice() {
237        [only] if only.range == unit.range => StaleUnitPlan::WriteWhole,
238        _ => StaleUnitPlan::Replace {
239            range: unit.range,
240            leaves,
241        },
242    }
243}
244
245/// Picks what to merge within one covered, closed bucket: the whole of `range` when `rows` merge
246/// within the byte cap and a rebuild of `range` would read at most `cap` source bytes. Otherwise,
247/// when the rows would merge but a cap is exceeded, each child bucket of the next finer rung gets
248/// the same treatment over the rows lying inside it. A child that a row straddles is skipped,
249/// since the row cannot be split. With fewer than two rows there is nothing to merge.
250pub fn split_promotion(
251    range: TimeRange,
252    rung: TimeDelta,
253    rows: &[&PartitionFreshnessRow],
254    bytes: BytesFn<'_>,
255    cap: i64,
256) -> Vec<PromotionTarget> {
257    if rows.len() < 2 || !is_promotable(rows, i64::MAX, i64::MAX) {
258        return vec![];
259    }
260    if is_promotable(rows, i64::MAX, cap) && bytes(range) <= cap {
261        return vec![PromotionTarget {
262            bucket: range,
263            inputs: rows.iter().map(|r| (*r).clone()).collect(),
264        }];
265    }
266    let Some(finer) = finer_rung(rung) else {
267        return vec![];
268    };
269    let convention = RangeConvention::Aligned;
270    let mut targets = vec![];
271    let mut begin = range.begin;
272    while begin < range.end {
273        let child = TimeRange::new(begin, begin + finer);
274        begin += finer;
275        if rows
276            .iter()
277            .any(|r| convention.row_intersects(r, child) && !convention.row_inside(r, child))
278        {
279            continue;
280        }
281        let inside: Vec<&PartitionFreshnessRow> = rows
282            .iter()
283            .filter(|r| convention.row_inside(r, child))
284            .copied()
285            .collect();
286        targets.extend(split_promotion(child, finer, &inside, bytes, cap));
287    }
288    targets
289}
290
291/// Picks the units to promote: covered, closed, exactly one planned bucket at the query's `rung`
292/// (not grown). `split_promotion` then decides what to merge within each, under the byte cap.
293/// Pure, like `promotion_candidates`.
294pub fn promotion_targets(
295    units: &[Unit],
296    rows: &[PartitionFreshnessRow],
297    verdicts: &[UnitVerdict],
298    rung: TimeDelta,
299    bytes: BytesFn<'_>,
300    cap: i64,
301) -> Vec<PromotionTarget> {
302    let mut targets = vec![];
303    for (unit, verdict) in units.iter().zip(verdicts) {
304        if *verdict != UnitVerdict::Covered || !unit.closed || unit.planned_rung != Some(rung) {
305            continue;
306        }
307        let inputs: Vec<&PartitionFreshnessRow> = unit.rows.iter().map(|&i| &rows[i]).collect();
308        targets.extend(split_promotion(unit.range, rung, &inputs, bytes, cap));
309    }
310    targets
311}
312
313fn hull(a: TimeRange, b: TimeRange) -> TimeRange {
314    TimeRange::new(a.begin.min(b.begin), a.end.max(b.end))
315}
316
317fn contains(outer: TimeRange, inner: TimeRange) -> bool {
318    outer.begin <= inner.begin && outer.end >= inner.end
319}
320
321/// Fetches the rows over `start`, plans the units and, as long as a unit grew past the fetched
322/// range, fetches again over the grown range. Rows written under a previous schema can overlap
323/// rows written under the current one, because the no-overlap constraint is per schema hash, so
324/// growth can chain.
325async fn settle_units(
326    pool: &sqlx::PgPool,
327    view_meta: &ViewMetadata,
328    planned: &[PlannedBucket],
329    start: TimeRange,
330) -> Result<(Vec<Unit>, Vec<PartitionFreshnessRow>)> {
331    let mut fetch_range = start;
332    loop {
333        let rows = fetch_freshness_candidates(pool, view_meta, fetch_range).await?;
334        let units = plan_units(planned, &rows);
335        let units_hull = units.iter().map(|u| u.range).reduce(hull);
336        match units_hull {
337            Some(h) if !contains(fetch_range, h) => fetch_range = hull(fetch_range, h),
338            _ => return Ok((units, rows)),
339        }
340    }
341}
342
343/// Brings the on-demand sources up to date over `range`, then snapshots every view's partitions
344/// over it. The extract and count sessions read the snapshot and cannot refresh upstream
345/// themselves.
346async fn snapshot_sources(
347    lakehouse: &Arc<LakehouseContext>,
348    on_demand_sources: &[Arc<dyn View>],
349    range: TimeRange,
350) -> Result<Arc<PartitionCache>> {
351    for source in on_demand_sources {
352        source
353            .jit_update(lakehouse.clone(), Some(range))
354            .await
355            .with_context(|| {
356                format!("refreshing on-demand source {}", source.get_view_set_name())
357            })?;
358    }
359    Ok(Arc::new(
360        PartitionCache::fetch_overlapping_insert_range(&lakehouse.lake().db_pool, range).await?,
361    ))
362}
363
364fn is_overlap_conflict(err: &anyhow::Error) -> bool {
365    err.chain()
366        .any(|e| e.downcast_ref::<PartitionOverlapConflict>().is_some())
367}
368
369fn record_outcome(outcome: &'static str) {
370    imetric!("on_demand_jit", "count", outcome = outcome, 1_u64);
371}
372
373/// Probes `unit` with the view's authored count query and judges it. The returned spec can write
374/// exactly `unit.range`.
375async fn probe_unit(
376    lakehouse: &Arc<LakehouseContext>,
377    view: &Arc<dyn View>,
378    view_meta: &ViewMetadata,
379    cache: &Arc<PartitionCache>,
380    unit: &Unit,
381    rows: &[PartitionFreshnessRow],
382) -> Result<(Arc<dyn super::view::PartitionSpec>, UnitVerdict)> {
383    let spec = view
384        .make_batch_partition_spec(lakehouse.clone(), cache.clone(), unit.range)
385        .await
386        .with_context(|| "make_batch_partition_spec")?;
387    let probed = hash_to_object_count(&spec.get_source_data_hash())?;
388    let verdict = judge_unit(unit, rows, &view_meta.file_schema_hash, probed);
389    Ok((spec, verdict))
390}
391
392/// Writes a stale unit as `plan` says. A whole write retires and inserts in one transaction. A
393/// replacement writes every leaf's file unregistered, one at a time, then commits the retire of
394/// the unit's rows and all the leaves together, so readers see either the old rows or the whole
395/// replacement. A leaf over the cap (only possible at the finest rung) is logged and counted as
396/// `over_cap`, in addition to the `written` outcome.
397#[allow(clippy::too_many_arguments)]
398async fn write_stale_unit(
399    lakehouse: &Arc<LakehouseContext>,
400    view: &Arc<dyn View>,
401    view_meta: &ViewMetadata,
402    cache: &Arc<PartitionCache>,
403    unit: &Unit,
404    whole: &Arc<dyn PartitionSpec>,
405    plan: &StaleUnitPlan,
406    bytes: BytesFn<'_>,
407    cap: i64,
408) -> Result<()> {
409    let lake = lakehouse.lake();
410    let logger: Arc<dyn crate::response_writer::Logger> = Arc::new(ResponseWriter::new(None));
411    let over_cap = |range: TimeRange| {
412        let nb_bytes = bytes(range);
413        if nb_bytes > cap {
414            warn!(
415                "on-demand partition [{}, {}) reads {nb_bytes} source bytes, over the cap of {cap}, \
416                 and cannot be split further",
417                range.begin.to_rfc3339(),
418                range.end.to_rfc3339()
419            );
420            record_outcome("over_cap");
421        }
422    };
423    match plan {
424        StaleUnitPlan::WriteWhole => {
425            whole.write(lake.clone(), logger).await?;
426            over_cap(unit.range);
427        }
428        StaleUnitPlan::Replace { range, leaves } => {
429            let mut written: Vec<Partition> = Vec::with_capacity(leaves.len());
430            for leaf in leaves {
431                let result = async {
432                    let spec = view
433                        .make_batch_partition_spec(lakehouse.clone(), cache.clone(), leaf.range)
434                        .await
435                        .with_context(|| "make_batch_partition_spec")?;
436                    spec.write_file(lake.clone(), logger.clone()).await
437                }
438                .await;
439                match result {
440                    Ok(partition) => written.push(partition),
441                    Err(e) => {
442                        // Unregistered files are in no `temporary_files` row, nothing else will
443                        // reclaim them.
444                        for file_path in written.iter().filter_map(|p| p.file_path.as_ref()) {
445                            if let Err(cleanup_err) = delete_if_orphan(lake, file_path).await {
446                                warn!("delete_if_orphan failed for {file_path}: {cleanup_err}");
447                            }
448                        }
449                        return Err(e).with_context(|| {
450                            format!(
451                                "writing on-demand leaf [{}, {})",
452                                leaf.range.begin.to_rfc3339(),
453                                leaf.range.end.to_rfc3339()
454                            )
455                        });
456                    }
457                }
458            }
459            insert_partitions_replacing(lake, view_meta, *range, &written, logger).await?;
460            for partition in &written {
461                if let Some(file_path) = &partition.file_path {
462                    lake.warm_object(file_path, partition.file_size);
463                }
464            }
465            for leaf in leaves {
466                over_cap(leaf.range);
467            }
468        }
469    }
470    record_outcome("written");
471    Ok(())
472}
473
474/// A concurrent reader wrote an overlapping unit first. Looks at the rows again, recomputes the
475/// unit (it may have grown), and either drops the write because the concurrent one already
476/// covers it or writes once more, through the same byte-cap rule as the first attempt. A second
477/// conflict is an error.
478#[allow(clippy::too_many_arguments)]
479async fn resolve_conflict(
480    lakehouse: &Arc<LakehouseContext>,
481    view: &Arc<dyn View>,
482    on_demand_sources: &[Arc<dyn View>],
483    extract_sources: &[ViewMetadata],
484    max_jit_src_bytes: i64,
485    view_meta: &ViewMetadata,
486    unit: &Unit,
487    rung: TimeDelta,
488    snapshot_range: &mut TimeRange,
489    cache: &mut Arc<PartitionCache>,
490) -> Result<()> {
491    let pool = &lakehouse.lake().db_pool;
492    let pseudo_bucket = PlannedBucket {
493        range: unit.range,
494        rung: unit.planned_rung.unwrap_or(rung),
495        closed: unit.closed,
496        nb_blocks: 0,
497        nb_objects: 0,
498    };
499    let (units, rows) = settle_units(pool, view_meta, &[pseudo_bucket], unit.range).await?;
500    let [grown] = units.as_slice() else {
501        anyhow::bail!(
502            "recomputing a conflicted unit yielded {} units",
503            units.len()
504        );
505    };
506    if !contains(*snapshot_range, grown.range) {
507        *snapshot_range = hull(*snapshot_range, grown.range);
508        *cache = snapshot_sources(lakehouse, on_demand_sources, *snapshot_range).await?;
509    }
510    let (spec, verdict) = probe_unit(lakehouse, view, view_meta, cache, grown, &rows).await?;
511    match verdict {
512        UnitVerdict::Covered => {
513            info!(
514                "on-demand unit [{}, {}) is now covered by a concurrent writer: dropping write",
515                unit.range.begin.to_rfc3339(),
516                unit.range.end.to_rfc3339()
517            );
518            record_outcome("conflict_dropped");
519        }
520        UnitVerdict::Stale => {
521            let partitions = source_partitions(cache, extract_sources);
522            let bytes = |range: TimeRange| source_bytes(&partitions, extract_sources, range);
523            let plan = plan_stale_unit(grown, &bytes, max_jit_src_bytes);
524            write_stale_unit(
525                lakehouse,
526                view,
527                view_meta,
528                cache,
529                grown,
530                &spec,
531                &plan,
532                &bytes,
533                max_jit_src_bytes,
534            )
535            .await
536            .with_context(|| "writing the on-demand unit after a conflict")?;
537        }
538    }
539    Ok(())
540}
541
542fn default_grace() -> TimeDelta {
543    match JitPartitionConfig::default().bucket_sizing {
544        BucketSizing::RangeDriven { grace } => grace,
545        BucketSizing::Fixed(_) => TimeDelta::zero(),
546    }
547}
548
549/// Brings an on-demand view up to date for `query_range`: sizes buckets from the range, probes
550/// each one, rewrites the stale ones, then promotes closed history to the range's rung.
551///
552/// `on_demand_sources` are refreshed over the range the units cover before source partitions are
553/// snapshotted. `extract_sources` are the views the extract query scans, whose snapshotted
554/// partitions measure the source bytes of a range against `max_jit_src_bytes`. `view` is owned
555/// because promotion hands it to `create_merged_partition`.
556#[span_fn]
557pub async fn update_on_demand_view(
558    lakehouse: Arc<LakehouseContext>,
559    view: Arc<dyn View>,
560    on_demand_sources: &[Arc<dyn View>],
561    extract_sources: &[ViewMetadata],
562    max_jit_src_bytes: i64,
563    query_range: TimeRange,
564) -> Result<()> {
565    let now = Utc::now();
566    let rung = select_rung(query_range);
567    let aligned = align_outward(query_range, rung)?;
568    // Without the clamp the open edge would materialize empty buckets up to the end of the rung.
569    let end_of_minute = now.duration_trunc(LADDER[0])? + LADDER[0];
570    let insert_range = TimeRange::new(aligned.begin, aligned.end.min(end_of_minute));
571    let planned = plan_dense_buckets(insert_range, rung, LADDER[0], now, default_grace());
572    let (Some(first), Some(last)) = (planned.first(), planned.last()) else {
573        return Ok(());
574    };
575    let pool = &lakehouse.lake().db_pool;
576    let view_meta = view.get_meta();
577    let (units, rows) = settle_units(
578        pool,
579        &view_meta,
580        &planned,
581        TimeRange::new(first.range.begin, last.range.end),
582    )
583    .await?;
584
585    let mut snapshot_range = units
586        .iter()
587        .map(|u| u.range)
588        .reduce(hull)
589        .with_context(|| "planned buckets without units")?;
590    let mut cache = snapshot_sources(&lakehouse, on_demand_sources, snapshot_range).await?;
591    let mut src_partitions = source_partitions(&cache, extract_sources);
592
593    let mut verdicts = Vec::with_capacity(units.len());
594    for unit in &units {
595        let (spec, verdict) =
596            probe_unit(&lakehouse, &view, &view_meta, &cache, unit, &rows).await?;
597        verdicts.push(verdict);
598        if verdict == UnitVerdict::Covered {
599            record_outcome("covered");
600            continue;
601        }
602        let bytes = |range: TimeRange| source_bytes(&src_partitions, extract_sources, range);
603        let plan = plan_stale_unit(unit, &bytes, max_jit_src_bytes);
604        match write_stale_unit(
605            &lakehouse,
606            &view,
607            &view_meta,
608            &cache,
609            unit,
610            &spec,
611            &plan,
612            &bytes,
613            max_jit_src_bytes,
614        )
615        .await
616        {
617            Ok(()) => {}
618            Err(e) if is_overlap_conflict(&e) => {
619                resolve_conflict(
620                    &lakehouse,
621                    &view,
622                    on_demand_sources,
623                    extract_sources,
624                    max_jit_src_bytes,
625                    &view_meta,
626                    unit,
627                    rung,
628                    &mut snapshot_range,
629                    &mut cache,
630                )
631                .await?;
632                src_partitions = source_partitions(&cache, extract_sources);
633            }
634            Err(e) => {
635                return Err(e).with_context(|| {
636                    format!(
637                        "writing on-demand unit [{}, {})",
638                        unit.range.begin.to_rfc3339(),
639                        unit.range.end.to_rfc3339()
640                    )
641                });
642            }
643        }
644    }
645
646    let bytes = |range: TimeRange| source_bytes(&src_partitions, extract_sources, range);
647    let targets = promotion_targets(&units, &rows, &verdicts, rung, &bytes, max_jit_src_bytes);
648    promote_closed_buckets(
649        lakehouse,
650        view,
651        targets,
652        i64::MAX,
653        max_jit_src_bytes,
654        RangeConvention::Aligned,
655    )
656    .await;
657    Ok(())
658}