:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(deltalite): index live files by partition for upsert planning (#111497)
Tom Owers37b9c05cd4ae
diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex c26981f912c4..12fc23af4f15 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -34,8 +34,9 @@ use arrow_cast::{cast_with_options, CastOptions};use arrow_schema::{DataType, Field, Schema, SchemaRef};use arrow_select::filter::filter_record_batch;use arrow_select::take::{take, take_record_batch};+use delta_kernel::expressions::Scalar;use deltalake::kernel::transaction::{CommitBuilder, CommitProperties};-use deltalake::kernel::{Action, MetadataExt as _, Remove, StructType};+use deltalake::kernel::{Action, LogicalFileView, MetadataExt as _, Remove, StructType};use deltalake::protocol::checkpoints::{cleanup_metadata, create_checkpoint};use deltalake::protocol::{DeltaOperation, SaveMode};use deltalake::table::config::TablePropertiesExt;@@ -986,9 +987,10 @@ async fn upsert_inner(let pk0_idx = table_schema.index_of(&opts.primary_keys[0]).ok();let plan_started = Instant::now();- let mut work = Vec::new();- for (value, source) in groups {- let files = list_partition_files(table, partition_col.as_deref(), &value).await?;+ let values: Vec<&str> = groups.iter().map(|(v, _)| v.as_str()).collect();+ let files_by_group = list_files_by_partition(table, partition_col.as_deref(), &values).await?;+ let mut work = Vec::with_capacity(groups.len());+ for ((value, source), files) in groups.into_iter().zip(files_by_group) {// Stats-based pruning is free (the Add-action stats are already in memory), so// both `Stats` and `Probe` apply it; `Probe` then verifies the survivors by// reading their PK columns inside the partition worker.@@ -1461,6 +1463,134 @@ fn source_pk_range(source: &PartitionSource, col_idx: usize) -> Result<Option<(VOk(acc)}+/// Live files of each partition in `values` (aligned with it), from ONE pass over the+/// snapshot's live files. Filtering the snapshot once per partition costs O(partitions x+/// live files): seconds of planning for a sync that touches a thousand partitions of a+/// table with ten thousand files.+///+/// Each list keeps the snapshot's file order, as the per-partition filter did. Where+/// the index cannot reproduce the filter's equality exactly, this falls back to it.+async fn list_files_by_partition(+ table: &DeltaTable,+ partition_col: Option<&str>,+ values: &[&str],+) -> Result<Vec<Vec<TargetFile>>> {+ if let Some(col) = partition_col {+ if let Some(files) = index_partition_files(table, col, values).await? {+ return Ok(files);+ }+ debug!(+ partition_col = col,+ "partition file index not applicable, filtering the snapshot per partition"+ );+ }+ let mut out = Vec::with_capacity(values.len());+ for value in values {+ out.push(list_partition_files(table, partition_col, value).await?);+ }+ Ok(out)+}++/// The one-pass index behind [`list_files_by_partition`]. A file belongs to a partition+/// value exactly when the delta-rs partition filter `col = value` keeps it: both sides+/// are parsed into typed scalars by the kernel's own `parse_scalar` (the filter's parser),+/// and a value that parses to NULL (the empty string) selects the NULL partition, as the+/// filter's `IS NULL` rewrite does. Only the touched partitions' files are materialised.+///+/// Returns `None` when the index cannot reproduce the filter exactly: a floating-point+/// or non-primitive partition column, a value that does not parse (the filter then+/// raises the same error), or a file without parsed partition values.+async fn index_partition_files(+ table: &DeltaTable,+ col: &str,+ values: &[&str],+) -> Result<Option<Vec<Vec<TargetFile>>>> {+ let schema = table.snapshot()?.schema();+ let Some(ptype) = schema+ .field(col)+ .and_then(|f| f.data_type().as_primitive_opt())+ else {+ return Ok(None);+ };++ // Distinct source strings can parse to the same scalar ("7" and "07" on a long+ // column); each still gets the files, exactly as separate filter calls would.+ let mut wanted: HashMap<PartitionKey, Vec<usize>> = HashMap::with_capacity(values.len());+ for (i, value) in values.iter().enumerate() {+ let Ok(scalar) = ptype.parse_scalar(value) else {+ return Ok(None);+ };+ let Some(key) = PartitionKey::from_scalar(&scalar) else {+ return Ok(None);+ };+ wanted.entry(key).or_default().push(i);+ }++ note_snapshot_scan();+ let mut out: Vec<Vec<TargetFile>> = values.iter().map(|_| Vec::new()).collect();+ let mut views = table.get_active_add_actions_by_partitions(&[]);+ while let Some(view) = views.try_next().await? {+ let Some(key) = file_partition_key(&view, col) else {+ return Ok(None);+ };+ if let Some(slots) = wanted.get(&key) {+ for &i in slots {+ out[i].push(target_file(&view));+ }+ }+ }+ Ok(Some(out))+}++fn file_partition_key(view: &LogicalFileView, col: &str) -> Option<PartitionKey> {+ let parsed = view.partition_values()?;+ let idx = parsed.fields().iter().position(|f| f.name() == col)?;+ PartitionKey::from_scalar(parsed.values().get(idx)?)+}++/// Hashable form of a parsed partition value, for the types whose SQL equality is plain+/// value equality. Floats are left out: SQL equality has `-0.0 = 0.0` and `NaN != NaN`,+/// which a bitwise key would get wrong. All values of one column share a type, so+/// collapsing the integer-backed types into one variant cannot conflate two values.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+enum PartitionKey {+ Null,+ Int(i64),+ Bool(bool),+ Str(String),+ Bytes(Vec<u8>),+ Decimal(i128),+}++impl PartitionKey {+ fn from_scalar(scalar: &Scalar) -> Option<Self> {+ Some(match scalar {+ Scalar::Null(_) => Self::Null,+ Scalar::Byte(v) => Self::Int(i64::from(*v)),+ Scalar::Short(v) => Self::Int(i64::from(*v)),+ Scalar::Integer(v) | Scalar::Date(v) => Self::Int(i64::from(*v)),+ Scalar::Long(v) | Scalar::Timestamp(v) | Scalar::TimestampNtz(v) => Self::Int(*v),+ Scalar::Boolean(v) => Self::Bool(*v),+ Scalar::String(v) => Self::Str(v.clone()),+ Scalar::Binary(v) => Self::Bytes(v.clone()),+ Scalar::Decimal(d) => Self::Decimal(d.bits()),+ _ => return None,+ })+ }+}++#[cfg(test)]+thread_local! {+ static SNAPSHOT_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}++/// Counts full passes over the snapshot's files, so a test can assert planning makes+/// one per upsert rather than one per touched partition.+fn note_snapshot_scan() {+ #[cfg(test)]+ SNAPSHOT_SCANS.with(|c| c.set(c.get() + 1));+}+async fn list_partition_files(table: &DeltaTable,partition_col: Option<&str>,@@ -1474,21 +1604,23 @@ async fn list_partition_files(None => vec![],};+ note_snapshot_scan();let views: Vec<_> = table.get_active_add_actions_by_partitions(&filters).try_collect().await?;- Ok(views- .into_iter()- .map(|v| TargetFile {- path: v.path().to_string(),- size: v.size() as u64,- stats: v.stats(),- remove: v.remove_action(true),- metadata: None,- })- .collect())+ Ok(views.iter().map(target_file).collect())+}++fn target_file(v: &LogicalFileView) -> TargetFile {+ TargetFile {+ path: v.path().to_string(),+ size: v.size() as u64,+ stats: v.stats(),+ remove: v.remove_action(true),+ metadata: None,+ }}/// Open a Parquet stream builder for `f`. A footer the probe already parsed is reused@@ -2628,4 +2760,323 @@ mod tests {// Unknown PK column errors.assert!(source_footprint(&[b], &schema, &["nope".to_string()]).is_err());}++ // ---- partition file index --------------------------------------------------------++ use arrow_array::{ArrayRef, Date32Array, Float64Array};+ use deltalake::kernel::{DataType as KernelType, StructField};+ use deltalake::operations::create::CreateBuilder;+ use deltalake::writer::DeltaWriter;++ fn scans() -> usize {+ SNAPSHOT_SCANS.with(|c| c.get())+ }++ fn arrow_type(t: &KernelType) -> DataType {+ match t {+ t if *t == KernelType::STRING => DataType::Utf8,+ t if *t == KernelType::LONG => DataType::Int64,+ t if *t == KernelType::DATE => DataType::Date32,+ t if *t == KernelType::DOUBLE => DataType::Float64,+ other => panic!("no fixture mapping for {other:?}"),+ }+ }++ fn fixture_schema(ptype: Option<&KernelType>) -> SchemaRef {+ let mut fields = vec![+ AField::new("pk", DataType::Utf8, false),+ AField::new("v", DataType::Int64, true),+ ];+ if let Some(t) = ptype {+ fields.push(AField::new("p", arrow_type(t), true));+ }+ Arc::new(Schema::new(fields))+ }++ fn fixture_rows(+ schema: &SchemaRef,+ tag: &str,+ parts: Option<ArrayRef>,+ n: usize,+ ) -> RecordBatch {+ let pks: Vec<String> = (0..n).map(|i| format!("{tag}-{i}")).collect();+ let mut cols: Vec<ArrayRef> = vec![+ Arc::new(StringArray::from(pks)),+ Arc::new(Int64Array::from((0..n as i64).collect::<Vec<_>>())),+ ];+ cols.extend(parts);+ RecordBatch::try_new(schema.clone(), cols).unwrap()+ }++ /// A table with one file per distinct partition value per commit, so partitions+ /// listed in several commits hold several live files.+ async fn fixture_table(+ dir: &std::path::Path,+ ptype: Option<KernelType>,+ commits: Vec<ArrayRef>,+ ) -> DeltaTable {+ let mut create = CreateBuilder::new()+ .with_location(dir.to_str().unwrap())+ .with_columns(vec![+ StructField::new("pk", KernelType::STRING, false),+ StructField::new("v", KernelType::LONG, true),+ ]);+ if let Some(t) = &ptype {+ create = create+ .with_columns(vec![StructField::new("p", t.clone(), true)])+ .with_partition_columns(vec!["p".to_string()]);+ }+ let mut table = create.await.unwrap();+ let schema = fixture_schema(ptype.as_ref());+ for (c, parts) in commits.into_iter().enumerate() {+ let n = parts.len();+ let p = ptype.is_some().then_some(parts);+ let mut w = RecordBatchWriter::for_table(&table).unwrap();+ w.write(fixture_rows(&schema, &format!("c{c}"), p, n))+ .await+ .unwrap();+ w.flush_and_commit(&mut table).await.unwrap();+ }+ table+ }++ /// Update the given commit-0 rows through `upsert`, so the table carries tombstoned+ /// files that the listing must not return.+ async fn tombstone_rows(+ table: &mut DeltaTable,+ ptype: Option<&KernelType>,+ commit0: &ArrayRef,+ rows: &[u32],+ ) {+ let schema = fixture_schema(ptype);+ let pks: Vec<String> = rows.iter().map(|i| format!("c0-{i}")).collect();+ let mut cols: Vec<ArrayRef> = vec![+ Arc::new(StringArray::from(pks)),+ Arc::new(Int64Array::from(vec![-1; rows.len()])),+ ];+ if ptype.is_some() {+ cols.push(take(commit0.as_ref(), &UInt32Array::from(rows.to_vec()), None).unwrap());+ }+ let stats = upsert(+ table,+ vec![RecordBatch::try_new(schema.clone(), cols).unwrap()],+ schema,+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(stats.rows_updated, rows.len());+ assert!(stats.files_removed > 0);+ table.load().await.unwrap();+ }++ type Fingerprint = Vec<(String, u64, Option<String>, String)>;++ fn fingerprint(files: &[TargetFile]) -> Fingerprint {+ files+ .iter()+ .map(|f| {+ (+ f.path.clone(),+ f.size,+ f.stats.clone(),+ f.remove.path.clone(),+ )+ })+ .collect()+ }++ /// The index must return, for every lookup value, exactly the files (in order) the+ /// per-partition filter returns, using `expected_scans` passes over the snapshot.+ async fn assert_index_matches_filter(+ table: &DeltaTable,+ col: Option<&str>,+ lookups: &[&str],+ expected_scans: usize,+ ) -> Vec<Fingerprint> {+ let before = scans();+ let indexed = list_files_by_partition(table, col, lookups).await.unwrap();+ assert_eq!(scans() - before, expected_scans, "snapshot passes");+ assert_eq!(indexed.len(), lookups.len());+ let mut out = Vec::new();+ for (value, got) in lookups.iter().zip(&indexed) {+ let want = list_partition_files(table, col, value).await.unwrap();+ assert_eq!(fingerprint(got), fingerprint(&want), "partition {value:?}");+ out.push(fingerprint(got));+ }+ out+ }++ fn strs(v: &[Option<&str>]) -> ArrayRef {+ Arc::new(StringArray::from(v.to_vec()))+ }++ #[tokio::test]+ async fn partition_index_matches_filter_for_encoded_and_null_string_values() {+ let dir = tempfile::tempdir().unwrap();+ let first = [+ Some("a"),+ Some("a b"),+ Some("a/b"),+ Some("100%"),+ Some("x=y"),+ Some("é"),+ Some("#?&"),+ Some("it's"),+ Some("A"),+ None,+ ];+ let commit0 = strs(&first);+ let mut table = fixture_table(+ dir.path(),+ Some(KernelType::STRING),+ vec![commit0.clone(), strs(&[Some("a"), Some("100%"), None])],+ )+ .await;+ tombstone_rows(&mut table, Some(&KernelType::STRING), &commit0, &[0, 2, 5]).await;++ let lookups = [+ "a", "a b", "a/b", "100%", "x=y", "é", "#?&", "it's", "A", "", "zzz", "a ", "a%2Fb",+ ];+ let got = assert_index_matches_filter(&table, Some("p"), &lookups, 1).await;+ let count = |v: &str| got[lookups.iter().position(|l| *l == v).unwrap()].len();+ // Commit 1 added a second file to "a"; the tombstoned commit-0 file is gone and its+ // rewrite is live.+ assert_eq!(count("a"), 2);+ assert_eq!(count("zzz"), 0);+ assert_eq!(count("a%2Fb"), 0);+ assert_eq!(count("a/b"), 1);+ // The empty string parses to NULL, which the filter turns into `p IS NULL`.+ assert_eq!(count(""), 2);+ }++ #[tokio::test]+ async fn partition_index_matches_filter_for_typed_partition_columns() {+ let dir = tempfile::tempdir().unwrap();+ let longs = |v: &[Option<i64>]| -> ArrayRef { Arc::new(Int64Array::from(v.to_vec())) };+ let commit0 = longs(&[Some(1), Some(2), Some(7), Some(-3), None]);+ let mut table = fixture_table(+ dir.path(),+ Some(KernelType::LONG),+ vec![commit0.clone(), longs(&[Some(7), None])],+ )+ .await;+ tombstone_rows(&mut table, Some(&KernelType::LONG), &commit0, &[1, 2]).await;+ // "07" and "+7" parse to the same long as "7": each gets the same files.+ let lookups = ["1", "2", "7", "07", "+7", "-3", "", "99"];+ let got = assert_index_matches_filter(&table, Some("p"), &lookups, 1).await;+ assert_eq!(got[2].len(), 2);+ assert_eq!(got[2], got[3]);+ assert_eq!(got[6].len(), 2);++ // A value the column type cannot parse: the filter raises, and so does the index.+ assert!(list_files_by_partition(&table, Some("p"), &["7", "x"])+ .await+ .is_err());+ assert!(list_partition_files(&table, Some("p"), "x").await.is_err());++ let dir = tempfile::tempdir().unwrap();+ let dates = |v: &[Option<i32>]| -> ArrayRef { Arc::new(Date32Array::from(v.to_vec())) };+ let table = fixture_table(+ dir.path(),+ Some(KernelType::DATE),+ vec![+ dates(&[Some(19723), Some(19724), None]),+ dates(&[Some(19724)]),+ ],+ )+ .await;+ let lookups = ["2024-01-01", "2024-01-02", "", "2023-12-31"];+ let got = assert_index_matches_filter(&table, Some("p"), &lookups, 1).await;+ assert_eq!(got[1].len(), 2);+ }++ #[tokio::test]+ async fn partition_index_falls_back_to_the_filter_for_float_columns() {+ let dir = tempfile::tempdir().unwrap();+ let doubles = |v: &[Option<f64>]| -> ArrayRef { Arc::new(Float64Array::from(v.to_vec())) };+ let table = fixture_table(+ dir.path(),+ Some(KernelType::DOUBLE),+ vec![doubles(&[Some(0.5), Some(1.0), None])],+ )+ .await;+ let lookups = ["0.5", "1", "1.0", ""];+ assert_index_matches_filter(&table, Some("p"), &lookups, lookups.len()).await;+ }++ #[tokio::test]+ async fn partition_index_matches_filter_for_unpartitioned_tables() {+ let dir = tempfile::tempdir().unwrap();+ let dummy = || -> ArrayRef { Arc::new(StringArray::from(vec!["-"; 3])) };+ let mut table = fixture_table(dir.path(), None, vec![dummy(), dummy()]).await;+ tombstone_rows(&mut table, None, &dummy(), &[0]).await;+ let got = assert_index_matches_filter(&table, None, &[WHOLE_TABLE], 1).await;+ assert_eq!(got[0].len(), 2);+ }++ fn many_parts(n: usize, step: usize) -> ArrayRef {+ let v: Vec<String> = (0..n).step_by(step).map(|i| format!("p{i:04}")).collect();+ Arc::new(StringArray::from(v))+ }++ #[tokio::test]+ async fn partition_index_matches_filter_across_many_partitions() {+ let dir = tempfile::tempdir().unwrap();+ let commit0 = many_parts(300, 1);+ let mut table = fixture_table(+ dir.path(),+ Some(KernelType::STRING),+ vec![commit0.clone(), many_parts(300, 7)],+ )+ .await;+ let rows: Vec<u32> = (0..300).step_by(11).collect();+ tombstone_rows(&mut table, Some(&KernelType::STRING), &commit0, &rows).await;+ let mut values: Vec<String> = (0..300).map(|i| format!("p{i:04}")).collect();+ values.push("p9999".to_string());+ let lookups: Vec<&str> = values.iter().map(String::as_str).collect();+ let got = assert_index_matches_filter(&table, Some("p"), &lookups, 1).await;+ assert_eq!(+ got.iter().map(Vec::len).sum::<usize>(),+ 300 + 300_usize.div_ceil(7)+ );+ }++ #[tokio::test]+ async fn upsert_planning_passes_over_the_snapshot_once_whatever_it_touches() {+ let dir = tempfile::tempdir().unwrap();+ let mut table = fixture_table(+ dir.path(),+ Some(KernelType::STRING),+ vec![many_parts(200, 1)],+ )+ .await;+ let schema = fixture_schema(Some(&KernelType::STRING));+ for touched in [1usize, 100] {+ let parts = many_parts(touched, 1);+ let before = scans();+ let stats = upsert(+ &table,+ vec![fixture_rows(+ &schema,+ &format!("new{touched}"),+ Some(parts),+ touched,+ )],+ schema.clone(),+ UpsertOptions {+ primary_keys: vec!["pk".to_string()],+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(stats.partitions_touched, touched);+ assert_eq!(scans() - before, 1, "touched {touched} partitions");+ table.load().await.unwrap();+ }+ }}