moraine 0.6.0

A SlateDB-backed catalog for DuckLake
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
//! The staged-row commit path: DuckLake authors rows over the ABI instead
//! of driving [`crate::transaction::Transaction`]'s verbs, and this module
//! turns the accumulated rows into one atomic store write.
//!
//! Three rules bound this path: every value DuckLake supplies is stored
//! **verbatim** except one interpreted convention (an `UPDATE` setting
//! `end_snapshot` becomes current-delete + history-write); one commit is one
//! atomic batch, reusing [`super::commit::diff_writes`]; and a lost race at
//! commit is **never retried** — DuckLake authored the ids and counters in
//! the batch. The loser's error always carries the substring `conflict`
//! (via [`Error::CommitConflict`]'s `Display`), the wire contract
//! DuckLake's retry loop scans for.
//!
//! Translation applies every staged row to a cloned working
//! [`CatalogSnapshot`], then diffs it against the unmodified base exactly
//! as a verb-path commit diffs its closure's output. An `UPDATE ... SET
//! end_snapshot` row's value is validated, not trusted: DuckLake always
//! sets it to this commit's own new snapshot id — the value `diff_writes`
//! stamps on its own — so a mismatch is drift caught loudly.

use std::{
    collections::{BTreeSet, HashMap, HashSet},
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

use slatedb::DbTransaction;
use tracing::debug;

use crate::{
    catalog::{
        CatalogSnapshot, ColumnInfo, IndexId, IndexInfo, SnapshotId, TableId,
        inline::{InlineScanKind, materialize_inline_rows},
        projection::ProjectionCache,
    },
    data_file::{self, DataStore},
    error::{Error, Result},
    store::{
        StagedBytes,
        handle::ReadHandle,
        inline as store_inline,
        key::{EntityKey, InlineKey, InlineOperation, Key},
        proto, read, value,
    },
    transaction::{
        commit,
        index_maintenance::{
            IndexMaintenanceMetrics, StagedEntries, StagedIndexEntry, apply_deferred_maintenance,
            apply_poison, stage_index_entry_stream,
        },
    },
};

mod apply;
mod decode;
mod index_upkeep;
pub(crate) mod inline;
mod overlay;
#[cfg(test)]
mod tests;

use apply::{
    ChildRows, apply_op, build_snapshot_value, collect_child_rows, collect_hard_deletes,
    is_inline_op,
};
use decode::Cursor;
use index_upkeep::stage_index_maintenance;
use inline::translate_inline;

use crate::telemetry::milliseconds;

fn next_diagnostic_id() -> u64 {
    static NEXT: AtomicU64 = AtomicU64::new(1);
    NEXT.fetch_add(1, Ordering::Relaxed)
}

#[derive(Default)]
struct CommitPhases {
    head_view: Duration,
    inline: Duration,
    index_maintenance: Duration,
    translate: Duration,
    stage: Duration,
    land: Duration,
    index_metrics: IndexMaintenanceMetrics,
}

fn mints_snapshot(operations: &[RowOperation]) -> bool {
    operations.iter().any(|operation| {
        matches!(
            operation,
            RowOperation::Insert {
                table: TableKind::Snapshot,
                ..
            }
        )
    })
}

/// Which `ducklake_*` table a staged row targets. `Snapshot`,
/// `SnapshotChanges`, and `SchemaVersions` all fold into one moraine
/// `snapshot` record; every other kind maps to one `EntityKey` variant or one
/// of the three unversioned statistics kinds.
// The discriminants are the staged-write wire protocol (the ABI's
// `table_kind` values): declaration order is load-bearing, pinned by
// `ALL` and its order test. Insert new kinds at the end only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum TableKind {
    /// `ducklake_snapshot`.
    Snapshot,
    /// `ducklake_snapshot_changes`.
    SnapshotChanges,
    /// `ducklake_schema`.
    Schema,
    /// `ducklake_table`.
    Table,
    /// `ducklake_view`.
    View,
    /// `ducklake_column`.
    Column,
    /// `ducklake_data_file`.
    DataFile,
    /// `ducklake_delete_file`.
    DeleteFile,
    /// `ducklake_table_stats`.
    TableStats,
    /// `ducklake_table_column_stats`.
    TableColumnStats,
    /// `ducklake_file_column_stats`.
    FileColumnStats,
    /// `ducklake_schema_versions`: one `(begin_snapshot, schema_version,
    /// table_id)` row per created-or-schema-altered table per commit. The
    /// first two must equal the batch's `ducklake_snapshot` values; each
    /// row lands as a `schema_version` record of its own.
    SchemaVersions,
    /// `ducklake_partition_info`.
    PartitionInfo,
    /// `ducklake_partition_column` — folded into its spec's record.
    PartitionColumn,
    /// `ducklake_file_partition_value` — folded into its file's record.
    FilePartitionValue,
    /// `ducklake_sort_info`.
    SortInfo,
    /// `ducklake_sort_expression` — folded into its spec's record.
    SortExpression,
    /// `ducklake_tag` — an entry in its object's container record.
    Tag,
    /// `ducklake_column_tag` — an entry embedded in its column's record.
    ColumnTag,
    /// `ducklake_files_scheduled_for_deletion` — the physical-deletion
    /// schedule, keyed by the scheduled file's id.
    FilesScheduledForDeletion,
    /// `ducklake_macro`.
    Macro,
    /// `ducklake_macro_impl` — folded into its macro's record.
    MacroImpl,
    /// `ducklake_macro_parameters` — folded into its macro's record.
    MacroParameters,
    /// `ducklake_column_mapping`.
    ColumnMapping,
    /// `ducklake_name_mapping` — folded into its mapping's record.
    NameMapping,
    /// `ducklake_metadata`: catalog options, keyed by `(key, scope,
    /// scope_id)`. Outside the snapshot protocol: rows overwrite the
    /// scope's option record in place, last write wins.
    Metadata,
}

