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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Integration tests for the CreateTable API

mod clustering;
mod column_mapping;
mod ctas;
mod ict;
mod partitioned;
mod row_tracking;
mod timestamp_ntz;
mod variant;

use std::sync::Arc;

use buoyant_kernel as delta_kernel;

use delta_kernel::committer::FileSystemCommitter;
use delta_kernel::schema::{DataType, StructField, StructType};
use delta_kernel::snapshot::Snapshot;
use delta_kernel::table_features::{
    TableFeature, TABLE_FEATURES_MIN_READER_VERSION, TABLE_FEATURES_MIN_WRITER_VERSION,
};
use delta_kernel::table_properties::TableProperties;
use delta_kernel::transaction::create_table::{create_table, CreateTableTransaction};
use delta_kernel::DeltaResult;
use rstest::rstest;
use serde_json::Value;
use test_utils::{assert_result_error_with_message, test_table_setup};

/// Helper to create a simple two-column schema for tests.
/// Shared with sub-modules.
pub(crate) fn simple_schema() -> DeltaResult<Arc<StructType>> {
    Ok(Arc::new(StructType::try_new(vec![
        StructField::new("id", DataType::INTEGER, true),
        StructField::new("value", DataType::STRING, true),
    ])?))
}

/// Helper to create a three-column schema for partition tests (id, date, value).
/// Shared with sub-modules.
pub(crate) fn partition_test_schema() -> DeltaResult<Arc<StructType>> {
    Ok(Arc::new(StructType::try_new(vec![
        StructField::new("id", DataType::INTEGER, true),
        StructField::new("date", DataType::DATE, true),
        StructField::new("value", DataType::STRING, true),
    ])?))
}

#[tokio::test]
async fn test_create_simple_table() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    // Create schema for an events table
    let schema = Arc::new(StructType::try_new(vec![
        StructField::new("event_id", DataType::LONG, true),
        StructField::new("user_id", DataType::LONG, true),
        StructField::new("event_type", DataType::STRING, true),
        StructField::new("timestamp", DataType::TIMESTAMP, true),
        StructField::new("properties", DataType::STRING, true),
    ])?);

    // Create table using new API
    let _ = create_table(&table_path, schema.clone(), "DeltaKernel-RS/0.17.0")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    // Verify table was created
    let table_url = delta_kernel::try_parse_uri(&table_path)?;
    let snapshot = Snapshot::builder_for(table_url).build(engine.as_ref())?;

    assert_eq!(snapshot.version(), 0);
    assert_eq!(snapshot.schema().fields().len(), 5);

    // Verify protocol versions via snapshot
    let protocol = snapshot.table_configuration().protocol();
    assert_eq!(
        protocol.min_reader_version(),
        TABLE_FEATURES_MIN_READER_VERSION
    );
    assert_eq!(
        protocol.min_writer_version(),
        TABLE_FEATURES_MIN_WRITER_VERSION
    );
    // Verify no reader/writer features are set (empty for table features mode)
    assert!(protocol.reader_features().is_some_and(|f| f.is_empty()));
    assert!(protocol.writer_features().is_some_and(|f| f.is_empty()));

    // Verify no table properties are set via public API
    assert_eq!(snapshot.table_properties(), &TableProperties::default());

    // Verify schema field names
    let field_names: Vec<_> = snapshot
        .schema()
        .fields()
        .map(|f| f.name().to_string())
        .collect();
    assert!(field_names.contains(&"event_id".to_string()));
    assert!(field_names.contains(&"user_id".to_string()));
    assert!(field_names.contains(&"event_type".to_string()));
    assert!(field_names.contains(&"timestamp".to_string()));
    assert!(field_names.contains(&"properties".to_string()));

    Ok(())
}

#[tokio::test]
async fn test_create_table_with_user_domain_metadata() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let schema = simple_schema()?;

    // Create table with domainMetadata feature enabled
    let txn = create_table(&table_path, schema, "Test/1.0")
        .with_table_properties([("delta.feature.domainMetadata", "supported")])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?;

    // Add user domain metadata during table creation
    let domain = "app.settings";
    let config = r#"{"version": 1, "enabled": true}"#;

    let _ = txn
        .with_domain_metadata(domain.to_string(), config.to_string())
        .commit(engine.as_ref())?;

    // Load snapshot and verify domain metadata was persisted
    let table_url = delta_kernel::try_parse_uri(&table_path)?;
    let snapshot = Snapshot::builder_for(table_url).build(engine.as_ref())?;

    // Verify domainMetadata feature is enabled in protocol
    assert!(
        snapshot
            .table_configuration()
            .is_feature_supported(&TableFeature::DomainMetadata),
        "DomainMetadata feature should be enabled"
    );

    // Verify domain metadata string was persisted correctly
    let retrieved_config = snapshot.get_domain_metadata(domain, engine.as_ref())?;
    assert_eq!(
        retrieved_config,
        Some(config.to_string()),
        "Domain metadata should be persisted and retrievable"
    );

    // Parse and verify the JSON contents
    let parsed: Value = serde_json::from_str(retrieved_config.as_ref().unwrap())?;
    assert_eq!(parsed["version"], 1);
    assert_eq!(parsed["enabled"], true);

    // Verify non-existent domain returns None
    let missing = snapshot.get_domain_metadata("nonexistent.domain", engine.as_ref())?;
    assert!(missing.is_none(), "Non-existent domain should return None");

    Ok(())
}

