datafusion-ducklake 0.5.0

DuckLake query engine for rust, built with datafusion.
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! Integration tests for SQL `UPDATE` support (SQLite metadata backend).
//!
//! Exercises `UPDATE t SET col = expr [, ...] [WHERE ...]` end-to-end through
//! DataFusion's SQL interface against a writable DuckLake catalog: affected-row
//! count, the resulting values, atomicity (one snapshot), rowid-lineage
//! preservation across the file rewrite, the change feed (preimage/postimage),
//! and update-all.

#![cfg(all(feature = "write-sqlite", feature = "metadata-sqlite"))]

use std::sync::Arc;

use arrow::array::{Array, Int32Array, Int64Array, UInt64Array};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
use datafusion::prelude::*;
use object_store::local::LocalFileSystem;
use sqlx::sqlite::SqlitePool;
use tempfile::TempDir;

use datafusion_ducklake::{
    DuckLakeCatalog, DuckLakeTableWriter, MetadataProvider, MetadataWriter, SqliteMetadataProvider,
    SqliteMetadataWriter, register_ducklake_functions,
};

/// The `(id, val)` schema used throughout.
fn table_schema() -> Arc<Schema> {
    Arc::new(Schema::new(vec![
        Field::new("id", DataType::Int32, false),
        Field::new("val", DataType::Int32, false),
    ]))
}

fn object_store() -> Arc<dyn object_store::ObjectStore> {
    Arc::new(LocalFileSystem::new())
}

/// A writable SQLite-backed catalog + data dir in `temp_dir`.
async fn make_writer(temp_dir: &TempDir) -> SqliteMetadataWriter {
    let db_path = temp_dir.path().join("test.db");
    let data_path = temp_dir.path().join("data");
    std::fs::create_dir_all(&data_path).unwrap();
    let conn_str = format!("sqlite:{}?mode=rwc", db_path.display());
    let writer = SqliteMetadataWriter::new_with_init(&conn_str)
        .await
        .unwrap();
    writer.set_data_path(data_path.to_str().unwrap()).unwrap();
    writer
}

/// Seed a single data file `t(id, val)` from the given rows via the low-level
/// writer (deterministic file layout: `row_id_start = 0`, positions `0..n`).
async fn seed_table(temp_dir: &TempDir, ids: Vec<i32>, vals: Vec<i32>) {
    let writer = Arc::new(make_writer(temp_dir).await);
    let batch = RecordBatch::try_new(
        table_schema(),
        vec![Arc::new(Int32Array::from(ids)), Arc::new(Int32Array::from(vals))],
    )
    .unwrap();
    DuckLakeTableWriter::new(writer, object_store())
        .unwrap()
        .write_table("main", "t", &[batch])
        .await
        .unwrap();
}

/// Append a second data file to `t`.
async fn append_file(temp_dir: &TempDir, ids: Vec<i32>, vals: Vec<i32>) {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}?mode=rwc", db_path.display());
    let writer = Arc::new(SqliteMetadataWriter::new(&conn_str).await.unwrap());
    let batch = RecordBatch::try_new(
        table_schema(),
        vec![Arc::new(Int32Array::from(ids)), Arc::new(Int32Array::from(vals))],
    )
    .unwrap();
    DuckLakeTableWriter::new(writer, object_store())
        .unwrap()
        .append_table("main", "t", &[batch])
        .await
        .unwrap();
}

/// A writable SessionContext bound to the seeded catalog.
async fn writable_ctx(temp_dir: &TempDir) -> SessionContext {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}?mode=rwc", db_path.display());
    let writer = SqliteMetadataWriter::new(&conn_str).await.unwrap();
    let provider = SqliteMetadataProvider::new(&conn_str).await.unwrap();
    let catalog = DuckLakeCatalog::with_writer(Arc::new(provider), Arc::new(writer)).unwrap();
    let ctx = SessionContext::new();
    ctx.register_catalog("ducklake", Arc::new(catalog));
    ctx
}

/// A read-only SessionContext; when `row_lineage`, tables expose the `rowid`
/// column.
async fn read_ctx(temp_dir: &TempDir, row_lineage: bool) -> SessionContext {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}", db_path.display());
    let provider = SqliteMetadataProvider::new(&conn_str).await.unwrap();
    let catalog = DuckLakeCatalog::new(provider)
        .unwrap()
        .with_row_lineage(row_lineage);
    let ctx = SessionContext::new();
    ctx.register_catalog("ducklake", Arc::new(catalog));
    ctx
}