impl TableKind {
    /// Every kind, in wire-discriminant order (`ALL[i] as i32 == i`).
    pub const ALL: [Self; 26] = [
        Self::Snapshot,
        Self::SnapshotChanges,
        Self::Schema,
        Self::Table,
        Self::View,
        Self::Column,
        Self::DataFile,
        Self::DeleteFile,
        Self::TableStats,
        Self::TableColumnStats,
        Self::FileColumnStats,
        Self::SchemaVersions,
        Self::PartitionInfo,
        Self::PartitionColumn,
        Self::FilePartitionValue,
        Self::SortInfo,
        Self::SortExpression,
        Self::Tag,
        Self::ColumnTag,
        Self::FilesScheduledForDeletion,
        Self::Macro,
        Self::MacroImpl,
        Self::MacroParameters,
        Self::ColumnMapping,
        Self::NameMapping,
        Self::Metadata,
    ];
}

impl TryFrom<i32> for TableKind {
    type Error = i32;

    /// Decodes a wire discriminant; the unrecognized value comes back as
    /// the error.
    fn try_from(value: i32) -> std::result::Result<Self, i32> {
        usize::try_from(value)
            .ok()
            .and_then(|index| Self::ALL.get(index).copied())
            .ok_or(value)
    }
}

/// One column value in a staged row, typed to the small set of primitive
/// kinds every `ducklake_*` column uses. Decoding into the right proto
/// shape happens here, table-kind by table-kind.
#[derive(Debug, Clone, PartialEq)]
pub enum Cell {
    /// SQL `NULL`.
    Null,
    /// An unsigned integer column (every id, counter, and count).
    U64(u64),
    /// A signed integer column (currently only `snapshot_time`, a
    /// `TIMESTAMPTZ` carried as microseconds since the epoch).
    I64(i64),
    /// A boolean column.
    Bool(bool),
    /// A text column (also used for `UUID`, carried as its text form).
    Str(String),
}

/// One staged row mutation, DuckLake-authored. `cells` are positional, in
/// the exact `ducklake_*` column order pinned in
/// `crates/moraine-duckdb/cpp/metadata_tables.cpp`.
#[derive(Debug, Clone)]
pub enum RowOperation {
    /// A new row: becomes a live `current` record (versioned kinds) or
    /// overwrites the current record in place (unversioned statistics
    /// kinds).
    Insert {
        /// The row's table.
        table: TableKind,
        /// The row's column values, in table order.
        cells: Vec<Cell>,
    },
    /// A row removed with no history mirror: the unversioned statistics
    /// kinds and the deletion schedule, plus the hard prunes maintenance
    /// issues — snapshot records, dead entity versions (`current` or
    /// `history`, named by their `end_snapshot`), and dead tag entries.
    Delete {
        /// The row's table.
        table: TableKind,
        /// The removed row's key columns, in table order (id columns
        /// only — see [`Self::Insert`]'s `cells` for the full row shape).
        cells: Vec<Cell>,
    },
    /// An `UPDATE ... SET end_snapshot = <v>` row: the one lifecycle
    /// convention this path interprets — ends the live version (moves it
    /// to `history`). Defined only for the six versioned kinds.
    UpdateSetEnd {
        /// The row's table.
        table: TableKind,
        /// The ended row's key columns, in table order, followed by the
        /// new `end_snapshot` value.
        cells: Vec<Cell>,
    },
    /// An `UPDATE ... SET begin_snapshot = <v>` row: rebases a data
    /// file's visibility window in place. DuckLake issues it only during
    /// a delete-rewrite, against the replacement file the same
    /// transaction just inserted — any other target is a shape error.
    UpdateSetBegin {
        /// The row's table (only `ducklake_data_file`).
        table: TableKind,
        /// The rebased row's key columns, followed by the new
        /// `begin_snapshot` value.
        cells: Vec<Cell>,
    },
    /// `inline/schema`: the Arrow IPC schema for one `(table_id,
    /// schema_version)`, written once at inline-table creation, stored
    /// verbatim.
    InlineSchema {
        /// Owning table.
        table_id: u64,
        /// Schema version the layout is pinned to.
        schema_version: u64,
        /// The Arrow IPC schema message, verbatim.
        arrow_schema: Vec<u8>,
    },
    /// `inline/insert`: one Arrow record-batch chunk of inlined rows.
    /// `chunk_seq` is not carried here — translation allocates it, so
    /// several `InlineInsert`s staged in one commit against the same
    /// `(table_id, schema_version, begin_snapshot)` land as sequential
    /// chunks in stage order.
    InlineInsert {
        /// Owning table.
        table_id: u64,
        /// Schema version the chunk was written under.
        schema_version: u64,
        /// Commit snapshot of the insert, DuckLake-authored verbatim.
        begin_snapshot: u64,
        /// The chunk's first row id; later rows are dense from here.
        row_id_start: u64,
        /// Row count carried by `arrow_body`.
        row_count: u64,
        /// The user-column cells, encoded as one Arrow IPC record-batch
        /// body (opaque bytes to this layer).
        arrow_body: Vec<u8>,
    },
    /// `inline/inline_delete`: tombstones one inlined-insert row.
    InlineInlineDelete {
        /// Owning table.
        table_id: u64,
        /// The tombstoned row.
        row_id: u64,
        /// The commit snapshot the row ends at.
        end_snapshot: u64,
    },
    /// `inline/file_delete`: an inlined delete against a Parquet-file row.
    InlineFileDelete {
        /// Owning table.
        table_id: u64,
        /// Targeted data file.
        data_file_id: u64,
        /// Deleted row.
        row_id: u64,
        /// The commit snapshot the delete takes effect at.
        begin_snapshot: u64,
    },
    /// Removes one live `inline/file_delete` record, issued once a flush
    /// has materialized that inlined deletion into a real delete file.
    InlineFileDeleteRemove {
        /// Owning table.
        table_id: u64,
        /// The data file the removed deletion targeted.
        data_file_id: u64,
        /// The row the removed deletion killed.
        row_id: u64,
    },
    /// Removes every `inline/insert` chunk begun at or before
    /// `flush_snapshot` for `(table_id, schema_version)`, plus the
    /// `inline/inline_delete` tombstones on those chunks' rows.
    InlineFlushDelete {
        /// Owning table.
        table_id: u64,
        /// Schema version being flushed.
        schema_version: u64,
        /// Chunks begun at or before this snapshot are flushed.
        flush_snapshot: u64,
    },
    /// Removes every `inline/*` record for `table_id`: schema, chunks,
    /// and tombstones.
    InlineDrop {
        /// The dropped table.
        table_id: u64,
    },
    /// Removes only the `inline/schema` record for one `(table_id,
    /// schema_version)`, leaving other schema versions' `inline/*` records
    /// untouched.
    InlineSchemaDrop {
        /// Owning table.
        table_id: u64,
        /// The schema version deregistered.
        schema_version: u64,
    },
}

