moraine 0.4.1

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
//! Opening, bootstrap, and snapshot materialization. The commit cycle
//! itself builds on these.

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use slatedb::{Db, DbReader, DbTransaction, IsolationLevel, config::WriteOptions};
use tracing::{debug, info, warn};
use uuid::Uuid;

use crate::{
    catalog::{
        CatalogSnapshot, SnapshotId,
        projection::{
            ProjectionCache, cache_epoch, cached_head_view, fold_committed_batch,
            install_head_view, install_head_view_at, invalidate_head_view,
        },
    },
    error::{Error, Result},
    store::{
        handle::ReadHandle,
        key::{EntityKey, Key, SysKey},
        open::StoreBuilder,
        proto, read, value,
    },
    transaction::{
        index_maintenance, inline,
        operations::{ChangeSet, Operation},
        verbs::{Transaction, TransactionParts},
    },
};

/// Structural layout version a fresh store bootstraps at — format 1 plus
/// nothing. Index-free stores stay here, byte-identical to pre-index
/// stores and readable by older binaries.
pub(crate) const FORMAT_VERSION: u64 = 1;
/// Format stamped lazily the first time an equality index exists: format 1
/// plus the `index` subspace and `index` kind. Older binaries, which
/// maintain no entries, refuse it.
pub(crate) const FORMAT_WITH_INDEX: u64 = 2;
/// Format stamped the first time a staged (multi-commit) index build
/// exists. A format-2 binary would read a `building` definition as a ready
/// index and serve from an under-covered entry set, so it must refuse this.
pub(crate) const FORMAT_WITH_STAGED_INDEX: u64 = 3;
/// The highest format this binary understands. It opens any store in
/// `MIN_FORMAT_VERSION..=MAX_FORMAT_VERSION` and refuses a newer one.
pub(crate) const MAX_FORMAT_VERSION: u64 = FORMAT_WITH_STAGED_INDEX;
/// The lowest structural format this binary reads directly. A store below
/// this floor must be migrated up before an ordinary attach can use it.
/// Every format so far is additive — each adds a subspace without moving an
/// existing key — so the floor sits at the base format and no store in the
/// world is below it. It rises only when a format rewrites the keyspace,
/// which is what makes an old store unreadable rather than merely older.
pub(crate) const MIN_FORMAT_VERSION: u64 = FORMAT_VERSION;
/// Bounded internal retries before a benign race is reported as a
/// conflict.
pub(crate) const MAX_COMMIT_ATTEMPTS: usize = 10;

/// Delay before the second commit attempt, in microseconds; each further
/// retry doubles it, up to [`RETRY_BACKOFF_MAX_MICROS`]. Without a pause the
/// budget is ten immediate re-runs, which under real contention is a spin
/// that burns the budget faster than the contention can clear.
const RETRY_BACKOFF_BASE_MICROS: u64 = 2_000;
/// Ceiling on one retry's delay. The whole budget then spans a few hundred
/// milliseconds — enough for a competing commit to land, short enough that a
/// caller waiting on a conflict is not left hanging.
const RETRY_BACKOFF_MAX_MICROS: u64 = 50_000;

/// How long to wait before re-running `attempt` (0-based; the first attempt
/// never waits). Exponential to the cap, plus jitter of up to the base delay
/// so two writers that just collided do not back off in lockstep and collide
/// again.
fn retry_backoff(attempt: usize) -> Duration {
    if attempt == 0 {
        return Duration::ZERO;
    }
    let doublings = u32::try_from(attempt - 1).unwrap_or(u32::MAX).min(31);
    let step = RETRY_BACKOFF_BASE_MICROS
        .saturating_mul(1_u64 << doublings)
        .min(RETRY_BACKOFF_MAX_MICROS);
    let jitter = now_micros().unsigned_abs() % RETRY_BACKOFF_BASE_MICROS;
    Duration::from_micros(step.saturating_add(jitter))
}

/// Current time in microseconds since the Unix epoch. Clamped, never
/// panicking: a clock before the epoch stamps 0.
pub(crate) fn now_micros() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
}

pub(crate) fn durable() -> WriteOptions {
    WriteOptions {
        await_durable: true,
        ..Default::default()
    }
}

