buoyant_kernel 0.21.103

Buoyant Data distribution of delta-kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Row tracking integration tests for the CreateTable API.
//!
//! Tests that creating a table with `delta.enableRowTracking=true` automatically adds the
//! `rowTracking` and `domainMetadata` features to the protocol and writes the initial row
//! tracking domain metadata with `rowIdHighWaterMark = -1`.

use std::sync::Arc;

use buoyant_kernel as delta_kernel;

use delta_kernel::arrow::array::{Int32Array, StringArray};
use delta_kernel::arrow::record_batch::RecordBatch;
use delta_kernel::committer::FileSystemCommitter;
use delta_kernel::engine::arrow_conversion::TryIntoArrow as _;
use delta_kernel::engine::arrow_data::ArrowEngineData;
use delta_kernel::row_tracking::RowTrackingDomainMetadata;
use delta_kernel::snapshot::Snapshot;
use delta_kernel::table_features::{
    TableFeature, TABLE_FEATURES_MIN_READER_VERSION, TABLE_FEATURES_MIN_WRITER_VERSION,
};
use delta_kernel::transaction::create_table::create_table;
use delta_kernel::transaction::data_layout::DataLayout;
use delta_kernel::DeltaResult;
use rstest::rstest;
use test_utils::{
    get_materialized_row_tracking_column_names, get_row_tracking_add_actions, insert_data,
    read_actions_from_commit, test_table_setup,
};
use url::Url;

/// Asserts protocol features are correct for row tracking on a snapshot.
fn assert_row_tracking_protocol(snapshot: &Snapshot) {
    let protocol = snapshot.table_configuration().protocol();

    assert!(protocol.min_reader_version() >= TABLE_FEATURES_MIN_READER_VERSION);
    assert!(protocol.min_writer_version() >= TABLE_FEATURES_MIN_WRITER_VERSION);

    // RowTracking is writer-only
    assert!(
        protocol
            .writer_features()
            .is_some_and(|f| f.contains(&TableFeature::RowTracking)),
        "rowTracking should be in writer features"
    );
    assert!(
        !protocol
            .reader_features()
            .is_some_and(|f| f.contains(&TableFeature::RowTracking)),
        "rowTracking should NOT be in reader features"
    );

    // DomainMetadata dependency is writer-only
    assert!(
        protocol
            .writer_features()
            .is_some_and(|f| f.contains(&TableFeature::DomainMetadata)),
        "domainMetadata should be in writer features"
    );
}