type CommittedRecords = Arc<Vec<read::EntityRecord>>;
type CommittedRecordCache = tokio::sync::Mutex<
    HashMap<read::EntityRecordKind, Arc<tokio::sync::OnceCell<CommittedRecords>>>,
>;

/// A malformed staged row: wrong cell count or a cell of the wrong kind
/// for its column.
fn corrupt_row(table: TableKind, detail: impl std::fmt::Display) -> Error {
    Error::Corruption(format!("staged row for {table:?}: {detail}"))
}

/// A staged-row transaction: one SlateDB transaction opened by
/// `begin` (crate-internal; [`crate::ffi_support::staged::staged_begin`]
/// is the entry point outside this crate), accumulating [`RowOperation`]s via
/// [`stage`](Self::stage) until [`commit`](Self::commit) translates and
/// lands them all in one atomic batch, or [`rollback`](Self::rollback)
/// discards them.
pub struct StagedTransaction {
    diagnostic_id: u64,
    db_tx: DbTransaction,
    ops: Vec<RowOperation>,
    /// The committed records at this transaction's read point, scanned once
    /// per requested kind and shared by later reads of that kind.
    committed: CommittedRecordCache,
    projections: Arc<std::sync::RwLock<ProjectionCache>>,
    /// The `DATA_PATH` object store and its bucket-relative prefix, present
    /// when the attach supplied `META_DATA_PATH`. Index maintenance
    /// scoped-reads registered data files through it; absent it is skipped.
    data_store: Option<DataStore>,
    data_prefix: String,
    data_reads: Arc<data_file::DataStoreCounters>,
}

impl StagedTransaction {
    /// Opens a fresh transaction at the current head. Nothing is staged
    /// yet; [`stage`](Self::stage) accumulates rows in memory only. A
    /// successful commit folds its batch into `projections` (a catalog's
    /// shared maintained-projection state).
    pub(crate) fn begin(
        db_tx: DbTransaction,
        projections: Arc<std::sync::RwLock<ProjectionCache>>,
        data_store: Option<DataStore>,
        data_prefix: String,
        data_reads: Arc<data_file::DataStoreCounters>,
    ) -> Self {
        Self {
            diagnostic_id: next_diagnostic_id(),
            db_tx,
            ops: Vec::new(),
            committed: tokio::sync::Mutex::new(HashMap::new()),
            projections,
            data_store,
            data_prefix,
            data_reads,
        }
    }

    /// As [`begin`](Self::begin), but with a throwaway, never-served
    /// projection state and no `DATA_PATH` store — for tests that drive a
    /// `StagedTransaction` directly without a `Catalog`.
    #[cfg(test)]
    pub(crate) fn begin_detached(db_tx: DbTransaction) -> Self {
        Self::begin(
            db_tx,
            Arc::new(std::sync::RwLock::new(ProjectionCache::empty())),
            None,
            String::new(),
            Arc::default(),
        )
    }

    /// As [`begin_detached`](Self::begin_detached), but sharing `catalog`'s
    /// projections — for tests that commit here and then read back through
    /// the handle.
    #[cfg(test)]
    pub(crate) fn begin_detached_on(catalog: &crate::Catalog, db_tx: DbTransaction) -> Self {
        Self::begin(
            db_tx,
            Arc::clone(catalog.projections()),
            None,
            String::new(),
            Arc::default(),
        )
    }

    /// As [`begin_detached`](Self::begin_detached), but reading registered
    /// files from `data_store` — for tests that exercise the file paths.
    #[cfg(test)]
    pub(crate) fn begin_detached_with_store(db_tx: DbTransaction, data_store: DataStore) -> Self {
        Self::begin(
            db_tx,
            Arc::new(std::sync::RwLock::new(ProjectionCache::empty())),
            Some(data_store),
            String::new(),
            Arc::default(),
        )
    }

    /// Accumulates one row mutation. Nothing touches the store until
    /// [`commit`](Self::commit).
    pub fn stage(&mut self, op: RowOperation) {
        self.ops.push(op);
    }

    /// The tables this transaction registers new data files against,
    /// ascending and deduplicated. Only inserts count — ending a file's
    /// visibility window registers nothing. A row too malformed to decode
    /// is left out rather than raised; [`commit`](Self::commit) rejects it.
    pub fn tables_with_staged_data_files(&self) -> Vec<TableId> {
        let mut tables: Vec<TableId> = self
            .ops
            .iter()
            .filter_map(|op| match op {
                RowOperation::Insert {
                    table: TableKind::DataFile,
                    cells,
                } => decode::decode_data_file(cells).ok(),
                _ => None,
            })
            .map(|file| TableId::new(file.table_id))
            .collect();
        tables.sort_unstable();
        tables.dedup();

        tables
    }