/// How long a durable commit may wait before the wait itself is reported,
/// and how often it is reported thereafter.
const STALL_INTERVAL: Duration = Duration::from_secs(10);

/// Commits `tx` and waits for the batch to reach object storage, naming
/// `operation` in the log if the wait runs long.
///
/// The wait is unbounded on purpose. A failed object-store write is retried
/// beneath us indefinitely, so a permanent refusal — expired credentials, a
/// revoked bucket policy — stalls here rather than failing. Giving up on a
/// deadline would not undo the staged batch: the flush continues, so the
/// deadline would report failure for a commit that still lands, and a
/// caller re-driving it would apply it twice. A stall that says so in the
/// log is the half of that trade worth having.
pub(crate) async fn commit_durable(
    tx: DbTransaction,
    operation: &'static str,
) -> std::result::Result<Option<slatedb::WriteHandle>, slatedb::Error> {
    let options = durable();
    let mut commit = Box::pin(tx.commit_with_options(&options));
    let mut waited = Duration::ZERO;
    loop {
        if let Ok(outcome) = tokio::time::timeout(STALL_INTERVAL, &mut commit).await {
            return outcome;
        }
        waited = waited.saturating_add(STALL_INTERVAL);
        warn!(
            operation,
            waited_seconds = waited.as_secs(),
            "still waiting for object storage to accept a durable write; writes are retried \
             indefinitely, so check credentials and bucket policy"
        );
    }
}

/// A commit that returns without waiting for the write to reach object
/// storage. The write is still atomic and visible to this handle at once;
/// only the durability wait — a flush-cadence tick — is skipped. Use it
/// where a lost write is self-correcting, never where a caller treats the
/// return as a durable fact.
pub(crate) fn non_durable() -> WriteOptions {
    WriteOptions {
        await_durable: false,
        ..Default::default()
    }
}

/// Refuses a store this binary must not touch: mid-migration, or a
/// format newer/older than it understands. `None` format means the store
/// is empty and needs bootstrap.
async fn validate_format(tx: ReadHandle<'_>) -> Result<Option<proto::FormatValue>> {
    if read::read_migration(tx).await?.is_some() {
        return Err(Error::Migration(
            "store is mid-migration; refusing to open".to_string(),
        ));
    }
    match read::read_format(tx).await? {
        Some(format) if format.format_version > MAX_FORMAT_VERSION => {
            Err(Error::Migration(format!(
                "store format {} is newer than this binary understands (max {MAX_FORMAT_VERSION}); \
             upgrade the binary",
                format.format_version
            )))
        }
        Some(format) if format.format_version < MIN_FORMAT_VERSION => {
            Err(Error::Migration(format!(
                "store format {} predates this binary's minimum ({MIN_FORMAT_VERSION}); \
             it must be migrated up before this binary can open it",
                format.format_version
            )))
        }
        Some(format) => Ok(Some(format)),
        None => Ok(None),
    }
}