/// A SessionContext with the `ducklake_*()` table functions registered.
async fn functions_ctx(temp_dir: &TempDir) -> SessionContext {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}", db_path.display());
    let provider = SqliteMetadataProvider::new(&conn_str).await.unwrap();
    let provider_arc: Arc<dyn MetadataProvider> =
        Arc::new(SqliteMetadataProvider::new(&conn_str).await.unwrap());
    let catalog = DuckLakeCatalog::new(provider).unwrap();
    let ctx = SessionContext::new();
    ctx.register_catalog("ducklake", Arc::new(catalog));
    register_ducklake_functions(&ctx, provider_arc);
    ctx
}

/// Run `sql` and return the single `count` (UInt64) it yields (INSERT/UPDATE).
async fn run_dml_count(ctx: &SessionContext, sql: &str) -> u64 {
    let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap();
    assert_eq!(batches.len(), 1, "DML should yield exactly one batch");
    assert_eq!(batches[0].num_rows(), 1, "DML count batch has one row");
    batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<UInt64Array>()
        .expect("count column is UInt64")
        .value(0)
}

/// `(id, val)` from `t`, ascending by id, through the full read path.
async fn read_pairs(temp_dir: &TempDir) -> Vec<(i32, i32)> {
    let ctx = read_ctx(temp_dir, false).await;
    let batches = ctx
        .sql("SELECT id, val FROM ducklake.main.t ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let mut rows = Vec::new();
    for b in &batches {
        let ids = b.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
        let vals = b.column(1).as_any().downcast_ref::<Int32Array>().unwrap();
        for i in 0..b.num_rows() {
            rows.push((ids.value(i), vals.value(i)));
        }
    }
    rows
}

/// `(rowid, id, val)` from `t`, ascending by id, via the row-lineage read path.
async fn read_rowid_rows(temp_dir: &TempDir) -> Vec<(i64, i32, i32)> {
    let ctx = read_ctx(temp_dir, true).await;
    let batches = ctx
        .sql("SELECT rowid, id, val FROM ducklake.main.t ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let mut rows = Vec::new();
    for b in &batches {
        let rowids = b.column(0).as_any().downcast_ref::<Int64Array>().unwrap();
        let ids = b.column(1).as_any().downcast_ref::<Int32Array>().unwrap();
        let vals = b.column(2).as_any().downcast_ref::<Int32Array>().unwrap();
        for i in 0..b.num_rows() {
            assert!(!rowids.is_null(i), "rowid must not be NULL after UPDATE");
            rows.push((rowids.value(i), ids.value(i), vals.value(i)));
        }
    }
    rows
}

async fn snapshot_count(temp_dir: &TempDir) -> i64 {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}", db_path.display());
    let pool = SqlitePool::connect(&conn_str).await.unwrap();
    sqlx::query_scalar("SELECT COUNT(*) FROM ducklake_snapshot")
        .fetch_one(&pool)
        .await
        .unwrap()
}

async fn max_snapshot(temp_dir: &TempDir) -> i64 {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}", db_path.display());
    let pool = SqlitePool::connect(&conn_str).await.unwrap();
    sqlx::query_scalar("SELECT COALESCE(MAX(snapshot_id), 0) FROM ducklake_snapshot")
        .fetch_one(&pool)
        .await
        .unwrap()
}

async fn live_data_file_count(temp_dir: &TempDir) -> i64 {
    let db_path = temp_dir.path().join("test.db");
    let conn_str = format!("sqlite:{}", db_path.display());
    let pool = SqlitePool::connect(&conn_str).await.unwrap();
    sqlx::query_scalar("SELECT COUNT(*) FROM ducklake_data_file WHERE end_snapshot IS NULL")
        .fetch_one(&pool)
        .await
        .unwrap()
}

// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn update_sets_value_where_id() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2, 3, 4], vec![10, 20, 30, 40]).await;
    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 20), (3, 30), (4, 40)],
        "baseline"
    );

    let ctx = writable_ctx(&temp_dir).await;
    let count = run_dml_count(&ctx, "UPDATE ducklake.main.t SET val = 200 WHERE id = 2").await;
    assert_eq!(count, 1, "one row matched id = 2");

    let rows = read_pairs(&temp_dir).await;
    assert_eq!(
        rows,
        vec![(1, 10), (2, 200), (3, 30), (4, 40)],
        "id=2 gets the new value; others unchanged"
    );
    assert_eq!(rows.len(), 4, "row count is unchanged by UPDATE");
}