/// Verifies row tracking across both activation paths (enablement property and feature signal)
/// and both table shapes (empty CREATE TABLE and CTAS with a single file of 5 rows).
///
/// Key behavioral differences by case:
/// - Activation path: `delta.enableRowTracking=true` sets materialized column name properties;
///   feature-signal-only does not.
/// - Table shape: empty tables get `rowIdHighWaterMark = -1` with no add actions; CTAS assigns
///   `baseRowId = 0` and `defaultRowCommitVersion = 0` and sets `rowIdHighWaterMark = 4`.
#[rstest]
#[tokio::test]
async fn test_create_table_with_row_tracking(
    #[values(
        ("delta.enableRowTracking", "true"),
        ("delta.feature.rowTracking", "supported")
    )]
    activation: (&str, &str),
    #[values(false, true)] with_data: bool,
) -> DeltaResult<()> {
    let (key, value) = activation;
    let expect_property_enabled = key == "delta.enableRowTracking";

    let (_temp_dir, table_path, engine) = test_table_setup()?;
    let schema = super::simple_schema()?;

    let mut txn = create_table(&table_path, schema.clone(), "Test/1.0")
        .with_table_properties([(key, value)])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?;

    if with_data {
        // Write one parquet file with 5 rows
        let arrow_schema = Arc::new(schema.as_ref().try_into_arrow()?);
        let batch = RecordBatch::try_new(
            arrow_schema,
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])),
                Arc::new(StringArray::from(vec!["a", "b", "c", "d", "e"])),
            ],
        )
        .map_err(|e| delta_kernel::Error::generic(e.to_string()))?;

        let write_context = Arc::new(txn.unpartitioned_write_context()?);
        let add_files = engine
            .write_parquet(&ArrowEngineData::new(batch), write_context.as_ref())
            .await?;
        txn.add_files(add_files);
    }

    let committed = txn.commit(engine.as_ref())?.unwrap_committed();
    let snapshot = committed
        .post_commit_snapshot()
        .expect("should have snapshot");
    assert_row_tracking_protocol(snapshot);

    // Verify domain metadata persists to disk for empty tables. CTAS is not checked here
    // because the high water mark is written via add-file processing, not the initial
    // domain metadata path.
    if !with_data {
        let disk_snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
        assert_row_tracking_protocol(&disk_snapshot);
    }

    let table_url = Url::from_directory_path(&table_path).expect("valid path");

    // Verify row tracking high water mark via snapshot API
    let disk_snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    let expected_high_water_mark: i64 = if with_data { 4 } else { -1 };
    assert_eq!(
        RowTrackingDomainMetadata::get_high_water_mark(&disk_snapshot, engine.as_ref())?,
        Some(expected_high_water_mark),
    );

    // Verify add actions
    let add_actions = get_row_tracking_add_actions(&table_url, 0).expect("failed to read commit");
    if with_data {
        assert_eq!(add_actions.len(), 1, "Expected one add action");
        assert_eq!(add_actions[0].base_row_id, Some(0), "baseRowId should be 0");
        assert_eq!(
            add_actions[0].default_row_commit_version,
            Some(0),
            "defaultRowCommitVersion should be 0"
        );
    } else {
        assert!(
            add_actions.is_empty(),
            "Expected no add actions for empty create"
        );
    }

    // Verify materialized column name properties.
    // Only set when delta.enableRowTracking=true; feature-signal-only tables do not get them.
    let col_names =
        get_materialized_row_tracking_column_names(&table_url, 0).expect("failed to read commit");

    if expect_property_enabled {
        let row_id_col = col_names
            .row_id_column_name
            .as_deref()
            .expect("materializedRowIdColumnName should be set");
        assert!(row_id_col.starts_with("_row-id-col-"), "got {row_id_col}");

        let commit_version_col = col_names
            .row_commit_version_column_name
            .as_deref()
            .expect("materializedRowCommitVersionColumnName should be set");
        assert!(
            commit_version_col.starts_with("_row-commit-version-col-"),
            "got {commit_version_col}"
        );
    } else {
        assert!(
            col_names.row_id_column_name.is_none(),
            "materializedRowIdColumnName should NOT be set for feature-signal-only tables"
        );
        assert!(
            col_names.row_commit_version_column_name.is_none(),
            "materializedRowCommitVersionColumnName should NOT be set for feature-signal-only tables"
        );

        // Also verify the enablement property itself is absent
        let metadata_actions =
            read_actions_from_commit(&table_url, 0, "metaData").expect("failed to read commit");
        assert!(
            metadata_actions[0]
                .get("configuration")
                .and_then(|c| c.get("delta.enableRowTracking"))
                .is_none(),
            "delta.enableRowTracking should NOT be set for feature-signal-only tables"
        );
    }

    Ok(())
}