/// Stages the initial state of an empty store into `tx`: format stamp,
/// snapshot 0 (carrying the default `main` schema, counters advanced past
/// its id), the `main` schema record itself, the global `encrypted`
/// option, and head pointer — the same starting catalog shape a fresh
/// DuckLake metadata store carries.
///
/// `encrypted` is recorded explicitly (as `"true"`/`"false"`) and only
/// here: whether data files are encrypted is fixed when the catalog is
/// created, exactly as DuckLake fixes it when initializing a metadata
/// store.
fn stage_bootstrap(tx: &DbTransaction, encrypted: bool, data_path: Option<&str>) -> Result<()> {
    let stage = |key: Key, bytes: Vec<u8>| tx.put(key.encode(), bytes).map_err(Error::from);
    stage(
        Key::Sys(SysKey::Format),
        value::encode_value(&proto::FormatValue {
            format_version: FORMAT_VERSION,
            writer_version: env!("CARGO_PKG_VERSION").to_string(),
        }),
    )?;
    // Bootstrap's snapshot records minting `main`, byte-identical to the
    // `created_schema:"main"` DuckLake's own initialization writes.
    let mut bootstrap_changes = ChangeSet::default();
    bootstrap_changes.created_schemas.insert("main".to_string());
    stage(
        Key::Snapshot { snapshot_id: 0 },
        value::encode_value(&proto::SnapshotValue {
            snapshot_id: 0,
            snapshot_time_micros: now_micros(),
            schema_version: 0,
            next_catalog_id: 1,
            next_file_id: 0,
            changes_made: bootstrap_changes.to_changes_made(),
            author: None,
            commit_message: None,
            commit_extra_info: None,
            schema_changed_table_ids: Vec::new(),
            deleted_data_file_ids: Vec::new(),
        }),
    )?;
    stage(
        Key::current(EntityKey::Schema { schema_id: 0 }),
        value::encode_value(&proto::SchemaValue {
            schema_id: 0,
            schema_uuid: Uuid::new_v4().to_string(),
            begin_snapshot: 0,
            end_snapshot: None,
            schema_name: "main".to_string(),
            path: "main/".to_string(),
            path_is_relative: true,
        }),
    )?;
    // The global option record carries `encrypted` and, when the lake was
    // given a data root, `data_path` — so a later open reads the root back
    // without being told it again.
    let mut options = std::collections::HashMap::from([(
        "encrypted".to_string(),
        if encrypted { "true" } else { "false" }.to_string(),
    )]);
    if let Some(path) = data_path {
        options.insert("data_path".to_string(), path.to_string());
    }
    stage(
        Key::current(EntityKey::Option {
            scope_kind: 0,
            scope_id: 0,
        }),
        value::encode_value(&proto::OptionScopeValue { options }),
    )?;
    stage(
        Key::Sys(SysKey::Head),
        value::encode_value(&proto::HeadValue { snapshot_id: 0 }),
    )
}

/// Opens the store, bootstrapping an empty one in one atomic batch under
/// conflict detection — a lost bootstrap race re-validates instead of
/// double-initializing. Every exit that does not commit rolls back.
///
/// The open is deliberately **not** retried. Every open takes the writer
/// epoch by a manifest compare-and-swap, so a concurrent open loses that
/// CAS — and re-attempting it takes the epoch in turn, fencing whichever
/// initializer had just won. Two initializers that both re-attempt can
/// therefore both lose, which is worse than the loss the retry was meant to
/// smooth over: the race currently always leaves a winner.
pub(crate) async fn open_initialized(
    store: StoreBuilder<'_>,
    encrypted: bool,
    data_path: Option<&str>,
) -> Result<Db> {
    let db = store.open_writer().await?;
    let tx = db
        .begin(IsolationLevel::Snapshot)
        .await
        .map_err(Error::from)?;

    match validate_format(ReadHandle::Tx(&tx)).await {
        Ok(Some(_)) => {
            tx.rollback();
            return Ok(db);
        }
        Ok(None) => {}
        Err(err) => {
            tx.rollback();
            return Err(err);
        }
    }

    if let Err(err) = stage_bootstrap(&tx, encrypted, data_path) {
        tx.rollback();
        return Err(err);
    }

    match commit_durable(tx, "bootstrap").await {
        Ok(_) => {
            // Once per store, ever: the commit that created the catalog.
            info!(encrypted, data_path, "bootstrapped a fresh catalog store");
            Ok(db)
        }
        Err(err) if err.kind() == slatedb::ErrorKind::Transaction => {
            // Lost the bootstrap race: someone initialized concurrently.
            let tx = db
                .begin(IsolationLevel::Snapshot)
                .await
                .map_err(Error::from)?;
            let validated = validate_format(ReadHandle::Tx(&tx)).await;
            tx.rollback();
            if validated?.is_some() {
                Ok(db)
            } else {
                Err(Error::Corruption(
                    "bootstrap race left the store uninitialized".to_string(),
                ))
            }
        }
        Err(err) => Err(err.into()),
    }
}

/// Opens the store read-only as a [`DbReader`], validating the format it
/// finds. Never opens a `Db`, so it never fences a live writer, and never
/// bootstraps — a read-only attach against an uninitialized store is refused
/// (there is nothing committed to read).
pub(crate) async fn open_reader_initialized(store: StoreBuilder<'_>) -> Result<DbReader> {
    let reader = store.open_reader().await?;
    match validate_format(ReadHandle::Reader(&reader)).await? {
        Some(_) => Ok(reader),
        None => Err(Error::Corruption(
            "store is not an initialized moraine catalog; a read-only attach \
             needs a writer to have created it first"
                .to_string(),
        )),
    }
}