#[tokio::test(flavor = "multi_thread")]
async fn update_expression_referencing_column() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2, 3], vec![10, 20, 30]).await;

    let ctx = writable_ctx(&temp_dir).await;
    // Assignment expression references the column being updated.
    let count = run_dml_count(
        &ctx,
        "UPDATE ducklake.main.t SET val = val + 5 WHERE id >= 2",
    )
    .await;
    assert_eq!(count, 2, "ids 2 and 3 match");

    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 25), (3, 35)],
        "matched rows get val + 5"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn update_multi_row_multi_file_is_one_snapshot() {
    let temp_dir = TempDir::new().unwrap();
    // Two data files: A=(1,10),(2,20); B=(3,30),(4,40).
    seed_table(&temp_dir, vec![1, 2], vec![10, 20]).await;
    append_file(&temp_dir, vec![3, 4], vec![30, 40]).await;
    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 20), (3, 30), (4, 40)],
        "baseline across two files"
    );
    assert_eq!(
        live_data_file_count(&temp_dir).await,
        2,
        "two live data files"
    );

    let before = snapshot_count(&temp_dir).await;

    // Update one row from each file in a single statement.
    let ctx = writable_ctx(&temp_dir).await;
    let count = run_dml_count(
        &ctx,
        "UPDATE ducklake.main.t SET val = val + 1 WHERE id IN (2, 3)",
    )
    .await;
    assert_eq!(count, 2, "one row from each file matched");

    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 21), (3, 31), (4, 40)],
        "one row updated in each file; the rest unchanged"
    );

    let after = snapshot_count(&temp_dir).await;
    assert_eq!(
        after - before,
        1,
        "the whole multi-file update is exactly ONE new snapshot (atomic)"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn update_preserves_rowid_lineage() {
    let temp_dir = TempDir::new().unwrap();
    // One file: rowids 0,1,2,3 for ids 1,2,3,4.
    seed_table(&temp_dir, vec![1, 2, 3, 4], vec![10, 20, 30, 40]).await;
    assert_eq!(
        read_rowid_rows(&temp_dir).await,
        vec![(0, 1, 10), (1, 2, 20), (2, 3, 30), (3, 4, 40)],
        "baseline rowids"
    );

    let ctx = writable_ctx(&temp_dir).await;
    let count = run_dml_count(
        &ctx,
        "UPDATE ducklake.main.t SET val = val * 10 WHERE id IN (2, 4)",
    )
    .await;
    assert_eq!(count, 2);

    // The updated rows keep their ORIGINAL rowids (1 and 3), proving lineage
    // survives the file rewrite via the embedded row-id column.
    assert_eq!(
        read_rowid_rows(&temp_dir).await,
        vec![(0, 1, 10), (1, 2, 200), (2, 3, 30), (3, 4, 400)],
        "rowids 1 and 3 are retained by their updated rows"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn update_all_rows_without_where() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2, 3], vec![10, 20, 30]).await;

    let ctx = writable_ctx(&temp_dir).await;
    let count = run_dml_count(&ctx, "UPDATE ducklake.main.t SET val = 99").await;
    assert_eq!(count, 3, "no WHERE updates every row");

    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 99), (2, 99), (3, 99)],
        "all rows set to 99"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn update_change_feed_emits_preimage_and_postimage() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2, 3], vec![10, 20, 30]).await;

    let before = max_snapshot(&temp_dir).await;
    let ctx = writable_ctx(&temp_dir).await;
    let count = run_dml_count(&ctx, "UPDATE ducklake.main.t SET val = 200 WHERE id = 2").await;
    assert_eq!(count, 1);
    let after = max_snapshot(&temp_dir).await;
    assert_eq!(after - before, 1, "one update snapshot");

    // The change feed over the update snapshot pairs the delete + insert that
    // share rowid 1 into update_preimage (old) + update_postimage (new).
    let fctx = functions_ctx(&temp_dir).await;
    let sql = format!(
        "SELECT id, val, change_type \
         FROM ducklake_table_changes('main.t', {before}, {after}) \
         ORDER BY change_type, id"
    );
    let batches = fctx.sql(&sql).await.unwrap().collect().await.unwrap();

    let mut got: Vec<(i32, i32, String)> = Vec::new();
    for b in &batches {
        let ids = b.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
        let vals = b.column(1).as_any().downcast_ref::<Int32Array>().unwrap();
        let ct = b.column(2);
        let ct = ct
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .map(|a| {
                (0..a.len())
                    .map(|i| a.value(i).to_string())
                    .collect::<Vec<_>>()
            })
            .or_else(|| {
                ct.as_any()
                    .downcast_ref::<arrow::array::StringViewArray>()
                    .map(|a| {
                        (0..a.len())
                            .map(|i| a.value(i).to_string())
                            .collect::<Vec<_>>()
                    })
            })
            .expect("change_type is a string column");
        for (i, ct_val) in ct.iter().enumerate() {
            got.push((ids.value(i), vals.value(i), ct_val.clone()));
        }
    }

    assert_eq!(
        got,
        vec![(2, 200, "update_postimage".to_string()), (2, 20, "update_preimage".to_string()),],
        "the update surfaces as a preimage (old) + postimage (new) pair"
    );
}