/// Verifies that CTAS with multiple files assigns non-overlapping baseRowId ranges and
/// computes the correct cumulative high water mark.
#[tokio::test]
async fn test_create_table_with_multiple_files_and_row_tracking() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let schema = super::simple_schema()?;
    let mut txn = create_table(&table_path, schema.clone(), "Test/1.0")
        .with_table_properties([("delta.enableRowTracking", "true")])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?;

    let arrow_schema: Arc<delta_kernel::arrow::datatypes::Schema> =
        Arc::new(schema.as_ref().try_into_arrow()?);

    // Write two separate parquet files: 3 rows and 5 rows
    let batch1 = RecordBatch::try_new(
        arrow_schema.clone(),
        vec![
            Arc::new(Int32Array::from(vec![1, 2, 3])),
            Arc::new(StringArray::from(vec!["a", "b", "c"])),
        ],
    )
    .map_err(|e| delta_kernel::Error::generic(e.to_string()))?;

    let batch2 = RecordBatch::try_new(
        arrow_schema,
        vec![
            Arc::new(Int32Array::from(vec![4, 5, 6, 7, 8])),
            Arc::new(StringArray::from(vec!["d", "e", "f", "g", "h"])),
        ],
    )
    .map_err(|e| delta_kernel::Error::generic(e.to_string()))?;

    let write_context = Arc::new(txn.unpartitioned_write_context()?);
    let adds1 = engine
        .write_parquet(&ArrowEngineData::new(batch1), write_context.as_ref())
        .await?;
    let adds2 = engine
        .write_parquet(&ArrowEngineData::new(batch2), write_context.as_ref())
        .await?;

    txn.add_files(adds1);
    txn.add_files(adds2);

    let committed = txn.commit(engine.as_ref())?.unwrap_committed();
    assert_eq!(committed.commit_version(), 0);

    let table_url = Url::from_directory_path(&table_path).expect("valid path");

    // Verify add actions (already sorted by baseRowId)
    let add_actions = get_row_tracking_add_actions(&table_url, 0).expect("failed to read commit");
    assert_eq!(add_actions.len(), 2, "Expected two add actions");

    // First file (3 rows): baseRowId = 0
    assert_eq!(add_actions[0].base_row_id, Some(0));
    assert_eq!(add_actions[0].default_row_commit_version, Some(0));

    // Second file (5 rows): baseRowId = 3 (first file had 3 rows)
    assert_eq!(add_actions[1].base_row_id, Some(3));
    assert_eq!(add_actions[1].default_row_commit_version, Some(0));

    // HWM should be 7 (IDs 0-2 from file 1, IDs 3-7 from file 2)
    let disk_snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    assert_eq!(
        RowTrackingDomainMetadata::get_high_water_mark(&disk_snapshot, engine.as_ref())?,
        Some(7),
        "HWM should be 7 for 8 total rows (3 + 5) starting from -1"
    );

    Ok(())
}

/// Verifies that row tracking and clustering can be enabled together. Both features require
/// DomainMetadata, which should appear exactly once in the protocol. Both domain metadata
/// entries (delta.rowTracking and delta.clustering) should be present in the commit.
#[test]
fn test_create_table_with_row_tracking_and_clustering() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let committed = create_table(&table_path, super::simple_schema()?, "Test/1.0")
        .with_table_properties([("delta.enableRowTracking", "true")])
        .with_data_layout(DataLayout::clustered(["id"]))
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?
        .unwrap_committed();

    let snapshot = committed
        .post_commit_snapshot()
        .expect("should have snapshot");
    let table_url = Url::from_directory_path(&table_path).expect("valid path");
    let protocol = snapshot.table_configuration().protocol();
    let writer_features = protocol
        .writer_features()
        .expect("should have writer features");

    assert!(writer_features.contains(&TableFeature::RowTracking));
    assert!(writer_features.contains(&TableFeature::ClusteredTable));
    // DomainMetadata should appear exactly once despite two features requiring it
    let dm_count = writer_features
        .iter()
        .filter(|f| **f == TableFeature::DomainMetadata)
        .count();
    assert_eq!(dm_count, 1, "DomainMetadata should not be duplicated");

    // Verify both domain metadata entries are present in the commit
    let dm_actions =
        read_actions_from_commit(&table_url, 0, "domainMetadata").expect("failed to read commit");
    assert!(
        dm_actions
            .iter()
            .any(|dm| dm["domain"] == "delta.rowTracking"),
        "row tracking domain metadata should be present"
    );
    assert!(
        dm_actions
            .iter()
            .any(|dm| dm["domain"] == "delta.clustering"),
        "clustering domain metadata should be present"
    );

    Ok(())
}