#[tokio::test]
async fn test_create_table_already_exists() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    // Create schema for a user profiles table
    let schema = Arc::new(StructType::try_new(vec![
        StructField::new("user_id", DataType::LONG, true),
        StructField::new("username", DataType::STRING, true),
        StructField::new("email", DataType::STRING, true),
        StructField::new("created_at", DataType::TIMESTAMP, true),
        StructField::new("is_active", DataType::BOOLEAN, true),
    ])?);

    // Create table first time
    let _ = create_table(&table_path, schema.clone(), "UserManagementService/1.2.0")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    // Try to create again - should fail at build time (table already exists)
    let result = create_table(&table_path, schema.clone(), "UserManagementService/1.2.0")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()));

    assert_result_error_with_message(result, "already exists");

    Ok(())
}

#[tokio::test]
async fn test_create_table_empty_schema_not_supported() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    // Create empty schema
    let schema = Arc::new(StructType::try_new(vec![])?);

    // Try to create table with empty schema - should fail at build time
    let result = create_table(&table_path, schema, "InvalidApp/0.1.0")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()));

    assert_result_error_with_message(result, "cannot be empty");

    Ok(())
}

fn top_level_non_null_schema() -> Arc<StructType> {
    Arc::new(
        StructType::try_new(vec![
            StructField::new("id", DataType::INTEGER, false),
            StructField::new("value", DataType::STRING, true),
        ])
        .expect("non-null top-level schema should be valid"),
    )
}

fn nested_non_null_schema() -> Arc<StructType> {
    let nested = StructType::try_new(vec![StructField::new("child", DataType::INTEGER, false)])
        .expect("nested non-null schema should be valid");
    Arc::new(
        StructType::try_new(vec![StructField::new(
            "nested",
            DataType::Struct(Box::new(nested)),
            true,
        )])
        .expect("top-level nested schema should be valid"),
    )
}

#[rstest]
#[case::top_level_non_null(top_level_non_null_schema())]
#[case::nested_non_null(nested_non_null_schema())]
fn test_create_table_non_null_columns_require_invariants_feature(
    #[case] schema: Arc<StructType>,
) -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let result = create_table(&table_path, schema, "InvalidApp/0.1.0")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()));

    assert_result_error_with_message(result, "Non-null column");

    Ok(())
}