/// A pure delete (no matching insert) must NOT surface in `ducklake_table_changes`
/// as an update: the correlation only pairs a delete + insert sharing a rowid.
#[tokio::test(flavor = "multi_thread")]
async fn update_change_feed_ignores_unrelated_inserts() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2], vec![10, 20]).await;

    let before = max_snapshot(&temp_dir).await;
    let ctx = writable_ctx(&temp_dir).await;
    run_dml_count(&ctx, "UPDATE ducklake.main.t SET val = 99 WHERE id = 1").await;
    let after = max_snapshot(&temp_dir).await;

    // Exactly one preimage + one postimage for the single updated row; no
    // spurious plain insert/delete rows.
    let fctx = functions_ctx(&temp_dir).await;
    let sql = format!(
        "SELECT change_type, COUNT(*) AS n \
         FROM ducklake_table_changes('main.t', {before}, {after}) \
         GROUP BY change_type ORDER BY change_type"
    );
    let batches = fctx.sql(&sql).await.unwrap().collect().await.unwrap();
    let mut counts: Vec<(String, i64)> = Vec::new();
    for b in &batches {
        let ct = b.column(0);
        let ct = ct
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .map(|a| {
                (0..a.len())
                    .map(|i| a.value(i).to_string())
                    .collect::<Vec<_>>()
            })
            .or_else(|| {
                ct.as_any()
                    .downcast_ref::<arrow::array::StringViewArray>()
                    .map(|a| {
                        (0..a.len())
                            .map(|i| a.value(i).to_string())
                            .collect::<Vec<_>>()
                    })
            })
            .unwrap();
        let n = b.column(1).as_any().downcast_ref::<Int64Array>().unwrap();
        for (i, ct_val) in ct.iter().enumerate() {
            counts.push((ct_val.clone(), n.value(i)));
        }
    }
    assert_eq!(
        counts,
        vec![("update_postimage".to_string(), 1), ("update_preimage".to_string(), 1),],
        "only the correlated pair is surfaced"
    );
}

/// A second UPDATE in the SAME session that re-touches a file the first UPDATE
/// modified must abort with a clear conflict (the catalog pins its snapshot to
/// the pre-update generation) — and must NOT corrupt: the first update's result
/// is preserved and the second row is left unchanged.
#[tokio::test(flavor = "multi_thread")]
async fn update_second_in_session_conflicts_without_corruption() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2, 3, 4], vec![10, 20, 30, 40]).await;

    let ctx = writable_ctx(&temp_dir).await;
    assert_eq!(
        run_dml_count(&ctx, "UPDATE ducklake.main.t SET val = 200 WHERE id = 2").await,
        1
    );
    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 200), (3, 30), (4, 40)]
    );

    // Second UPDATE (same session, same file) — aborts on the commit CAS.
    let err = ctx
        .sql("UPDATE ducklake.main.t SET val = 300 WHERE id = 3")
        .await
        .unwrap()
        .collect()
        .await
        .expect_err("second in-session UPDATE must conflict, not silently corrupt");
    let msg = err.to_string();
    assert!(
        msg.contains("Re-open the catalog") && msg.contains("THIS session"),
        "conflict message must explain the pinned-snapshot cause, got: {msg}"
    );

    // Clean abort: id=2 stays updated, id=3 unchanged, no row lost/duplicated.
    assert_eq!(
        read_pairs(&temp_dir).await,
        vec![(1, 10), (2, 200), (3, 30), (4, 40)],
        "aborted UPDATE leaves the first update intact and id=3 unchanged"
    );
}