/// Refuses a store whose keyspace is mid-move. A structural migration
/// rewrites keys in place, so any scan of it may be missing records that
/// have not arrived yet; failing is the only way to avoid returning a
/// silently partial catalog.
pub(crate) async fn refuse_mid_migration(tx: ReadHandle<'_>) -> Result<()> {
    match read::read_migration(tx).await? {
        Some(marker) => Err(Error::Migration(format!(
            "store is migrating from format {} to {}; reads are unavailable until it completes",
            marker.from_format, marker.to_format
        ))),
        None => Ok(()),
    }
}

/// The latest committed snapshot id. An initialized store always has one,
/// so its absence is corruption rather than an empty catalog.
pub(crate) async fn read_head_id(tx: ReadHandle<'_>) -> Result<u64> {
    Ok(read::read_head(tx)
        .await?
        .ok_or_else(|| Error::Corruption("store has no head pointer".to_string()))?
        .snapshot_id)
}

/// Materializes a catalog view through an open transaction, so the view
/// and any staged writes share one read point. `at: None` reads the head
/// (`current` only); `at: Some(s)` also scans `history` to reconstruct the
/// entities live at `s`.
pub(crate) async fn materialize(tx: ReadHandle<'_>, at: Option<u64>) -> Result<CatalogSnapshot> {
    refuse_mid_migration(tx).await?;
    let head = read_head_id(tx).await?;
    let target = match at {
        Some(requested) if requested > head => {
            return Err(Error::NotFound(format!(
                "snapshot {requested} (head is {head})"
            )));
        }
        Some(requested) => requested,
        None => head,
    };
    // A missing record at or below head is an expired snapshot, not a
    // missing one: ids are sequential to head, so `target` was minted, and
    // expiry deletes snapshot records without renumbering. The reader
    // re-resolves from head rather than dereference reclaimed files.
    let snapshot = read::read_snapshot(tx, target).await?.ok_or_else(|| {
        Error::SnapshotExpired(format!(
            "snapshot {target} is below the retention horizon (head is {head}); \
             re-resolve from head"
        ))
    })?;
    let current = read::scan_current_entities(tx).await?;
    let history = match at {
        Some(_) => read::scan_history_entities(tx).await?,
        None => Vec::new(),
    };

    Ok(CatalogSnapshot::build(
        snapshot,
        current,
        history,
        at.map(|_| target),
    ))
}

/// One staged write: `Some` puts, `None` deletes.
pub(crate) type StagedWrite = (Vec<u8>, Option<Vec<u8>>);

mod diff;
mod fold;
mod group;
use diff::diff_options;
pub(crate) use diff::diff_writes;
pub(crate) use group::Coalescer;
use group::Outcome;

/// What a batch's durable write did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Landed {
    /// The batch is durable.
    Committed,
    /// A concurrent commit advanced the head first; nothing was written.
    LostRace,
}

/// The result of one attempt at a group.
enum CommitOutcome {
    /// The attempt committed; carries one snapshot id per member, in
    /// member order.
    Committed(Vec<SnapshotId>),
    /// Lost the head race: what each member tried to change, and the head
    /// the batch's premise was read at — classification reads the commits
    /// above it.
    LostRace {
        ours: Vec<ChangeSet>,
        head_before: u64,
    },
    /// Nothing landed, for a reason the attempt cannot classify. Retrying
    /// is the only way to learn more: an attempt that meets the same
    /// failure without a batch to share surfaces it typed.
    Nothing,
}

