Skip to main content

micromegas_analytics/lakehouse/
jit_promotion.rs

1//! On-demand promotion of fine JIT partitions into coarser ones.
2//!
3//! A query over a long range plans coarse buckets (see `partition_ladder`). When a closed bucket
4//! is already covered by several finer partitions, they are merged into one, so that this query and
5//! the following ones read a few large files instead of many small ones. The work is optional: it
6//! never fails the query, and it skips instead of waiting when another query is already on it.
7
8use super::{
9    jit_partitions::{Coverage, JitBucket, PartitionFreshnessRow, RangeConvention},
10    lakehouse_context::LakehouseContext,
11    merge::create_merged_partition,
12    partition::Partition,
13    partition_cache::PartitionCache,
14    partition_source_data::hash_to_object_count,
15    view::View,
16};
17use crate::{response_writer::ResponseWriter, time::TimeRange};
18use anyhow::{Context, Result};
19use chrono::TimeDelta;
20use micromegas_ingestion::data_lake_connection::{is_read_only, is_read_only_violation};
21use micromegas_tracing::prelude::*;
22use std::collections::hash_map::DefaultHasher;
23use std::hash::{Hash, Hasher};
24use std::sync::Arc;
25
26/// A closed bucket whose covering partitions should be merged into one.
27#[derive(Debug, Clone)]
28pub struct PromotionTarget {
29    pub bucket: TimeRange,
30    pub inputs: Vec<PartitionFreshnessRow>,
31}
32
33/// Whether `inputs` are worth merging: at least two of them, within the object cap and the byte
34/// cap on their summed `file_size`, all written with the same file schema.
35pub fn is_promotable(
36    inputs: &[&PartitionFreshnessRow],
37    max_nb_objects: i64,
38    max_bytes: i64,
39) -> bool {
40    if inputs.len() < 2 {
41        return false;
42    }
43    if inputs
44        .iter()
45        .any(|r| r.file_schema_hash != inputs[0].file_schema_hash)
46    {
47        return false;
48    }
49    let mut sum: i64 = 0;
50    for r in inputs {
51        match hash_to_object_count(&r.source_data_hash) {
52            Ok(count) => sum += count,
53            Err(_) => return false,
54        }
55    }
56    let bytes: i64 = inputs.iter().map(|r| r.file_size).sum();
57    sum <= max_nb_objects && bytes <= max_bytes
58}
59
60/// Picks the buckets to promote. A pure function of the planner output, the verdicts and the
61/// candidate rows: no object storage is read. A bucket qualifies when the planner emitted it
62/// closed at the query's rung (not descended), it was judged covered by at least two of its own
63/// rows, and those rows fit the object cap with a single schema hash.
64pub fn promotion_candidates(
65    buckets: &[JitBucket],
66    verdicts: &[Coverage],
67    candidates: &[PartitionFreshnessRow],
68    query_rung: TimeDelta,
69    max_nb_objects: i64,
70) -> Vec<PromotionTarget> {
71    let mut targets = vec![];
72    for (bucket, verdict) in buckets.iter().zip(verdicts) {
73        let planned = &bucket.planned;
74        if !planned.closed || planned.rung != query_rung || *verdict != Coverage::Covered {
75            continue;
76        }
77        let inputs: Vec<&PartitionFreshnessRow> = candidates
78            .iter()
79            .filter(|r| RangeConvention::BlockHull.row_inside(r, planned.range))
80            .collect();
81        if is_promotable(&inputs, max_nb_objects, i64::MAX) {
82            targets.push(PromotionTarget {
83                bucket: planned.range,
84                inputs: inputs.into_iter().cloned().collect(),
85            });
86        }
87    }
88    targets
89}
90
91fn promotion_lock_key(view: &dyn View, bucket: TimeRange) -> i64 {
92    let mut hasher = DefaultHasher::new();
93    "promote".hash(&mut hasher);
94    view.get_view_set_name().hash(&mut hasher);
95    view.get_view_instance_id().hash(&mut hasher);
96    bucket.begin.hash(&mut hasher);
97    bucket.end.hash(&mut hasher);
98    hasher.finish() as i64
99}
100
101fn hull_of<'a>(rows: impl Iterator<Item = &'a PartitionFreshnessRow>) -> Option<TimeRange> {
102    let mut hull: Option<TimeRange> = None;
103    for r in rows {
104        hull = Some(match hull {
105            None => TimeRange::new(r.begin_insert_time, r.end_insert_time),
106            Some(h) => TimeRange::new(
107                h.begin.min(r.begin_insert_time),
108                h.end.max(r.end_insert_time),
109            ),
110        });
111    }
112    hull
113}
114
115fn freshness_row(p: &Partition) -> PartitionFreshnessRow {
116    PartitionFreshnessRow {
117        begin_insert_time: p.begin_insert_time(),
118        end_insert_time: p.end_insert_time(),
119        file_schema_hash: p.view_metadata.file_schema_hash.clone(),
120        source_data_hash: p.source_data_hash.clone(),
121        file_size: p.file_size,
122    }
123}
124
125fn record_skip(bucket: TimeRange, reason: &'static str) {
126    info!(
127        "jit promotion skipped_{reason} [{}, {})",
128        bucket.begin.to_rfc3339(),
129        bucket.end.to_rfc3339()
130    );
131    imetric!("jit_promotion", "count", reason = reason, 1_u64);
132}
133
134enum Promotion {
135    Promoted,
136    Skipped(&'static str),
137}
138
139async fn promote_one(
140    lakehouse: &Arc<LakehouseContext>,
141    view: &Arc<dyn View>,
142    target: &PromotionTarget,
143    max_nb_objects: i64,
144    max_bytes: i64,
145    convention: RangeConvention,
146) -> Result<Promotion> {
147    let pool = &lakehouse.lake().db_pool;
148    let mut lock_transaction = pool.begin().await.with_context(|| "begin")?;
149    let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1);")
150        .bind(promotion_lock_key(view.as_ref(), target.bucket))
151        .fetch_one(&mut *lock_transaction)
152        .await
153        .with_context(|| "pg_try_advisory_xact_lock")?;
154    if !locked {
155        return Ok(Promotion::Skipped("locked"));
156    }
157    let setting: String = sqlx::query_scalar("SHOW transaction_read_only")
158        .fetch_one(&mut *lock_transaction)
159        .await
160        .with_context(|| "SHOW transaction_read_only")?;
161    if is_read_only(&setting) {
162        return Ok(Promotion::Skipped("read_only"));
163    }
164
165    // Another query may have promoted the bucket between the snapshot and the lock.
166    let fetched = PartitionCache::fetch_inclusive_insert_range_for_view(
167        pool,
168        view.get_view_set_name(),
169        view.get_view_instance_id(),
170        target.bucket,
171    )
172    .await?;
173    let (inside, others): (Vec<Partition>, Vec<Partition>) = fetched
174        .partitions
175        .into_iter()
176        .partition(|p| convention.row_inside(&freshness_row(p), target.bucket));
177    let rows: Vec<PartitionFreshnessRow> = inside.iter().map(freshness_row).collect();
178    let row_refs: Vec<&PartitionFreshnessRow> = rows.iter().collect();
179    let straddled = others
180        .iter()
181        .any(|p| convention.row_intersects(&freshness_row(p), target.bucket));
182    let hull = hull_of(rows.iter());
183    if straddled
184        || !is_promotable(&row_refs, max_nb_objects, max_bytes)
185        || hull != hull_of(target.inputs.iter())
186    {
187        return Ok(Promotion::Skipped("changed"));
188    }
189    let hull = hull.with_context(|| "promotable bucket without rows")?;
190
191    let mut cache = PartitionCache::empty(hull);
192    cache.partitions = inside;
193    let cache = Arc::new(cache);
194    create_merged_partition(
195        cache.clone(),
196        cache,
197        lakehouse.clone(),
198        view.clone(),
199        hull,
200        Arc::new(ResponseWriter::new(None)),
201    )
202    .await
203    .with_context(|| "create_merged_partition")?;
204    lock_transaction.commit().await.with_context(|| "commit")?;
205    Ok(Promotion::Promoted)
206}
207
208/// Merges each target's partitions into one, in turn. Never fails: a target that errors is logged
209/// and counted, and the query still reads a complete set of partitions because a merge retires its
210/// inputs in the same transaction that inserts the result.
211///
212/// The lock transaction stays open across the merge, which takes a second connection from the same
213/// pool, so a promoting query holds two connections.
214pub async fn promote_closed_buckets(
215    lakehouse: Arc<LakehouseContext>,
216    view: Arc<dyn View>,
217    targets: Vec<PromotionTarget>,
218    max_nb_objects: i64,
219    max_bytes: i64,
220    convention: RangeConvention,
221) {
222    for target in targets {
223        match promote_one(
224            &lakehouse,
225            &view,
226            &target,
227            max_nb_objects,
228            max_bytes,
229            convention,
230        )
231        .await
232        {
233            Ok(Promotion::Promoted) => {
234                info!(
235                    "jit promotion promoted [{}, {})",
236                    target.bucket.begin.to_rfc3339(),
237                    target.bucket.end.to_rfc3339()
238                );
239                imetric!("jit_promotion", "count", reason = "promoted", 1_u64);
240            }
241            Ok(Promotion::Skipped(reason)) => record_skip(target.bucket, reason),
242            Err(e) if is_read_only_violation(&e) => {
243                debug!("jit promotion on a read-only connection: {e:#}");
244                imetric!("jit_promotion", "count", reason = "read_only", 1_u64);
245            }
246            Err(e) => {
247                warn!(
248                    "jit promotion failed [{}, {}): {e:#}",
249                    target.bucket.begin.to_rfc3339(),
250                    target.bucket.end.to_rfc3339()
251                );
252                imetric!("jit_promotion_failed", "count", 1_u64);
253            }
254        }
255    }
256}