    /// Discards every staged row without writing anything.
    pub fn rollback(self) {
        self.db_tx.rollback();
    }

    /// Snapshot records as this transaction sees them: the committed
    /// rows at its read point, minus the snapshot deletes staged so far.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged snapshot-delete row
    /// is malformed.
    pub async fn visible_snapshots(&self) -> Result<Vec<proto::SnapshotValue>> {
        let committed = read::scan_snapshots(ReadHandle::Tx(&self.db_tx)).await?;

        let mut deleted = BTreeSet::new();
        for op in &self.ops {
            if let RowOperation::Delete {
                table: TableKind::Snapshot,
                cells,
            } = op
            {
                let mut c = Cursor::new(TableKind::Snapshot, cells);
                deleted.insert(c.u64()?);
                c.finish()?;
            }
        }

        Ok(committed
            .into_iter()
            .filter(|s| !deleted.contains(&s.snapshot_id))
            .collect())
    }

    /// The committed records of one kind at this transaction's read point,
    /// read through `db_tx` so current and history are one consistent cut.
    async fn committed_entities(&self, kind: read::EntityRecordKind) -> Result<CommittedRecords> {
        let cell = {
            let mut committed = self.committed.lock().await;
            Arc::clone(
                committed
                    .entry(kind)
                    .or_insert_with(|| Arc::new(tokio::sync::OnceCell::new())),
            )
        };
        let records = cell
            .get_or_try_init(|| async {
                let started = Instant::now();
                let records = read::scan_entity_kind(ReadHandle::Tx(&self.db_tx), kind).await?;
                let history_records = records
                    .iter()
                    .filter(|record| {
                        record
                            .lifecycle()
                            .is_some_and(|(_, end_snapshot)| end_snapshot.is_some())
                    })
                    .count();
                let current_records = records.len().saturating_sub(history_records);
                debug!(
                    transaction_id = self.diagnostic_id,
                    ?kind,
                    current_records,
                    history_records,
                    records = records.len(),
                    elapsed_ms = milliseconds(started.elapsed()),
                    "scanned committed entities for staged transaction"
                );
                Ok::<_, Error>(Arc::new(records))
            })
            .await?;
        Ok(Arc::clone(records))
    }

    /// The committed records of one kind, as the overlay's starting point.
    async fn committed_rows<T>(
        &self,
        kind: read::EntityRecordKind,
        extract: impl Fn(&read::EntityRecord) -> Option<T>,
    ) -> Result<Vec<T>> {
        Ok(self
            .committed_entities(kind)
            .await?
            .iter()
            .filter_map(extract)
            .collect())
    }

    /// `ducklake_data_file` rows as this transaction sees them: committed
    /// rows at its read point with its own staged rows over them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_data_files(&self) -> Result<Vec<proto::DataFileValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::File, |r| match r {
                read::EntityRecord::File(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_delete_file` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_delete_files(&self) -> Result<Vec<proto::DeleteFileValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::DeleteFile, |r| match r {
                read::EntityRecord::DeleteFile(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_column` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_columns(&self) -> Result<Vec<proto::ColumnValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Column, |r| match r {
                read::EntityRecord::Column(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_table` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_tables(&self) -> Result<Vec<proto::TableValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Table, |r| match r {
                read::EntityRecord::Table(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_file_column_stats` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_file_column_stats(&self) -> Result<Vec<proto::FileColumnStatsValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::FileColumnStats, |r| match r {
                read::EntityRecord::FileColumnStats(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_unversioned(&self.ops, committed)
    }

    /// `ducklake_schema` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_schemas(&self) -> Result<Vec<proto::SchemaValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Schema, |r| match r {
                read::EntityRecord::Schema(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_view` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_views(&self) -> Result<Vec<proto::ViewValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::View, |r| match r {
                read::EntityRecord::View(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_partition_info` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_partition_info(&self) -> Result<Vec<proto::PartitionValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Partition, |r| match r {
                read::EntityRecord::Partition(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_sort_info` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_sort_info(&self) -> Result<Vec<proto::SortValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Sort, |r| match r {
                read::EntityRecord::Sort(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_macro` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_macros(&self) -> Result<Vec<proto::MacroValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Macro, |r| match r {
                read::EntityRecord::Macro(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_versioned(&self.ops, committed)
    }

    /// `ducklake_table_stats` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_table_stats(&self) -> Result<Vec<proto::TableStatsValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::TableStats, |r| match r {
                read::EntityRecord::TableStats(v) => Some(*v),
                _ => None,
            })
            .await?;
        overlay::overlay_unversioned(&self.ops, committed)
    }

    /// `ducklake_table_column_stats` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_table_column_stats(&self) -> Result<Vec<proto::TableColumnStatsValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::TableColumnStats, |r| match r {
                read::EntityRecord::TableColumnStats(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_unversioned(&self.ops, committed)
    }

    /// `ducklake_column_mapping` rows as this transaction sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_mappings(&self) -> Result<Vec<proto::MappingValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Mapping, |r| match r {
                read::EntityRecord::Mapping(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_unversioned(&self.ops, committed)
    }

    /// The `ducklake_tag` container records as this transaction sees them,
    /// with its staged tag rows folded into the containers.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_tag_containers(&self) -> Result<Vec<proto::TagValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Tag, |r| match r {
                read::EntityRecord::Tag(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_tag_containers(&self.ops, committed)
    }

    /// The option-scope records as this transaction sees them, as
    /// `(scope_kind, scope_id, options)` triples — the shape the
    /// `ducklake_metadata` projection flattens.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_option_scopes(&self) -> Result<Vec<(u64, u64, proto::OptionScopeValue)>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::Option, |r| match r {
                read::EntityRecord::Option {
                    scope_kind,
                    scope_id,
                    value,
                } => Some((*scope_kind, *scope_id, value.clone())),
                _ => None,
            })
            .await?;
        overlay::overlay_option_scopes(&self.ops, committed)
    }

    /// The rows this transaction staged for one embedded child kind,
    /// decoded and paired with the parent each names. Deletes need no
    /// counterpart: an embedded row is only removed alongside its parent,
    /// which the parent's overlay already drops.
    fn staged_children<T>(
        &self,
        kind: TableKind,
        decode: impl Fn(&[Cell]) -> Result<T>,
    ) -> Result<Vec<T>> {
        self.ops
            .iter()
            .filter_map(|op| match op {
                RowOperation::Insert { table, cells } if *table == kind => Some(decode(cells)),
                _ => None,
            })
            .collect()
    }

    /// The `ducklake_partition_column` rows this transaction staged, each
    /// with its spec's id. See [`staged_children`](Self::staged_children).
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_partition_columns(&self) -> Result<Vec<(u64, proto::PartitionColumn)>> {
        self.staged_children(TableKind::PartitionColumn, decode::decode_partition_column)
    }

    /// The `ducklake_file_partition_value` rows this transaction staged,
    /// each with its `(table_id, data_file_id)`.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_file_partition_values(
        &self,
    ) -> Result<Vec<((u64, u64), proto::FilePartitionValue)>> {
        self.staged_children(
            TableKind::FilePartitionValue,
            decode::decode_file_partition_value,
        )
    }

    /// The `ducklake_sort_expression` rows this transaction staged, each
    /// with its spec's id.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_sort_expressions(&self) -> Result<Vec<(u64, proto::SortExpression)>> {
        self.staged_children(TableKind::SortExpression, decode::decode_sort_expression)
    }