/// Verifies that row tracking and clustering work together when the table has data (CTAS).
/// Both features generate domain metadata and the add files need row tracking columns.
/// Verifies that both domain metadata entries survive when add files are also written.
#[tokio::test]
async fn test_create_table_with_row_tracking_and_clustering_and_data() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let schema = super::simple_schema()?;
    let mut txn = create_table(&table_path, schema.clone(), "Test/1.0")
        .with_table_properties([("delta.enableRowTracking", "true")])
        .with_data_layout(DataLayout::clustered(["id"]))
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?;

    let arrow_schema = Arc::new(schema.as_ref().try_into_arrow()?);
    let batch = RecordBatch::try_new(
        arrow_schema,
        vec![
            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])),
            Arc::new(StringArray::from(vec!["a", "b", "c", "d", "e"])),
        ],
    )
    .map_err(|e| delta_kernel::Error::generic(e.to_string()))?;

    let write_context = Arc::new(txn.unpartitioned_write_context()?);
    let add_files = engine
        .write_parquet(&ArrowEngineData::new(batch), write_context.as_ref())
        .await?;
    txn.add_files(add_files);

    let committed = txn.commit(engine.as_ref())?.unwrap_committed();
    let snapshot = committed
        .post_commit_snapshot()
        .expect("should have snapshot");
    let table_url = Url::from_directory_path(&table_path).expect("valid path");

    // Both features must be present in the protocol exactly once
    let writer_features = snapshot
        .table_configuration()
        .protocol()
        .writer_features()
        .expect("should have writer features");
    assert!(writer_features.contains(&TableFeature::RowTracking));
    assert!(writer_features.contains(&TableFeature::ClusteredTable));
    assert_eq!(
        writer_features
            .iter()
            .filter(|f| **f == TableFeature::DomainMetadata)
            .count(),
        1,
        "DomainMetadata should appear exactly once"
    );

    // Both domain metadata entries must survive alongside the add actions
    let dm_actions =
        read_actions_from_commit(&table_url, 0, "domainMetadata").expect("failed to read commit");
    assert!(
        dm_actions
            .iter()
            .any(|dm| dm["domain"] == "delta.rowTracking"),
        "row tracking domain metadata should be present"
    );
    assert!(
        dm_actions
            .iter()
            .any(|dm| dm["domain"] == "delta.clustering"),
        "clustering domain metadata should be present"
    );

    // Add action must have correct row tracking fields
    let add_actions = get_row_tracking_add_actions(&table_url, 0).expect("failed to read commit");
    assert_eq!(add_actions.len(), 1, "Expected one add action");
    assert_eq!(add_actions[0].base_row_id, Some(0));
    assert_eq!(add_actions[0].default_row_commit_version, Some(0));

    // High water mark should reflect the 5 written rows
    let disk_snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    assert_eq!(
        RowTrackingDomainMetadata::get_high_water_mark(&disk_snapshot, engine.as_ref())?,
        Some(4),
        "5 rows -> high water mark = 4"
    );

    Ok(())
}

/// Verifies that a table created with the feature signal only
/// (`delta.feature.rowTracking=supported`, no `delta.enableRowTracking=true`) correctly handles a
/// subsequent data append. The initial create writes `rowIdHighWaterMark = -1`; the append must
/// read that and assign `baseRowId = 0` to the first file.
#[tokio::test]
async fn test_feature_signal_create_then_append_assigns_correct_base_row_id() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    // Create empty table with feature signal only (no enablement property)
    let _ = create_table(&table_path, super::simple_schema()?, "Test/1.0")
        .with_table_properties([("delta.feature.rowTracking", "supported")])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    let table_url = Url::from_directory_path(&table_path).expect("valid path");

    // Initial commit must have written rowIdHighWaterMark = -1
    let v0_snapshot = Snapshot::builder_for(&table_path)
        .at_version(0)
        .build(engine.as_ref())?;
    assert_eq!(
        RowTrackingDomainMetadata::get_high_water_mark(&v0_snapshot, engine.as_ref())?,
        Some(-1),
        "Initial high water mark should be -1"
    );

    // Append 3 rows to the table
    let snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    let _ = insert_data(
        snapshot,
        &engine,
        vec![
            Arc::new(Int32Array::from(vec![1, 2, 3])),
            Arc::new(StringArray::from(vec!["a", "b", "c"])),
        ],
    )
    .await?;

    // The append must read the HWM from the create commit and assign baseRowId = 0
    let add_actions = get_row_tracking_add_actions(&table_url, 1).expect("failed to read commit");
    assert_eq!(add_actions.len(), 1, "Expected one add action");
    assert_eq!(
        add_actions[0].base_row_id,
        Some(0),
        "First file after create should start at baseRowId 0 (high water mark was -1)"
    );
    assert_eq!(add_actions[0].default_row_commit_version, Some(1));

    // High water mark after append: 3 rows starting from 0 -> high water mark = 2
    let v1_snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    assert_eq!(
        RowTrackingDomainMetadata::get_high_water_mark(&v1_snapshot, engine.as_ref())?,
        Some(2),
        "3 rows starting from 0 -> high water mark = 2"
    );

    Ok(())
}