/// CDC over a range that mixes an unrelated plain INSERT with an UPDATE: the
/// insert must surface as `insert`, and the update as a preimage/postimage pair.
/// Exercises the correlated path together with a non-embedded insert file (the
/// `update_change_feed_ignores_unrelated_inserts` test does not actually insert).
#[tokio::test(flavor = "multi_thread")]
async fn update_change_feed_mixed_insert_and_update() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2], vec![10, 20]).await;
    let before = max_snapshot(&temp_dir).await;

    // Snapshot +1: a plain INSERT (no embedded rowid).
    run_dml_count(
        &writable_ctx(&temp_dir).await,
        "INSERT INTO ducklake.main.t VALUES (9, 90)",
    )
    .await;
    // Snapshot +2: an UPDATE.
    run_dml_count(
        &writable_ctx(&temp_dir).await,
        "UPDATE ducklake.main.t SET val = 100 WHERE id = 1",
    )
    .await;
    let after = max_snapshot(&temp_dir).await;

    let fctx = functions_ctx(&temp_dir).await;
    let sql = format!(
        "SELECT id, val, change_type FROM ducklake_table_changes('main.t', {before}, {after}) \
         ORDER BY change_type, id"
    );
    let batches = fctx.sql(&sql).await.unwrap().collect().await.unwrap();
    let mut got: Vec<(i32, i32, String)> = Vec::new();
    for b in &batches {
        let ids = b.column(0).as_any().downcast_ref::<Int32Array>().unwrap();
        let vals = b.column(1).as_any().downcast_ref::<Int32Array>().unwrap();
        let ct = b.column(2);
        let cts: Vec<String> = ct
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .map(|a| (0..a.len()).map(|i| a.value(i).to_string()).collect())
            .or_else(|| {
                ct.as_any()
                    .downcast_ref::<arrow::array::StringViewArray>()
                    .map(|a| (0..a.len()).map(|i| a.value(i).to_string()).collect())
            })
            .expect("change_type is a string column");
        for (i, c) in cts.iter().enumerate() {
            got.push((ids.value(i), vals.value(i), c.clone()));
        }
    }
    assert_eq!(
        got,
        vec![
            (9, 90, "insert".to_string()),
            (1, 100, "update_postimage".to_string()),
            (1, 10, "update_preimage".to_string()),
        ],
        "unrelated insert stays an insert; the update is a preimage/postimage pair"
    );
}

/// CDC over an INSERT-only range (no UPDATE/DELETE): every added row is an
/// `insert` and nothing is reclassified. Guards the fast path that must NOT do
/// the correlated delete+insert probing when the range applied no deletes.
#[tokio::test(flavor = "multi_thread")]
async fn change_feed_insert_only_range_is_all_inserts() {
    let temp_dir = TempDir::new().unwrap();
    seed_table(&temp_dir, vec![1, 2], vec![10, 20]).await;
    let before = max_snapshot(&temp_dir).await;
    run_dml_count(
        &writable_ctx(&temp_dir).await,
        "INSERT INTO ducklake.main.t VALUES (3, 30)",
    )
    .await;
    let after = max_snapshot(&temp_dir).await;

    let fctx = functions_ctx(&temp_dir).await;
    let sql = format!(
        "SELECT change_type, COUNT(*) AS n FROM ducklake_table_changes('main.t', {before}, {after}) \
         GROUP BY change_type ORDER BY change_type"
    );
    let batches = fctx.sql(&sql).await.unwrap().collect().await.unwrap();
    let mut counts: Vec<(String, i64)> = Vec::new();
    for b in &batches {
        let ct = b.column(0);
        let cts: Vec<String> = ct
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .map(|a| (0..a.len()).map(|i| a.value(i).to_string()).collect())
            .or_else(|| {
                ct.as_any()
                    .downcast_ref::<arrow::array::StringViewArray>()
                    .map(|a| (0..a.len()).map(|i| a.value(i).to_string()).collect())
            })
            .unwrap();
        let n = b.column(1).as_any().downcast_ref::<Int64Array>().unwrap();
        for (i, c) in cts.iter().enumerate() {
            counts.push((c.clone(), n.value(i)));
        }
    }
    assert_eq!(
        counts,
        vec![("insert".to_string(), 1)],
        "insert-only range yields only inserts"
    );
}