    /// The `ducklake_column_tag` rows this transaction staged, each with
    /// its `(table_id, column_id)`.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_column_tags(&self) -> Result<Vec<((u64, u64), proto::ColumnTag)>> {
        self.staged_children(TableKind::ColumnTag, decode::decode_column_tag_row)
    }

    /// The `ducklake_macro_impl` rows this transaction staged, each with
    /// its macro's id.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_macro_impls(&self) -> Result<Vec<(u64, proto::MacroImplementation)>> {
        self.staged_children(TableKind::MacroImpl, decode::decode_macro_impl)
    }

    /// The `ducklake_macro_parameters` rows this transaction staged, each
    /// with its `(macro_id, impl_id)`.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_macro_parameters(&self) -> Result<Vec<((u64, u64), proto::MacroParameter)>> {
        self.staged_children(TableKind::MacroParameters, decode::decode_macro_parameter)
    }

    /// The `ducklake_name_mapping` rows this transaction staged, each with
    /// its mapping's id.
    ///
    /// # Errors
    ///
    /// Returns an error if a staged row is malformed.
    pub fn staged_name_mappings(&self) -> Result<Vec<(u64, proto::NameMapping)>> {
        self.staged_children(TableKind::NameMapping, decode::decode_name_mapping)
    }

    /// The `schema_version` records as this transaction sees them, as
    /// `(table_id, begin_snapshot, schema_version)` triples: the committed
    /// records with the transaction's own inserts and deletes over them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_schema_version_records(&self) -> Result<Vec<(u64, u64, u64)>> {
        let mut records = read::scan_schema_versions(ReadHandle::Tx(&self.db_tx)).await?;

        // A staged delete removes committed records and any staged insert
        // before it; a staged insert after the delete survives.
        let mut deleted = HashSet::new();
        let mut inserted = Vec::new();
        for op in &self.ops {
            match op {
                RowOperation::Insert { table, cells } if *table == TableKind::SchemaVersions => {
                    inserted.push(decode::decode_schema_version_row(cells)?);
                }
                RowOperation::Delete { table, cells } if *table == TableKind::SchemaVersions => {
                    let (table_id, begin_snapshot, _) = decode::decode_schema_version_row(cells)?;
                    deleted.insert((table_id, begin_snapshot));
                    inserted.retain(|(t, b, _)| !(*t == table_id && *b == begin_snapshot));
                }
                _ => {}
            }
        }
        records.retain(|(t, b, _)| !deleted.contains(&(*t, *b)));
        records.extend(inserted);

        Ok(records)
    }

    /// `ducklake_files_scheduled_for_deletion` rows as this transaction
    /// sees them.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails or a staged row is malformed.
    pub async fn visible_scheduled_deletions(&self) -> Result<Vec<proto::GcFileValue>> {
        let committed = self
            .committed_rows(read::EntityRecordKind::GcFile, |r| match r {
                read::EntityRecord::GcFile(v) => Some(v.clone()),
                _ => None,
            })
            .await?;
        overlay::overlay_unversioned(&self.ops, committed)
    }

    /// Translates every staged row and lands them in one atomic batch.
    ///
    /// A commit with a `ducklake_snapshot` insert mints that snapshot and
    /// advances head. A commit without one is a maintenance commit and
    /// lands head-preserving: no new snapshot record, `sys/head` untouched.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Constraint`] or [`Error::Corruption`] if the
    /// staged rows are malformed, mutate entities without the required
    /// `ducklake_snapshot` / `ducklake_snapshot_changes` pair, or expire
    /// the head snapshot. Returns [`Error::CommitConflict`] — **never
    /// retried internally** — if a concurrent commit advanced the head
    /// first; the store is left unchanged by the loser.
    pub async fn commit(self) -> Result<SnapshotId> {
        self.commit_reporting()
            .await
            .map(|report| report.snapshot_id)
    }

    /// As [`commit`](Self::commit), also naming the deferred-maintenance
    /// indexes this commit left awaiting repair.
    ///
    /// # Errors
    ///
    /// As [`commit`](Self::commit).
    #[allow(clippy::too_many_lines)]
    pub async fn commit_reporting(self) -> Result<CommitReport> {
        let started = Instant::now();
        let Self {
            diagnostic_id,
            db_tx,
            ops,
            committed: _,
            projections,
            data_store,
            data_prefix,
            data_reads,
        } = self;
        let staged_rows = ops.len();
        let mut uses_inline_chunk_directory = ops
            .iter()
            .any(|operation| matches!(operation, RowOperation::InlineInsert { .. }));
        let mut phases = CommitPhases::default();

        // Both read `db_tx`'s current state before any write in this commit
        // is staged: `InlineFlushDelete`/`InlineDrop` name a table, not keys,
        // and resolve against the same cut as `base`.
        let head_view = async {
            let phase_started = Instant::now();
            let base = commit::head_view_for(&db_tx, &projections).await?;
            Ok::<_, Error>((base, phase_started.elapsed()))
        };
        let inline = async {
            let phase_started = Instant::now();
            let writes = translate_inline(&db_tx, &ops).await?;
            Ok::<_, Error>((writes, phase_started.elapsed()))
        };
        let (base, inline_writes) = match futures::try_join!(head_view, inline) {
            Ok(((base, head_view_elapsed), (inline_writes, inline_elapsed))) => {
                phases.head_view = head_view_elapsed;
                phases.inline = inline_elapsed;
                (base, inline_writes)
            }
            Err(err) => {
                db_tx.rollback();
                return Err(err);
            }
        };
        let base_ref: &CatalogSnapshot = &base;

        let mints_snapshot = mints_snapshot(&ops);
        // Staged before translation so a poisoned index definition rides
        // the writes it produces.
        let store = data_store.as_ref();
        let read_metrics = Arc::new(data_file::ScopedReadMetrics::reporting_to(data_reads));
        let phase_started = Instant::now();
        let entries = match stage_index_maintenance(
            &db_tx,
            base_ref,
            &ops,
            store,
            &data_prefix,
            read_metrics,
        )
        .await
        {
            Ok(entries) => entries,
            Err(err) => {
                db_tx.rollback();
                return Err(err);
            }
        };
        phases.index_maintenance = phase_started.elapsed();
        let StagedEntries {
            poisoned,
            deferred,
            bytes: entry_bytes,
            uses_inline_chunk_directory: repaired_inline_chunk_directory,
            metrics: index_metrics,
        } = entries;
        phases.index_metrics = index_metrics;
        uses_inline_chunk_directory |= repaired_inline_chunk_directory;

        // A head-preserving commit never marks a definition maintaining.
        let deferred_indexes = if mints_snapshot {
            deferred.iter().copied().map(IndexId::new).collect()
        } else {
            Vec::new()
        };

        let phase_started = Instant::now();
        match translate_batch(base_ref, &ops, &poisoned, &deferred, mints_snapshot) {
            Ok((result_id, mut writes, translated_head_view)) => {
                phases.translate = phase_started.elapsed();
                let phase_started = Instant::now();
                let staged_bytes = match stage_batch(
                    &db_tx,
                    &mut writes,
                    inline_writes,
                    result_id,
                    base_ref.batch_seq,
                    entry_bytes,
                    uses_inline_chunk_directory,
                )
                .await
                {
                    Ok(staged) => staged,
                    Err(err) => {
                        db_tx.rollback();
                        return Err(err);
                    }
                };
                phases.stage = phase_started.elapsed();
                // Landed off-task: the write cannot be retracted once
                // issued, so a host interrupt races the wait, not the write.
                let head_before = base_ref.snapshot.snapshot_id;
                let head_view_update = translated_head_view.map_or_else(
                    || commit::HeadViewUpdate::Rebuild(Arc::clone(&base)),
                    |view| commit::HeadViewUpdate::Prepared(Arc::new(view)),
                );
                let phase_started = Instant::now();
                let landed = commit::commit_batch_off_task(
                    db_tx,
                    head_before,
                    result_id,
                    writes,
                    staged_bytes,
                    head_view_update,
                    projections,
                )
                .await?;
                phases.land = phase_started.elapsed();
                match landed {
                    commit::Landed::Committed(commit_timings) => {
                        staged_landed(
                            diagnostic_id,
                            result_id,
                            staged_rows,
                            staged_bytes,
                            &phases,
                            commit_timings,
                            started,
                        );
                        Ok(CommitReport {
                            snapshot_id: SnapshotId::new(result_id),
                            deferred_indexes,
                        })
                    }
                    commit::Landed::LostRace => Err(staged_lost_race(result_id, staged_rows)),
                }
            }
            Err(err) => {
                db_tx.rollback();
                Err(err)
            }
        }
    }
}