/// Runs one attempt: stage every member onto whichever batch the store is
/// forming, and take that batch's fate as this attempt's.
///
/// Members are staged one caller at a time, so each stages against the
/// state the members before it left — a batch can never conflict with
/// itself, only fail on a premise an earlier member invalidated.
async fn attempt_group<F>(
    db: &Db,
    members: &[F],
    coalescer: &Arc<Coalescer>,
) -> Result<CommitOutcome>
where
    F: Fn(&mut Transaction) -> Result<()>,
{
    let staged = coalescer.stage(db, members).await?;

    // A caller that staged nothing is not riding the batch and does not
    // wait on it: it reports the head standing at its turn, exactly as a
    // commit of the same closure alone would.
    if !staged.contributed {
        return Ok(CommitOutcome::Committed(staged.ids));
    }

    match group::await_outcome(staged.outcome).await {
        Outcome::Committed => Ok(CommitOutcome::Committed(staged.ids)),
        Outcome::LostRace => Ok(CommitOutcome::LostRace {
            ours: staged.ours,
            head_before: staged.head_before,
        }),
        Outcome::Nothing => Ok(CommitOutcome::Nothing),
    }
}

/// The view a commit attempt stages against: the cached one when it already
/// matches head, else a fresh materialization. Staging against this is what
/// lets a commit skip the full `current` rescan.
///
/// Every read runs through `db_tx`, so the premise view and the
/// conflict-detection window share one start sequence and no commit can land
/// between them unnoticed. The install is compare-and-set against an epoch
/// captured first, so a head-preserving commit (id reused, content changed)
/// that invalidates mid-read cannot have its invalidation undone here.
pub(crate) async fn head_view_for(
    db_tx: &DbTransaction,
    projections: &std::sync::RwLock<ProjectionCache>,
) -> Result<Arc<CatalogSnapshot>> {
    let epoch = cache_epoch(projections);
    let handle = ReadHandle::Tx(db_tx);
    // The commit path's own gate. `materialize` below carries one too, but
    // a warm cache returns before reaching it, and a commit staged against
    // a view of a keyspace mid-rewrite is the writer-side form of the
    // partial read the marker exists to forbid.
    refuse_mid_migration(handle).await?;
    let head = read_head_id(handle).await?;
    if let Some(view) = cached_head_view(projections, head) {
        return Ok(view);
    }

    let view = Arc::new(materialize(handle, None).await?);
    install_head_view_at(projections, epoch, Arc::clone(&view));

    Ok(view)
}

/// Folds a just-committed head-advancing batch into `base` and installs the
/// result as the new head view, or clears the cache when the fold cannot be
/// applied faithfully. Only for head-advancing commits: their minted id is
/// unique, so a concurrent attempt reading the old id never mistakes this
/// view for its own. Head-preserving commits reuse the id and are handled
/// by clearing the cache before they commit ([`invalidate_head_view`]).
pub(crate) fn refresh_head_view(
    projections: &std::sync::RwLock<ProjectionCache>,
    base: &CatalogSnapshot,
    writes: &[StagedWrite],
) {
    let mut view = base.clone();
    match fold::fold_batch(&mut view, writes) {
        Ok(()) => install_head_view(projections, Arc::new(view)),
        Err(err) => {
            // The committed batch could not be folded into the cached view;
            // dropping the cache is safe (the next commit rescans and
            // reinstalls) but the cause is worth a trace — a batch this
            // writer just built should always fold.
            debug!(error = %err, "head view fold failed; clearing the cached view");
            invalidate_head_view(projections);
        }
    }
}

/// What one attempt staged onto its transaction.
enum Prepared {
    /// The closure changed nothing; the head is unchanged.
    Nothing {
        /// The head snapshot id the attempt read.
        head: u64,
    },
    /// Writes are staged and ready to commit.
    Staged {
        /// This member's change set, empty for an options-only commit.
        ours: Box<ChangeSet>,
        /// The snapshot id a successful commit reports.
        commits: u64,
        /// The staged batch, kept so a successful commit can fold it into
        /// the maintained projections.
        writes: Vec<StagedWrite>,
    },
}

/// The store format the staged state requires: a `building` index implies
/// [`FORMAT_WITH_STAGED_INDEX`], any other index [`FORMAT_WITH_INDEX`],
/// else the base [`FORMAT_VERSION`].
fn target_format(state: &CatalogSnapshot) -> u64 {
    if state
        .indexes
        .values()
        .flat_map(BTreeMap::values)
        .any(|index| index.build_state.is_some())
    {
        FORMAT_WITH_STAGED_INDEX
    } else if state
        .indexes
        .values()
        .any(|per_table| !per_table.is_empty())
    {
        FORMAT_WITH_INDEX
    } else {
        FORMAT_VERSION
    }
}