#[tokio::test]
async fn test_create_table_log_actions() -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    // Create schema
    let schema = Arc::new(StructType::try_new(vec![
        StructField::new("user_id", DataType::LONG, true),
        StructField::new("action", DataType::STRING, true),
    ])?);

    let engine_info = "AuditService/2.1.0";

    // Create table
    let _ = create_table(&table_path, schema, engine_info)
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    // Read the actual Delta log file
    let log_file_path = format!("{table_path}/_delta_log/00000000000000000000.json");
    let log_contents = std::fs::read_to_string(&log_file_path).expect("Failed to read log file");

    // Parse each line (each line is a separate JSON action)
    let actions: Vec<Value> = log_contents
        .lines()
        .map(|line| serde_json::from_str(line).expect("Failed to parse JSON"))
        .collect();

    // Verify we have exactly 3 actions: CommitInfo, Protocol, Metadata
    // CommitInfo is first to comply with ICT (In-Commit Timestamps) protocol requirements
    assert_eq!(
        actions.len(),
        3,
        "Expected 3 actions (commitInfo, protocol, metaData), found {}",
        actions.len()
    );

    // Verify CommitInfo action (first for ICT compliance)
    let commit_info_action = &actions[0];
    assert!(
        commit_info_action.get("commitInfo").is_some(),
        "First action should be commitInfo"
    );
    let commit_info = commit_info_action.get("commitInfo").unwrap();
    assert!(
        commit_info.get("timestamp").is_some(),
        "CommitInfo should have timestamp"
    );
    assert!(
        commit_info.get("engineInfo").is_some(),
        "CommitInfo should have engineInfo"
    );
    assert!(
        commit_info.get("operation").is_some(),
        "CommitInfo should have operation"
    );
    assert_eq!(
        commit_info["operation"], "CREATE TABLE",
        "Operation should be CREATE TABLE"
    );

    // Verify Protocol action
    let protocol_action = &actions[1];
    assert!(
        protocol_action.get("protocol").is_some(),
        "Second action should be protocol"
    );
    let protocol = protocol_action.get("protocol").unwrap();
    assert_eq!(
        protocol["minReaderVersion"],
        TABLE_FEATURES_MIN_READER_VERSION
    );
    assert_eq!(
        protocol["minWriterVersion"],
        TABLE_FEATURES_MIN_WRITER_VERSION
    );

    // Verify Metadata action
    let metadata_action = &actions[2];
    assert!(
        metadata_action.get("metaData").is_some(),
        "Third action should be metaData"
    );
    let metadata = metadata_action.get("metaData").unwrap();
    assert!(metadata.get("id").is_some(), "Metadata should have id");
    assert!(
        metadata.get("schemaString").is_some(),
        "Metadata should have schemaString"
    );
    assert!(
        metadata.get("createdTime").is_some(),
        "Metadata should have createdTime"
    );

    // Additional CommitInfo verification (commit_info was already extracted from actions[0] above)
    assert_eq!(
        commit_info["engineInfo"], engine_info,
        "CommitInfo should contain the engine info we provided"
    );

    assert!(
        commit_info.get("txnId").is_some(),
        "CommitInfo should have txnId"
    );

    // Verify kernelVersion is present
    let kernel_version = commit_info.get("kernelVersion");
    assert!(
        kernel_version.is_some(),
        "CommitInfo should have kernelVersion"
    );
    assert!(
        kernel_version.unwrap().as_str().unwrap().starts_with("v"),
        "Kernel version should start with 'v'"
    );

    Ok(())
}

/// Helper to create a `CreateTableTransaction` for tests.
fn create_test_create_table_txn() -> DeltaResult<(
    Arc<impl delta_kernel::Engine>,
    CreateTableTransaction,
    tempfile::TempDir,
)> {
    let (tempdir, table_path, engine) = test_table_setup()?;
    let schema = Arc::new(
        StructType::try_new(vec![
            StructField::nullable("id", DataType::INTEGER),
            StructField::nullable("name", DataType::STRING),
        ])
        .expect("valid schema"),
    );
    let txn = create_table(&table_path, schema, "test_engine")
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?;
    Ok((engine, txn, tempdir))
}

#[tokio::test]
async fn test_create_table_txn_debug() -> DeltaResult<()> {
    let (_engine, txn, _tempdir) = create_test_create_table_txn()?;
    let debug_str = format!("{txn:?}");
    assert!(
        debug_str.contains("Transaction") && debug_str.contains("create_table"),
        "Debug output should contain Transaction info: {debug_str}"
    );
    Ok(())
}

#[rstest]
// ReaderWriter features (AlwaysIfSupported)
#[case("vacuumProtocolCheck", TableFeature::VacuumProtocolCheck, true, true)]
#[case("v2Checkpoint", TableFeature::V2Checkpoint, true, true)]
// ReaderWriter features (EnabledIf -- feature signal alone does not enable)
#[case("deletionVectors", TableFeature::DeletionVectors, true, false)]
#[case("typeWidening", TableFeature::TypeWidening, true, false)]
// WriterOnly features (EnabledIf -- feature signal alone does not enable)
#[case("appendOnly", TableFeature::AppendOnly, false, false)]
#[case("changeDataFeed", TableFeature::ChangeDataFeed, false, false)]
#[case("rowTracking", TableFeature::RowTracking, false, false)]
fn test_create_table_with_feature_signal(
    #[case] feature_name: &str,
    #[case] feature: TableFeature,
    #[case] is_reader_writer: bool,
    #[case] enabled_when_supported: bool,
) -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let property_key = format!("delta.feature.{feature_name}");
    let _ = create_table(&table_path, simple_schema()?, "Test/1.0")
        .with_table_properties([(property_key.as_str(), "supported")])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    let snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    let table_config = snapshot.table_configuration();

    assert!(
        table_config.is_feature_supported(&feature),
        "{feature_name} should be supported"
    );
    assert_eq!(
        table_config.is_feature_enabled(&feature),
        enabled_when_supported,
        "{feature_name}: is_feature_enabled should be {enabled_when_supported}"
    );
    let protocol = table_config.protocol();
    assert!(
        protocol
            .writer_features()
            .is_some_and(|f| f.contains(&feature)),
        "{feature_name} should be in writer features"
    );
    if is_reader_writer {
        assert!(
            protocol
                .reader_features()
                .is_some_and(|f| f.contains(&feature)),
            "{feature_name} should be in reader features"
        );
    }

    Ok(())
}