/// What a landed commit produced.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommitReport {
    /// The snapshot the commit's rows are visible at.
    pub snapshot_id: SnapshotId,
    /// Deferred-maintenance indexes this commit left `Maintaining`.
    pub deferred_indexes: Vec<IndexId>,
}

/// The writes a batch carries and the snapshot id it results in. A
/// snapshot-minting commit translates its operations and appends its own
/// snapshot record; a maintenance one reuses the standing id.
fn translate_batch(
    base: &CatalogSnapshot,
    ops: &[RowOperation],
    poisoned: &[u64],
    deferred: &[u64],
    mints_snapshot: bool,
) -> Result<(u64, Vec<commit::StagedWrite>, Option<CatalogSnapshot>)> {
    if !mints_snapshot {
        return translate_maintenance(base, ops)
            .map(|writes| (base.snapshot.snapshot_id, writes, None));
    }

    let (new_id, mut writes, snap, translated_head_view) =
        translate(base, ops, poisoned, deferred)?;
    // Derived before the snapshot record joins the batch: the changelog
    // names `current` keys, and that record is not.
    let changelog = commit::changelog_writes(new_id, &writes);
    writes.push((
        Key::Snapshot {
            snapshot_id: new_id,
        }
        .encode(),
        Some(value::encode_value(&snap)),
    ));
    writes.extend(changelog);
    let translated_head_view = translated_head_view.map(|mut view| {
        view.batch_seq = base.batch_seq.saturating_add(1);
        view
    });
    Ok((new_id, writes, translated_head_view))
}