/// Materializes, runs the closure, and stages the resulting writes.
/// Options-only commits stage no snapshot record and no head advance.
/// The format-stamp write this commit owes, if any. The stamp is lazy and
/// forward-only: a completed or dropped build never downgrades it.
async fn format_stamp(
    db_tx: &DbTransaction,
    state: &CatalogSnapshot,
) -> Result<Option<StagedWrite>> {
    let target_format = target_format(state);
    if target_format <= FORMAT_VERSION {
        return Ok(None);
    }
    let current = read::read_format(ReadHandle::Tx(db_tx))
        .await?
        .map_or(FORMAT_VERSION, |format| format.format_version);
    if current >= target_format {
        return Ok(None);
    }

    // The stamp decides which binaries can open the store from here on.
    info!(
        from = current,
        to = target_format,
        "upgrading the store format stamp"
    );

    Ok(Some((
        Key::Sys(SysKey::Format).encode(),
        Some(value::encode_value(&proto::FormatValue {
            format_version: target_format,
            writer_version: env!("CARGO_PKG_VERSION").to_string(),
        })),
    )))
}

/// The `ducklake_schema_versions` record a schema-changing commit owes for
/// one table. Written by both commit paths and outliving the snapshot
/// record that names the same table: expiry deletes snapshots, and a data
/// file older than every surviving snapshot still has to resolve its
/// schema version.
pub(crate) fn schema_version_write(
    table_id: u64,
    begin_snapshot: u64,
    schema_version: u64,
) -> StagedWrite {
    (
        Key::SchemaVersion {
            table_id,
            begin_snapshot,
        }
        .encode(),
        Some(value::encode_value(&proto::SchemaVersionValue {
            schema_version,
        })),
    )
}

async fn prepare_and_stage<F>(
    db_tx: &DbTransaction,
    f: &F,
    base: &CatalogSnapshot,
) -> Result<Prepared>
where
    F: Fn(&mut Transaction) -> Result<()>,
{
    let head = base.snapshot.snapshot_id;
    let new_id = head + 1;
    let mut tx = Transaction::new(base.clone(), new_id);
    f(&mut tx)?;
    let TransactionParts {
        operations,
        index_entries,
        inline_ops,
        mut state,
        next_catalog_id,
        next_file_id,
    } = tx.into_parts();

    if operations.is_empty() {
        let mut writes = Vec::new();
        diff_options(&mut writes, base, &state);
        if writes.is_empty() {
            return Ok(Prepared::Nothing { head });
        }
        // Re-put the unchanged head as a conflict anchor: every
        // snapshot-minting commit writes it, so a racing drop of this
        // option's scope forces a re-run that re-validates the scope
        // against the winner's state instead of committing blind.
        writes.push((
            Key::Sys(SysKey::Head).encode(),
            Some(value::encode_value(&proto::HeadValue { snapshot_id: head })),
        ));
        stage_writes(db_tx, &writes)?;
        return Ok(Prepared::Staged {
            ours: Box::default(),
            commits: head,
            writes,
        });
    }

    // Entries stage before the entity diff so a poisoned definition rides
    // that diff rather than needing a write of its own.
    let poisoned = index_maintenance::stage_index_entries(db_tx, &index_entries).await?;
    index_maintenance::apply_poison(&mut state, &poisoned);

    let mut writes = diff_writes(base, &state, new_id);
    // Inline records live outside the entity model, so they are translated
    // rather than diffed — and translated against `db_tx`'s pre-commit
    // state, before any of this batch's writes are staged onto it.
    writes.extend(inline::stage_inline_writes(db_tx, &inline_ops).await?);
    writes.extend(format_stamp(db_tx, &state).await?);
    tracing::debug!(
        snapshot = new_id,
        index_entries = index_entries.len(),
        inline_ops = inline_ops.len(),
        catalog_writes = writes.len(),
        poisoned_indexes = poisoned.len(),
        "commit staged"
    );

    let schema_changed = operations.iter().any(Operation::is_schema_changing);
    let schema_changed_table_ids: Vec<u64> = operations
        .iter()
        .filter_map(Operation::schema_changed_table_id)
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect();
    let schema_version = base.snapshot.schema_version + u64::from(schema_changed);
    for table_id in &schema_changed_table_ids {
        writes.push(schema_version_write(*table_id, new_id, schema_version));
    }
    let ours = ChangeSet::from_operations(&operations);

    let snapshot = proto::SnapshotValue {
        snapshot_id: new_id,
        snapshot_time_micros: now_micros(),
        schema_version,
        next_catalog_id,
        next_file_id,
        changes_made: ours.to_changes_made(),
        author: None,
        commit_message: None,
        commit_extra_info: None,
        schema_changed_table_ids,
        // Recorded so a later loser can classify a delete against this
        // commit at file grain; `changes_made` carries only the table.
        deleted_data_file_ids: ours.deleted_data_file_ids.iter().copied().collect(),
    };
    writes.push((
        Key::Snapshot {
            snapshot_id: new_id,
        }
        .encode(),
        Some(value::encode_value(&snapshot)),
    ));
    writes.push((
        Key::Sys(SysKey::Head).encode(),
        Some(value::encode_value(&proto::HeadValue {
            snapshot_id: new_id,
        })),
    ));
    stage_writes(db_tx, &writes)?;

    Ok(Prepared::Staged {
        ours: Box::new(ours),
        commits: new_id,
        writes,
    })
}