#[rstest]
fn test_create_table_with_checkpoint_stats_properties(
    #[values(true, false)] write_stats_as_json: bool,
    #[values(true, false)] write_stats_as_struct: bool,
) -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let json_val = write_stats_as_json.to_string();
    let struct_val = write_stats_as_struct.to_string();

    let _ = create_table(&table_path, simple_schema()?, "Test/1.0")
        .with_table_properties([
            ("delta.checkpoint.writeStatsAsJson", json_val.as_str()),
            ("delta.checkpoint.writeStatsAsStruct", struct_val.as_str()),
        ])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    let snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    let tp = snapshot.table_properties();
    assert_eq!(tp.checkpoint_write_stats_as_json, Some(write_stats_as_json));
    assert_eq!(
        tp.checkpoint_write_stats_as_struct,
        Some(write_stats_as_struct)
    );

    Ok(())
}

#[rstest]
// ReaderWriter features
#[case("delta.enableDeletionVectors", TableFeature::DeletionVectors, true)]
#[case("delta.enableTypeWidening", TableFeature::TypeWidening, true)]
// WriterOnly features
#[case("delta.enableChangeDataFeed", TableFeature::ChangeDataFeed, false)]
#[case("delta.appendOnly", TableFeature::AppendOnly, false)]
#[case("delta.enableRowTracking", TableFeature::RowTracking, false)]
fn test_create_table_with_enablement_property(
    #[case] property: &str,
    #[case] feature: TableFeature,
    #[case] is_reader_writer: bool,
    #[values(true, false)] expect_enabled: bool,
) -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;
    let value = expect_enabled.to_string();

    let _ = create_table(&table_path, simple_schema()?, "Test/1.0")
        .with_table_properties([(property, value.as_str())])
        .build(engine.as_ref(), Box::new(FileSystemCommitter::new()))?
        .commit(engine.as_ref())?;

    let snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
    let table_config = snapshot.table_configuration();

    assert_eq!(
        table_config.is_feature_supported(&feature),
        expect_enabled,
        "{property}={value}: feature supported should be {expect_enabled}"
    );
    assert_eq!(
        table_config.is_feature_enabled(&feature),
        expect_enabled,
        "{property}={value}: feature enabled should be {expect_enabled}"
    );
    let protocol = table_config.protocol();
    assert_eq!(
        protocol
            .writer_features()
            .is_some_and(|f| f.contains(&feature)),
        expect_enabled,
        "{property}={value}: in writer features should be {expect_enabled}"
    );
    if is_reader_writer {
        assert_eq!(
            protocol
                .reader_features()
                .is_some_and(|f| f.contains(&feature)),
            expect_enabled,
            "{property}={value}: in reader features should be {expect_enabled}"
        );
    }

    Ok(())
}

#[rstest]
#[case::without_cm(false)]
#[case::with_cm(true)]
fn test_create_table_special_char_column_name(#[case] cm_enabled: bool) -> DeltaResult<()> {
    let (_temp_dir, table_path, engine) = test_table_setup()?;

    let schema = Arc::new(StructType::try_new(vec![
        StructField::new("valid_col", DataType::INTEGER, true),
        StructField::new("bad column", DataType::STRING, true),
    ])?);

    let mut builder = create_table(&table_path, schema, "Test/1.0");
    if cm_enabled {
        builder = builder.with_table_properties([("delta.columnMapping.mode", "name")]);
    }
    let result = builder.build(engine.as_ref(), Box::new(FileSystemCommitter::new()));

    if cm_enabled {
        let txn = result?;
        let _ = txn.commit(engine.as_ref())?;

        let snapshot = Snapshot::builder_for(&table_path).build(engine.as_ref())?;
        assert_eq!(snapshot.version(), 0);
        let field_names: Vec<_> = snapshot
            .schema()
            .fields()
            .map(|f| f.name().clone())
            .collect();
        assert!(
            field_names.contains(&"bad column".to_string()),
            "Schema should contain field 'bad column', got: {field_names:?}"
        );
    } else {
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("invalid character"),
            "Expected invalid character error, got: {err}"
        );
    }

    Ok(())
}