/// Stamps the head, folds in the inline writes, and stages the whole batch
/// onto `db_tx`, returning what the batch weighs (`entry_bytes` included,
/// since index entries stage directly and never join `writes`). A
/// maintenance batch stamps the head too, reusing the standing snapshot id.
async fn stage_batch(
    db_tx: &DbTransaction,
    writes: &mut Vec<commit::StagedWrite>,
    inline_writes: Vec<commit::StagedWrite>,
    result_id: u64,
    standing_batch_seq: u64,
    entry_bytes: u64,
    uses_inline_chunk_directory: bool,
) -> Result<StagedBytes> {
    writes.push(commit::head_stamp(result_id, standing_batch_seq));
    writes.extend(inline_writes);
    if uses_inline_chunk_directory
        && let Some(stamp) =
            commit::format_stamp_to(db_tx, commit::FORMAT_WITH_INLINE_CHUNK_DIRECTORY).await?
    {
        writes.push(stamp);
    }
    let mut staged = commit::stage_writes(db_tx, writes)?;
    staged.0 = staged.0.saturating_add(entry_bytes);
    Ok(staged)
}

/// One landed staged commit's summary event.
fn staged_landed(
    transaction_id: u64,
    result_id: u64,
    staged_rows: usize,
    staged_bytes: StagedBytes,
    phases: &CommitPhases,
    commit_timings: commit::CommitTimings,
    started: Instant,
) {
    debug!(
        transaction_id,
        snapshot = result_id,
        staged_rows,
        staged_bytes = staged_bytes.0,
        head_view_ms = milliseconds(phases.head_view),
        inline_ms = milliseconds(phases.inline),
        index_maintenance_ms = milliseconds(phases.index_maintenance),
        index_delete_derivation_ms = milliseconds(phases.index_metrics.deletion_derivation),
        index_add_derivation_ms = milliseconds(phases.index_metrics.addition_derivation),
        index_probe_window_ms = milliseconds(phases.index_metrics.probe_window),
        index_probe_service_ms = milliseconds(phases.index_metrics.probe_service),
        index_stage_ms = milliseconds(phases.index_metrics.staging),
        index_encode_ms = milliseconds(phases.index_metrics.scoped_read.encode_duration),
        index_parquet_read_ms = milliseconds(phases.index_metrics.scoped_read.range_duration),
        index_additions = phases.index_metrics.additions,
        index_deletions = phases.index_metrics.deletions,
        index_unique_probes = phases.index_metrics.unique_probes,
        index_probe_hits = phases.index_metrics.probe_hits,
        index_probe_misses = phases.index_metrics.probe_misses,
        index_probe_peak_in_flight = phases.index_metrics.probe_peak_in_flight,
        index_probes_completed_during_deletions =
            phases.index_metrics.probes_completed_during_deletions,
        index_metadata_hits = phases.index_metrics.scoped_read.metadata_hits,
        index_metadata_misses = phases.index_metrics.scoped_read.metadata_misses,
        index_range_fetches = phases.index_metrics.scoped_read.range_fetches,
        index_ranges = phases.index_metrics.scoped_read.ranges,
        index_range_bytes = phases.index_metrics.scoped_read.range_bytes,
        index_files = phases.index_metrics.scoped_read.parquet_files,
        index_inline_chunks = phases.index_metrics.scoped_read.inline_chunks,
        index_arrow_batches = phases.index_metrics.scoped_read.arrow_batches,
        translate_ms = milliseconds(phases.translate),
        stage_ms = milliseconds(phases.stage),
        land_ms = milliseconds(phases.land),
        durable_ms = milliseconds(commit_timings.durable),
        projection_ms = milliseconds(commit_timings.projection),
        elapsed_ms = milliseconds(started.elapsed()),
        "staged commit landed"
    );
}

/// The lost-race error for a staged commit, logged as it is built. Its
/// text must contain `conflict`: DuckLake's retry loop scans for it.
fn staged_lost_race(result_id: u64, staged_rows: usize) -> Error {
    debug!(
        attempted_snapshot = result_id,
        staged_rows, "staged commit lost a write-write race; DuckLake re-drives"
    );
    Error::CommitConflict(format!(
        "a concurrent commit changed state this one read or wrote \
         (attempted snapshot {result_id}); staged-row commits are never \
         retried internally"
    ))
}