pub(crate) fn stage_writes(db_tx: &DbTransaction, writes: &[StagedWrite]) -> Result<()> {
    for (key, write) in writes {
        match write {
            Some(bytes) => db_tx.put(key.clone(), bytes.clone()),
            None => db_tx.delete(key.clone()),
        }
        .map_err(Error::from)?;
    }
    Ok(())
}

/// Commits one staged batch — one commit's or a whole batch of them — and
/// folds the result into the maintained projections. `head` is the id the
/// batch leaves at the head pointer, its last snapshot-minting member's.
///
/// The one place a catalog batch reaches the store: both front doors land
/// here, so the durable write, the head-race classification, and the
/// projection bookkeeping that must accompany them are written once.
pub(crate) async fn commit_batch(
    db_tx: DbTransaction,
    head_before: u64,
    head: u64,
    writes: &[StagedWrite],
    base: &CatalogSnapshot,
    projections: &std::sync::RwLock<ProjectionCache>,
) -> Result<Landed> {
    // A head-preserving commit reuses the head id with new content; drop the
    // cache before the write is visible so no concurrent attempt reads a
    // stale view that still matches by id.
    let head_advanced = head > head_before;
    if !head_advanced {
        invalidate_head_view(projections);
    }
    match commit_durable(db_tx, "commit").await {
        Ok(_) => {
            fold_committed_batch(projections, writes, head);
            if head_advanced {
                refresh_head_view(projections, base, writes);
            }
            Ok(Landed::Committed)
        }
        Err(err) if err.kind() == slatedb::ErrorKind::Transaction => Ok(Landed::LostRace),
        Err(err) => Err(err.into()),
    }
}