/// Applies every op onto a clone of `base`, then diffs the two exactly as
/// a verb-path commit diffs its closure's output.
fn translate(
    base: &CatalogSnapshot,
    ops: &[RowOperation],
    poisoned: &[u64],
    deferred: &[u64],
) -> Result<(
    u64,
    Vec<commit::StagedWrite>,
    proto::SnapshotValue,
    Option<CatalogSnapshot>,
)> {
    let snapshot = build_snapshot_value(ops)?;
    let new_id = snapshot.snapshot_id;

    // DuckLake mints the id from the head it read; an id at or below the
    // head means another commit landed in between, a lost race.
    if new_id <= base.snapshot.snapshot_id {
        return Err(staged_lost_race(new_id, ops.len()));
    }

    // Ends and deletes apply before inserts regardless of emit order (a
    // rename ends and re-inserts under one id, and the insert must win the
    // shared `current` key); begin-rebases apply last, targeting rows this
    // commit inserted. Inline ops are translated by `translate_inline`.
    let mut state = base.clone();
    let mut children = collect_child_rows(ops)?;
    let mut direct = Vec::new();
    let hard_deleted = collect_hard_deletes(ops)?;

    let phases: [fn(&RowOperation) -> bool; 3] = [
        |op| {
            !is_inline_op(op)
                && !matches!(
                    op,
                    RowOperation::Insert { .. } | RowOperation::UpdateSetBegin { .. }
                )
        },
        |op| matches!(op, RowOperation::Insert { .. }),
        |op| matches!(op, RowOperation::UpdateSetBegin { .. }),
    ];
    for phase in phases {
        for op in ops.iter().filter(|op| phase(op)) {
            apply_op(
                base,
                &mut state,
                op,
                new_id,
                &mut children,
                &mut direct,
                &hard_deleted,
            )?;
        }
    }

    refuse_orphaned_children(&children)?;

    // DuckLake authors column ids itself; float each table's field-id
    // counter above every live id so a later verb-path `add_column` cannot
    // re-allocate one.
    for (table_id, columns) in &state.columns {
        let Some(max_id) = columns.keys().max() else {
            continue;
        };
        if let Some(table) = state.tables.get_mut(table_id)
            && table.next_column_id <= *max_id
        {
            table.next_column_id = max_id + 1;
        }
    }

    apply_poison(&mut state, poisoned);
    apply_deferred_maintenance(base, &mut state, deferred, new_id);
    state.snapshot = snapshot.clone();

    let mut writes = commit::diff_writes(base, &state, new_id);
    let translated_head_view = match commit::finish_translated_head_view(&mut state, &direct) {
        Ok(()) => Some(state),
        Err(err) => {
            debug!(error = %err, "translated head view could not be completed; rebuilding after commit");
            None
        }
    };
    writes.extend(direct);
    // The `ducklake_schema_versions` rows this commit staged, as records
    // of their own.
    for table_id in &snapshot.schema_changed_table_ids {
        writes.push(commit::schema_version_write(
            *table_id,
            new_id,
            snapshot.schema_version,
        ));
    }

    Ok((new_id, writes, snapshot, translated_head_view))
}

/// Refuses child rows left over after every parent was applied: an
/// embedded child whose parent is not in the same commit has nowhere to
/// live.
fn refuse_orphaned_children(children: &ChildRows) -> Result<()> {
    let orphans = [
        (
            children.partition_columns.is_empty(),
            TableKind::PartitionColumn,
            "partition_column rows without a matching partition_info insert in this commit",
        ),
        (
            children.sort_expressions.is_empty(),
            TableKind::SortExpression,
            "sort_expression rows without a matching sort_info insert in this commit",
        ),
        (
            children.file_partition_values.is_empty(),
            TableKind::FilePartitionValue,
            "file_partition_value rows without a matching data_file insert in this commit",
        ),
        (
            children.macro_implementations.is_empty(),
            TableKind::MacroImpl,
            "macro_impl rows without a matching macro insert in this commit",
        ),
        (
            children.macro_parameters.is_empty(),
            TableKind::MacroParameters,
            "macro_parameters rows without a matching macro_impl in this commit",
        ),
        (
            children.name_mappings.is_empty(),
            TableKind::NameMapping,
            "name_mapping rows without a matching column_mapping insert in this commit",
        ),
    ];
    for (applied, table, detail) in orphans {
        if !applied {
            return Err(corrupt_row(table, detail));
        }
    }
    Ok(())
}

/// Translates a head-preserving maintenance commit (no `ducklake_snapshot`
/// insert): the head snapshot id is retained and no snapshot record is
/// written. Only raw deletes, schedule inserts, row-ID file-stat inserts,
/// option writes, and inline ops are legal; anything versioned is a
/// constraint violation.
fn translate_maintenance(
    base: &CatalogSnapshot,
    ops: &[RowOperation],
) -> Result<Vec<commit::StagedWrite>> {
    let head = base.snapshot.snapshot_id;

    let mut state = base.clone();
    let mut children = ChildRows::default();
    let mut direct = Vec::new();
    let hard_deleted = collect_hard_deletes(ops)?;
    for op in ops {
        let row_id_statistics_insert = match op {
            RowOperation::Insert {
                table: TableKind::FileColumnStats,
                cells,
            } => file_column_stats_column_id(cells)? == data_file::ROW_ID_FIELD_ID,
            _ => false,
        };
        let allowed = matches!(
            op,
            RowOperation::Delete { .. }
                | RowOperation::Insert {
                    table: TableKind::FilesScheduledForDeletion | TableKind::Metadata,
                    ..
                }
        ) || row_id_statistics_insert
            || is_inline_op(op);
        if !allowed {
            return Err(Error::Constraint(
                "a staged commit without a ducklake_snapshot insert may only maintain \
                 unversioned state (maintenance deletes, deletion-schedule inserts, \
                 reserved row-ID file-stat inserts, and ducklake_metadata writes)"
                    .to_string(),
            ));
        }
        apply_op(
            base,
            &mut state,
            op,
            head,
            &mut children,
            &mut direct,
            &hard_deleted,
        )?;
    }

    let mut writes = commit::diff_writes(base, &state, head);
    writes.extend(direct);
    Ok(writes)
}

/// The `column_id` cell of a `ducklake_file_column_stats` row; `apply_op`
/// decodes the whole row.
fn file_column_stats_column_id(cells: &[Cell]) -> Result<u64> {
    let mut cursor = Cursor::new(TableKind::FileColumnStats, cells);
    let _data_file_id = cursor.u64()?;
    let _table_id = cursor.u64()?;
    cursor.u64()
}