/// Commits a group of closures as one batch, retrying benign races with a
/// full re-run — fresh snapshot, closures, ids — so every member's premise
/// re-validates against the state that won. A true conflict surfaces as
/// [`Error::CommitConflict`], which the caller may retry; an exhausted
/// budget surfaces as [`Error::RetryBudgetExhausted`], which it may not.
///
/// Returns one snapshot id per member, in member order. A group of one is
/// the ordinary commit path.
pub(crate) async fn commit_cycle<F>(
    db: &Db,
    members: &[F],
    coalescer: &Arc<Coalescer>,
) -> Result<Vec<SnapshotId>>
where
    F: Fn(&mut Transaction) -> Result<()>,
{
    // Kept across attempts so an exhausted budget can report where the
    // premise started and what it kept losing to.
    let started = std::time::Instant::now();
    let mut first_head = None;
    let mut last_intervening = Vec::new();

    for attempt in 0..MAX_COMMIT_ATTEMPTS {
        // Every path into this loop past the first is a lost race, so the
        // wait belongs here rather than at each `continue`.
        if attempt > 0 {
            tokio::time::sleep(retry_backoff(attempt)).await;
        }
        match attempt_group(db, members, coalescer).await? {
            CommitOutcome::Nothing => {
                tracing::debug!(attempt, "commit's batch wrote nothing; retrying");
            }
            CommitOutcome::Committed(ids) => {
                tracing::debug!(
                    snapshot = ids.last().map(|id| id.get()),
                    members = members.len(),
                    attempt,
                    elapsed_ms = started.elapsed().as_millis(),
                    "commit landed"
                );
                return Ok(ids);
            }
            CommitOutcome::LostRace { ours, head_before } => {
                first_head.get_or_insert(head_before);
                // An options-only loser is last-write-wins: always benign.
                if ours.iter().all(ChangeSet::is_empty) {
                    tracing::debug!(
                        attempt,
                        head_before,
                        "commit lost the head race with nothing to conflict over; retrying"
                    );
                    continue;
                }
                let intervening = intervening_changes(db, head_before).await?;
                for (snapshot_id, theirs) in &intervening {
                    // A group conflicts if any of its members does: they
                    // share a batch, so they share a fate.
                    if ours
                        .iter()
                        .any(|mine| crate::transaction::operations::conflicts(mine, theirs))
                    {
                        tracing::debug!(
                            attempt,
                            head_before,
                            winner = snapshot_id,
                            "commit conflicts with an intervening commit; surfacing"
                        );
                        return Err(Error::CommitConflict(format!(
                            "concurrent commit {snapshot_id} touched the same state"
                        )));
                    }
                }
                last_intervening = intervening.iter().map(|(id, _)| *id).collect();
                tracing::debug!(
                    attempt,
                    head_before,
                    intervening = ?last_intervening,
                    "commit lost the head race to disjoint commits; retrying"
                );
            }
        }
    }

    let head_before = first_head.unwrap_or_default();
    // The only record of an exhausted budget: without it a caller sees a
    // slow commit and no reason for it.
    tracing::warn!(
        attempts = MAX_COMMIT_ATTEMPTS,
        head_before,
        intervening = ?last_intervening,
        "commit exhausted its retry budget; reporting a terminal error"
    );
    Err(Error::RetryBudgetExhausted(format!(
        "spent {MAX_COMMIT_ATTEMPTS} attempts from head snapshot {head_before} without \
         settling; commits above it: {last_intervening:?}"
    )))
}

/// The change sets of every commit above `head_before`, read outside any
/// transaction (the loser's is dead). A record that has already been
/// expired by a racing maintenance commit classifies as an unknowable
/// change (forcing the conflict path), never as corruption — the caller
/// re-drives against the new head.
async fn intervening_changes(db: &Db, head_before: u64) -> Result<Vec<(u64, ChangeSet)>> {
    let head_bytes = db
        .get(Key::Sys(SysKey::Head).encode())
        .await
        .map_err(Error::from)?
        .ok_or_else(|| Error::Corruption("store has no head pointer".to_string()))?;
    let head: proto::HeadValue = value::decode_value(&head_bytes)?;
    let mut changes = Vec::new();

    for snapshot_id in (head_before + 1)..=head.snapshot_id {
        let change_set = match db
            .get(Key::Snapshot { snapshot_id }.encode())
            .await
            .map_err(Error::from)?
        {
            Some(bytes) => {
                let snapshot: proto::SnapshotValue = value::decode_value(&bytes)?;
                let mut change_set = ChangeSet::parse(&snapshot.changes_made);
                // The grammar named the tables this commit deleted from;
                // the record names the files. With both, a delete of ours
                // classifies against it at file grain — without the file
                // ids (a DuckLake-authored snapshot) it stays untargeted
                // and table grain stands.
                if !snapshot.deleted_data_file_ids.is_empty() {
                    change_set.deleted_data_file_ids =
                        snapshot.deleted_data_file_ids.iter().copied().collect();
                    change_set.deletes_untargeted_files = false;
                }
                change_set
            }
            None => ChangeSet {
                has_unknown: true,
                ..ChangeSet::default()
            },
        };
        changes.push((snapshot_id, change_set));
    }

    Ok(changes)
}

#[cfg(test)]
mod tests;