lix 0.12.2

Embeddable version control for apps and AI agents.
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
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
#![allow(clippy::clone_on_copy, clippy::iter_cloned_collect)]

use std::collections::{BTreeMap, BTreeSet};

use crate::LixError;
use crate::changelog::CommitId;
use crate::commit_graph::{CommitGraphNode, CommitGraphStoreReader, ReachableCommitGraphNode};
use crate::storage_adapter::StorageAdapterRead;

/// Walks parent links from `head_commit_id` and returns reachable commits
/// nearest-first.
///
/// `max_depth` bounds the walk itself. A caller that only wants the first few
/// generations pays for those generations, not for the whole graph.
///
/// The walker is intentionally storage-free. It asks `CommitGraphReader` to
/// load parsed commit facts and owns only traversal concerns: batching, cycle
/// detection, and nearest-depth selection.
pub(crate) async fn walk_reachable_nodes<S>(
    reader: &mut CommitGraphStoreReader<S>,
    head_commit_id: &CommitId,
    max_depth: Option<u32>,
) -> Result<Vec<ReachableCommitGraphNode>, LixError>
where
    S: StorageAdapterRead,
{
    let mut walk = ReachableWalk::new(*head_commit_id);
    let mut commits = Vec::new();
    while let Some(layer) = walk.next_layer(reader).await? {
        let depth = layer.depth;
        commits.extend(
            layer
                .commits
                .into_iter()
                .map(|commit| ReachableCommitGraphNode { commit, depth }),
        );
        if max_depth.is_some_and(|max_depth| depth >= max_depth) {
            break;
        }
    }
    Ok(commits)
}

/// One nearest-depth generation of a reachable-commit walk.
pub(crate) struct ReachableLayer {
    pub(crate) depth: u32,
    pub(crate) commits: Vec<CommitGraphNode>,
}

/// Resumable breadth-first cursor over the reachable commit graph.
///
/// Breadth-first order is the order the history surfaces already publish
/// (nearest depth first, commit id within a depth), so a caller that has
/// collected enough rows can simply stop asking for the next layer instead of
/// materializing the remainder of the graph and truncating afterwards.
///
/// Each layer is loaded with one batched point read rather than one storage
/// round-trip per commit.
pub(crate) struct ReachableWalk {
    seen: BTreeSet<CommitId>,
    /// Frontier entries carry the generation of the child that discovered them.
    /// Commit generations are strictly increasing away from the roots, so a
    /// parent that fails to sit below its child proves a corrupt cycle.
    frontier: Vec<(CommitId, u64)>,
    depth: u32,
}

impl ReachableWalk {
    pub(crate) fn new(head_commit_id: CommitId) -> Self {
        Self {
            seen: BTreeSet::from([head_commit_id]),
            frontier: vec![(head_commit_id, u64::MAX)],
            depth: 0,
        }
    }

    pub(crate) async fn next_layer<S>(
        &mut self,
        reader: &mut CommitGraphStoreReader<S>,
    ) -> Result<Option<ReachableLayer>, LixError>
    where
        S: StorageAdapterRead,
    {
        if self.frontier.is_empty() {
            return Ok(None);
        }
        let depth = self.depth;
        let mut frontier = std::mem::take(&mut self.frontier);
        frontier.sort_unstable();
        let commit_ids = frontier
            .iter()
            .map(|(commit_id, _)| *commit_id)
            .collect::<Vec<_>>();
        let loaded = reader.load_nodes(&commit_ids).await?;
        let mut commits = Vec::with_capacity(commit_ids.len());
        let mut next_frontier = Vec::new();
        for ((commit_id, node), (_, child_generation)) in loaded.into_iter().zip(frontier.iter()) {
            let Some(node) = node else {
                return Err(LixError::new(
                    "LIX_ERROR_UNKNOWN",
                    format!("commit_graph missing commit '{commit_id}'"),
                ));
            };
            if node.generation >= *child_generation {
                return Err(LixError::new(
                    "LIX_ERROR_UNKNOWN",
                    format!(
                        "commit_graph cycle detected at commit '{commit_id}': it does not have a lower generation than the child that reaches it"
                    ),
                ));
            }
            for parent_commit_id in &node.parent_commit_ids {
                if self.seen.insert(*parent_commit_id) {
                    next_frontier.push((*parent_commit_id, node.generation));
                }
            }
            commits.push(node);
        }
        self.frontier = next_frontier;
        self.depth = depth.saturating_add(1);
        Ok(Some(ReachableLayer { depth, commits }))
    }
}

/// Returns the best common ancestors shared by two commit heads.
///
/// This is graph math, not merge policy. A commit is "best" when it is a
/// common ancestor and no descendant of it is also a common ancestor.
///
/// Simple history has one best common ancestor:
///
/// ```text
/// A -- B -- C   left
///       \
///        D      right
/// ```
///
/// `best_common_ancestors(C, D)` returns `[B]`.
///
/// Commit history is a DAG, not a tree, so criss-cross histories can have
/// multiple equally good answers. Callers that need one merge base should wrap
/// this API with an explicit policy instead of pretending the graph always has
/// a single lowest common ancestor.
pub(crate) async fn best_common_ancestors<S>(
    reader: &mut CommitGraphStoreReader<S>,
    left_commit_id: &CommitId,
    right_commit_id: &CommitId,
) -> Result<Vec<CommitGraphNode>, LixError>
where
    S: StorageAdapterRead,
{
    let mut loader = NodeTraversalLoader::new(reader);
    let best = loader
        .best_common_ids(*left_commit_id, *right_commit_id)
        .await?;
    let mut nodes = Vec::with_capacity(best.len());
    for commit_id in best {
        nodes.push(loader.load_node(&commit_id).await?);
    }
    Ok(nodes)
}

struct NodeTraversalLoader<'a, S>
where
    S: StorageAdapterRead,
{
    reader: &'a mut CommitGraphStoreReader<S>,
}

impl<'a, S> NodeTraversalLoader<'a, S>
where
    S: StorageAdapterRead,
{
    fn new(reader: &'a mut CommitGraphStoreReader<S>) -> Self {
        Self { reader }
    }

    async fn best_common_ids(
        &mut self,
        left_commit_id: CommitId,
        right_commit_id: CommitId,
    ) -> Result<Vec<CommitId>, LixError> {
        const LEFT: u8 = 1;
        const RIGHT: u8 = 2;
        const BOTH: u8 = LEFT | RIGHT;
        const STALE: u8 = 4;

        let left = self.load_node(&left_commit_id).await?;
        let right = self.load_node(&right_commit_id).await?;
        let mut colors = BTreeMap::from([(left_commit_id, LEFT), (right_commit_id, RIGHT)]);
        if left_commit_id == right_commit_id {
            colors.insert(left_commit_id, BOTH);
        }
        let mut queue = BTreeSet::from([
            (left.generation, left_commit_id),
            (right.generation, right_commit_id),
        ]);
        let mut non_stale_queued = BTreeSet::from([left_commit_id, right_commit_id]);
        let mut best = Vec::new();

        while !queue.is_empty() {
            if !best.is_empty() && non_stale_queued.is_empty() {
                break;
            }
            let (generation, commit_id) = queue.pop_last().expect("queue is not empty");
            non_stale_queued.remove(&commit_id);
            let commit = self.load_node(&commit_id).await?;
            if commit.generation != generation {
                return Err(LixError::unknown(format!(
                    "commit '{commit_id}' generation changed during graph walk"
                )));
            }
            let mut color = colors[&commit_id];
            if color & STALE == 0 && color & BOTH == BOTH {
                best.push(commit_id);
                color |= STALE;
                colors.insert(commit_id, color);
            }
            for parent_commit_id in commit.parent_commit_ids {
                let parent = self.load_node(&parent_commit_id).await?;
                if parent.generation >= generation {
                    return Err(LixError::unknown(format!(
                        "commit '{commit_id}' parent '{parent_commit_id}' does not have a lower generation"
                    )));
                }
                let parent_color = colors.entry(parent_commit_id).or_default();
                *parent_color |= color;
                queue.insert((parent.generation, parent_commit_id));
                if *parent_color & STALE == 0 {
                    non_stale_queued.insert(parent_commit_id);
                } else {
                    non_stale_queued.remove(&parent_commit_id);
                }
            }
        }
        best.sort_unstable();
        best.dedup();
        Ok(best)
    }

    async fn load_node(&mut self, commit_id: &CommitId) -> Result<CommitGraphNode, LixError> {
        let Some(commit) = self.reader.load_node(commit_id).await? else {
            return Err(LixError::new(
                "LIX_ERROR_UNKNOWN",
                format!("commit_graph missing commit '{commit_id}'"),
            ));
        };
        Ok(commit)
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;
    use serde_json::json;

    use crate::LixError;
    use crate::changelog::{
        ChangeId, ChangelogAppend, ChangelogContext, ChangelogWriter, CommitId, CommitRecord,
    };
    use crate::commit_graph::CommitGraphChange;
    use crate::commit_graph::CommitGraphContext;
    use crate::storage_adapter::StorageAdapter;
    use crate::storage_adapter::{Memory, StorageKey, StorageReadOptions, StorageWriteOptions};
    use crate::tracked_state::{
        CommitStateManifest, CommitStateMutationInventory, CommitStateReplayDebt,
    };

    fn ts(value: &str) -> crate::common::LixTimestamp {
        crate::common::LixTimestamp::expect_parse("timestamp", value)
    }

    fn commit_id(label: &str) -> CommitId {
        CommitId::for_test_label(label)
    }

    fn commit_ids<const N: usize>(labels: [&str; N]) -> Vec<CommitId> {
        labels.into_iter().map(commit_id).collect()
    }

    fn sorted_commit_ids<const N: usize>(labels: [&str; N]) -> Vec<CommitId> {
        let mut ids = commit_ids(labels);
        ids.sort();
        ids
    }

    fn sorted_commit_ids_at_depth<const N: usize>(
        labels: [&str; N],
        depth: u32,
    ) -> Vec<(CommitId, u32)> {
        sorted_commit_ids(labels)
            .into_iter()
            .map(|id| (id, depth))
            .collect()
    }

    #[tokio::test]
    async fn reachable_nodes_returns_commits_nearest_first() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change(
                    "commit-parent-change",
                    "commit-parent",
                    &[],
                    &["commit-root"],
                ),
                commit_change("commit-head-change", "commit-head", &[], &["commit-parent"]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head = commit_id("commit-head");
        let commits = reader
            .reachable_nodes(&commit_head)
            .await
            .expect("reachable commits should load");

        assert_eq!(
            commits
                .iter()
                .map(|reachable| (reachable.commit.commit_id.clone(), reachable.depth))
                .collect::<Vec<_>>(),
            vec![
                (commit_id("commit-head"), 0),
                (commit_id("commit-parent"), 1),
                (commit_id("commit-root"), 2)
            ]
        );
    }

    #[tokio::test]
    async fn reachable_nodes_errors_on_missing_parent_commit() {
        let storage = StorageAdapter::new(Memory::new());
        let error = append_changes_result(
            &storage,
            &[commit_change(
                "commit-head-change",
                "commit-head",
                &[],
                &["missing-parent"],
            )],
        )
        .await
        .expect_err("changelog should reject missing parent");

        assert!(
            error
                .message
                .contains(&commit_id("missing-parent").to_string())
        );
    }

    #[tokio::test]
    async fn exact_graph_read_rejects_record_stored_under_another_commit_key() {
        let storage = StorageAdapter::new(Memory::new());
        let requested = commit_id("requested-commit");
        let embedded = commit_id("embedded-commit");
        let mut writes = storage.new_write_set();
        writes.put(
            crate::changelog::COMMIT_SPACE,
            StorageKey(Bytes::copy_from_slice(requested.as_uuid().as_bytes())),
            crate::changelog::encode_commit_record(&CommitRecord {
                touched_scope_digest: crate::changelog::CommitTouchedScopeDigest::absent(),
                format_version: 4,
                commit_id: embedded,
                generation: 0,
                parent_commit_ids: Vec::new(),
                first_parent_jump_commit_id: embedded,
                first_parent_jump_span: 0,
                account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
                created_at: ts("2026-01-01T00:00:00Z"),
            })
            .expect("mismatched commit should encode"),
        );
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("mismatched commit should persist");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = reader
            .load_node(&requested)
            .await
            .expect_err("exact read must reject a mismatched embedded commit id");

        assert!(
            error
                .message
                .contains("identity does not match requested key")
        );
    }

    #[tokio::test]
    async fn reachable_nodes_errors_on_cycle() {
        let storage = StorageAdapter::new(Memory::new());
        let mut writes = storage.new_write_set();
        for (label, parent) in [("commit-a", "commit-b"), ("commit-b", "commit-a")] {
            let current_commit_id = commit_id(label);
            let parent_commit_id = commit_id(parent);
            let record = CommitRecord {
                touched_scope_digest: crate::changelog::CommitTouchedScopeDigest::absent(),
                format_version: 4,
                commit_id: current_commit_id,
                generation: 1,
                parent_commit_ids: vec![parent_commit_id],
                first_parent_jump_commit_id: parent_commit_id,
                first_parent_jump_span: 1,
                account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
                created_at: ts("2026-01-01T00:00:00Z"),
            };
            writes.put(
                crate::changelog::COMMIT_SPACE,
                StorageKey(Bytes::copy_from_slice(
                    current_commit_id.as_uuid().as_bytes(),
                )),
                crate::changelog::encode_commit_record(&record)
                    .expect("cycle commit should encode"),
            );
            stage_test_commit_manifest(&mut writes, &record)
                .expect("cycle commit authority should stage");
        }
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("corrupt cycle should persist");

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_a = commit_id("commit-a");
        let error = reader
            .reachable_nodes(&commit_a)
            .await
            .expect_err("walker should reject parent cycles");

        assert!(error.message.contains("cycle"));
    }

    #[tokio::test]
    async fn reachable_nodes_dedupes_shared_ancestors_in_diamond() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-root"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-root"]),
                commit_change(
                    "commit-head-change",
                    "commit-head",
                    &[],
                    &["commit-left", "commit-right"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head = commit_id("commit-head");
        let commits = reader
            .reachable_nodes(&commit_head)
            .await
            .expect("reachable commits should load");
        let mut expected = vec![(commit_id("commit-head"), 0)];
        expected.extend(sorted_commit_ids_at_depth(
            ["commit-left", "commit-right"],
            1,
        ));
        expected.push((commit_id("commit-root"), 2));

        assert_eq!(
            commits
                .iter()
                .map(|reachable| (reachable.commit.commit_id.clone(), reachable.depth))
                .collect::<Vec<_>>(),
            expected
        );
    }

    #[tokio::test]
    async fn reachable_nodes_keeps_nearest_depth_for_multiple_paths() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change(
                    "commit-parent-change",
                    "commit-parent",
                    &[],
                    &["commit-root"],
                ),
                commit_change(
                    "commit-head-change",
                    "commit-head",
                    &[],
                    &["commit-root", "commit-parent"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head = commit_id("commit-head");
        let commits = reader
            .reachable_nodes(&commit_head)
            .await
            .expect("reachable commits should load");

        assert_eq!(
            commits
                .iter()
                .map(|reachable| (reachable.commit.commit_id.clone(), reachable.depth))
                .collect::<Vec<_>>(),
            vec![
                (commit_id("commit-head"), 0),
                (commit_id("commit-parent"), 1),
                (commit_id("commit-root"), 1)
            ]
        );
    }

    #[tokio::test]
    async fn reachable_nodes_orders_same_depth_commits_by_id() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-z-change", "commit-z", &[], &[]),
                commit_change("commit-a-change", "commit-a", &[], &[]),
                commit_change(
                    "commit-head-change",
                    "commit-head",
                    &[],
                    &["commit-z", "commit-a"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head = commit_id("commit-head");
        let commits = reader
            .reachable_nodes(&commit_head)
            .await
            .expect("reachable commits should load");
        let mut expected = vec![(commit_id("commit-head"), 0)];
        expected.extend(sorted_commit_ids_at_depth(["commit-z", "commit-a"], 1));

        assert_eq!(
            commits
                .iter()
                .map(|reachable| (reachable.commit.commit_id.clone(), reachable.depth))
                .collect::<Vec<_>>(),
            expected
        );
    }

    #[tokio::test]
    async fn bounded_reachable_nodes_match_unbounded_prefix_for_a_diamond() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-root"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-root"]),
                commit_change(
                    "commit-head-change",
                    "commit-head",
                    &[],
                    &["commit-left", "commit-right"],
                ),
            ],
        )
        .await;

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let head = commit_id("commit-head");
        let full = reader
            .reachable_nodes(&head)
            .await
            .expect("full diamond should load");
        for max_depth in [0, 1, 2] {
            let bounded = super::walk_reachable_nodes(&mut reader, &head, Some(max_depth))
                .await
                .expect("bounded diamond should load");
            let expected = full
                .iter()
                .filter(|reachable| reachable.depth <= max_depth)
                .cloned()
                .collect::<Vec<_>>();
            assert_eq!(bounded, expected);
        }
    }

    #[tokio::test]
    async fn bounded_reachable_nodes_match_unbounded_prefix_for_linear_history() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change(
                    "commit-parent-change",
                    "commit-parent",
                    &[],
                    &["commit-root"],
                ),
                commit_change("commit-head-change", "commit-head", &[], &["commit-parent"]),
            ],
        )
        .await;

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let head = commit_id("commit-head");
        let full = reader
            .reachable_nodes(&head)
            .await
            .expect("full linear history should load");
        for max_depth in [0, 1, 2] {
            let bounded = super::walk_reachable_nodes(&mut reader, &head, Some(max_depth))
                .await
                .expect("bounded linear history should load");
            let expected = full
                .iter()
                .filter(|reachable| reachable.depth <= max_depth)
                .cloned()
                .collect::<Vec<_>>();
            assert_eq!(bounded, expected);
        }
    }

    #[tokio::test]
    async fn bounded_reachable_nodes_validate_only_parents_inside_the_frontier() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change(
                    "commit-parent-change",
                    "commit-parent",
                    &[],
                    &["commit-root"],
                ),
                commit_change("commit-head-change", "commit-head", &[], &["commit-parent"]),
            ],
        )
        .await;
        let root = commit_id("commit-root");
        let mut writes = storage.new_write_set();
        writes.delete(
            crate::changelog::COMMIT_SPACE,
            StorageKey(Bytes::copy_from_slice(root.as_uuid().as_bytes())),
        );
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("old ancestry corruption should stage");

        let head = commit_id("commit-head");
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let bounded = super::walk_reachable_nodes(&mut reader, &head, Some(1))
            .await
            .expect("parent below the frontier must not load");
        assert_eq!(bounded.len(), 2);

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = super::walk_reachable_nodes(&mut reader, &head, Some(2))
            .await
            .expect_err("missing parent inside the frontier must fail");
        assert!(error.message.contains(&root.to_string()));
    }

    #[tokio::test]
    async fn bounded_reachable_nodes_reject_cycles_closed_at_the_frontier() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[commit_change("commit-root-change", "commit-root", &[], &[])],
        )
        .await;
        let root = commit_id("commit-root");
        let left = commit_id("commit-cycle-left");
        let right = commit_id("commit-cycle-right");
        let record = |commit_id, parents| CommitRecord {
            touched_scope_digest: crate::changelog::CommitTouchedScopeDigest::absent(),
            format_version: 4,
            commit_id,
            generation: 2,
            parent_commit_ids: parents,
            first_parent_jump_commit_id: commit_id,
            first_parent_jump_span: 0,
            account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
            created_at: ts("2026-01-01T00:00:00Z"),
        };
        let records = [
            record(left, vec![right, root]),
            record(right, vec![left, root]),
        ];
        let mut writes = storage.new_write_set();
        for record in records {
            writes.put(
                crate::changelog::COMMIT_SPACE,
                StorageKey(Bytes::copy_from_slice(
                    record.commit_id.as_uuid().as_bytes(),
                )),
                crate::changelog::encode_commit_record(&record)
                    .expect("cyclic record should encode"),
            );
        }
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("cycle should persist");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = super::walk_reachable_nodes(&mut reader, &left, Some(1))
            .await
            .expect_err("cycle closed at the frontier must fail");
        assert!(error.message.contains("cycle detected"));
    }

    #[tokio::test]
    async fn reachable_nodes_errors_on_missing_head_commit() {
        let storage = StorageAdapter::new(Memory::new());
        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let missing_head = commit_id("missing-head");

        let error = reader
            .reachable_nodes(&missing_head)
            .await
            .expect_err("missing head should fail");

        assert!(error.message.contains(&missing_head.to_string()));
    }

    #[tokio::test]
    async fn best_common_ancestors_returns_nearest_common_commit_in_simple_graph() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-a-change", "commit-a", &[], &[]),
                commit_change("commit-b-change", "commit-b", &[], &["commit-a"]),
                commit_change("commit-c-change", "commit-c", &[], &["commit-b"]),
                commit_change("commit-d-change", "commit-d", &[], &["commit-b"]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_c = commit_id("commit-c");
        let commit_d = commit_id("commit-d");
        let ancestors = reader
            .best_common_ancestors(&commit_c, &commit_d)
            .await
            .expect("best common ancestors should load");

        assert_eq!(
            ancestors
                .iter()
                .map(|commit| commit.commit_id.clone())
                .collect::<Vec<_>>(),
            commit_ids(["commit-b"])
        );
    }

    #[tokio::test]
    async fn best_common_ancestors_does_not_walk_the_shared_history_below_the_frontier() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change(
                    "commit-parent-change",
                    "commit-parent",
                    &[],
                    &["commit-root"],
                ),
                commit_change("commit-base-change", "commit-base", &[], &["commit-parent"]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-base"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-base"]),
            ],
        )
        .await;
        let root = commit_id("commit-root");
        let mut writes = storage.new_write_set();
        writes.delete(
            crate::changelog::COMMIT_SPACE,
            StorageKey(Bytes::copy_from_slice(root.as_uuid().as_bytes())),
        );
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("old shared history corruption should stage");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let ancestors = reader
            .best_common_ancestors(&commit_id("commit-left"), &commit_id("commit-right"))
            .await
            .expect("merge base should stop at the shared frontier");

        assert_eq!(
            ancestors
                .into_iter()
                .map(|commit| commit.commit_id)
                .collect::<Vec<_>>(),
            commit_ids(["commit-base"])
        );
    }

    #[tokio::test]
    async fn merge_base_and_general_walk_reject_non_decreasing_parent_generation() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-child-change", "commit-child", &[], &["commit-root"]),
                commit_change(
                    "commit-sibling-change",
                    "commit-sibling",
                    &[],
                    &["commit-root"],
                ),
                commit_change(
                    "commit-grandchild-change",
                    "commit-grandchild",
                    &[],
                    &["commit-child"],
                ),
            ],
        )
        .await;
        let child = commit_id("commit-child");
        let mut writes = storage.new_write_set();
        let record = CommitRecord {
            touched_scope_digest: crate::changelog::CommitTouchedScopeDigest::absent(),
            format_version: 4,
            commit_id: child,
            generation: 0,
            parent_commit_ids: commit_ids(["commit-root"]),
            first_parent_jump_commit_id: child,
            first_parent_jump_span: 0,
            account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
            created_at: ts("2026-01-01T00:00:00Z"),
        };
        writes.put(
            crate::changelog::COMMIT_SPACE,
            StorageKey(Bytes::copy_from_slice(child.as_uuid().as_bytes())),
            crate::changelog::encode_commit_record(&record).expect("corrupt commit should encode"),
        );
        stage_test_commit_manifest(&mut writes, &record)
            .expect("matching corrupt authority should stage");
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("corrupt commit should persist");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = reader
            .best_common_ancestors(&child, &commit_id("commit-root"))
            .await
            .expect_err("invalid generations should fail the graph walk");

        assert!(
            error.message.contains("does not have a lower generation")
                || error
                    .message
                    .contains("first-parent jump span exceeds its generation")
                || error.message.contains("no advancing first-parent jump")
        );

        for (left, right) in [
            ("commit-root", "commit-child"),
            ("commit-child", "commit-root"),
        ] {
            let read = storage
                .begin_read(StorageReadOptions::default())
                .await
                .expect("read should open");
            let mut reader = CommitGraphContext::new().reader(read);
            let error = reader
                .merge_base(&commit_id(left), &commit_id(right))
                .await
                .expect_err("direct-parent shortcut must reject invalid generations");
            assert!(
                error.message.contains("does not have a lower generation")
                    || error.message.contains("no advancing first-parent jump")
            );
        }

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = reader
            .merge_base(&commit_id("commit-child"), &commit_id("commit-sibling"))
            .await
            .expect_err("shared-parent shortcut must reject invalid generations");
        assert!(
            error.message.contains("does not have a lower generation")
                || error.message.contains("no advancing first-parent jump")
        );

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let error = reader
            .merge_base(&commit_id("commit-root"), &commit_id("commit-grandchild"))
            .await
            .expect_err("linear prefix and DAG fallback must preserve generation validation");
        assert!(
            error.message.contains("does not have a lower generation")
                || error.message.contains("no advancing first-parent jump")
        );
    }

    #[tokio::test]
    async fn best_common_ancestors_returns_shared_fork_in_diamond_graph() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-root"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-root"]),
                commit_change(
                    "commit-left-head-change",
                    "commit-left-head",
                    &[],
                    &["commit-left"],
                ),
                commit_change(
                    "commit-right-head-change",
                    "commit-right-head",
                    &[],
                    &["commit-right"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_left_head = commit_id("commit-left-head");
        let commit_right_head = commit_id("commit-right-head");
        let ancestors = reader
            .best_common_ancestors(&commit_left_head, &commit_right_head)
            .await
            .expect("best common ancestors should load");

        assert_eq!(
            ancestors
                .iter()
                .map(|commit| commit.commit_id.clone())
                .collect::<Vec<_>>(),
            commit_ids(["commit-root"])
        );
    }

    #[tokio::test]
    async fn best_common_ancestors_returns_parent_when_one_side_is_ancestor() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-a-change", "commit-a", &[], &[]),
                commit_change("commit-b-change", "commit-b", &[], &["commit-a"]),
                commit_change("commit-c-change", "commit-c", &[], &["commit-b"]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_b = commit_id("commit-b");
        let commit_c = commit_id("commit-c");
        let ancestors = reader
            .best_common_ancestors(&commit_b, &commit_c)
            .await
            .expect("best common ancestors should load");

        assert_eq!(
            ancestors
                .iter()
                .map(|commit| commit.commit_id.clone())
                .collect::<Vec<_>>(),
            commit_ids(["commit-b"])
        );
    }

    #[tokio::test]
    async fn best_common_ancestors_returns_multiple_bases_for_criss_cross_graph() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-root"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-root"]),
                commit_change(
                    "commit-head-left-change",
                    "commit-head-left",
                    &[],
                    &["commit-left", "commit-right"],
                ),
                commit_change(
                    "commit-head-right-change",
                    "commit-head-right",
                    &[],
                    &["commit-right", "commit-left"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head_left = commit_id("commit-head-left");
        let commit_head_right = commit_id("commit-head-right");
        let ancestors = reader
            .best_common_ancestors(&commit_head_left, &commit_head_right)
            .await
            .expect("best common ancestors should load");

        assert_eq!(
            ancestors
                .iter()
                .map(|commit| commit.commit_id.clone())
                .collect::<Vec<_>>(),
            sorted_commit_ids(["commit-left", "commit-right"])
        );
    }

    #[tokio::test]
    async fn merge_base_returns_single_best_common_ancestor() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-a-change", "commit-a", &[], &[]),
                commit_change("commit-b-change", "commit-b", &[], &["commit-a"]),
                commit_change("commit-c-change", "commit-c", &[], &["commit-b"]),
                commit_change("commit-d-change", "commit-d", &[], &["commit-b"]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_c = commit_id("commit-c");
        let commit_d = commit_id("commit-d");
        let base = reader
            .merge_base(&commit_c, &commit_d)
            .await
            .expect("single merge base should resolve");

        assert_eq!(base, commit_id("commit-b"));
    }

    #[tokio::test]
    async fn merge_base_resolves_deep_linear_ancestor_and_fork() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-a-change", "commit-a", &[], &[]),
                commit_change("commit-b-change", "commit-b", &[], &["commit-a"]),
                commit_change("commit-c-change", "commit-c", &[], &["commit-b"]),
                commit_change("commit-d-change", "commit-d", &[], &["commit-c"]),
                commit_change("commit-e-change", "commit-e", &[], &["commit-d"]),
                commit_change("commit-x-change", "commit-x", &[], &["commit-b"]),
                commit_change("commit-y-change", "commit-y", &[], &["commit-x"]),
                commit_change("commit-z-change", "commit-z", &[], &["commit-y"]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);

        assert_eq!(
            reader
                .merge_base(&commit_id("commit-b"), &commit_id("commit-e"))
                .await
                .expect("deep ancestor should resolve"),
            commit_id("commit-b")
        );
        assert_eq!(
            reader
                .merge_base(&commit_id("commit-e"), &commit_id("commit-z"))
                .await
                .expect("deep linear fork should resolve"),
            commit_id("commit-b")
        );
    }

    #[tokio::test]
    async fn merge_base_segment_skips_refine_shared_fork_and_unequal_head() {
        let storage = StorageAdapter::new(Memory::new());
        let mut changes = Vec::new();
        changes.push(commit_change(
            "segment-root-change",
            "segment-root",
            &[],
            &[],
        ));
        let mut trunk_parent = "segment-root".to_string();
        for index in 1..=70 {
            let label = format!("segment-trunk-{index}");
            changes.push(commit_change(
                &format!("{label}-change"),
                &label,
                &[],
                &[&trunk_parent],
            ));
            trunk_parent = label;
        }
        let fork = trunk_parent.clone();
        let mut left_parent = fork.clone();
        let mut right_parent = fork.clone();
        for index in 1..=130 {
            let left = format!("segment-left-{index}");
            changes.push(commit_change(
                &format!("{left}-change"),
                &left,
                &[],
                &[&left_parent],
            ));
            left_parent = left;
            let right = format!("segment-right-{index}");
            changes.push(commit_change(
                &format!("{right}-change"),
                &right,
                &[],
                &[&right_parent],
            ));
            right_parent = right;
        }
        append_changes(&storage, &changes).await;

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("general-walker read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        let general = reader
            .best_common_ancestors(&commit_id(&left_parent), &commit_id(&right_parent))
            .await
            .expect("general walker should resolve fork");
        assert_eq!(
            general
                .iter()
                .map(|node| node.commit_id)
                .collect::<Vec<_>>(),
            vec![commit_id(&fork)],
            "Myers fast path must agree with the general DAG walker",
        );

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        assert_eq!(
            reader
                .merge_base(&commit_id(&left_parent), &commit_id(&right_parent))
                .await
                .expect("segmented fork should resolve exactly"),
            commit_id(&fork)
        );

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("second read should open");
        let mut reader = CommitGraphContext::new().reader(read);
        assert_eq!(
            reader
                .merge_base(&commit_id("segment-trunk-10"), &commit_id(&left_parent))
                .await
                .expect("unequal segmented ancestor should resolve exactly"),
            commit_id("segment-trunk-10")
        );
    }

    #[tokio::test]
    async fn merge_base_errors_when_histories_have_no_common_commit() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-left-change", "commit-left", &[], &[]),
                commit_change("commit-right-change", "commit-right", &[], &[]),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_left = commit_id("commit-left");
        let commit_right = commit_id("commit-right");
        let error = reader
            .merge_base(&commit_left, &commit_right)
            .await
            .expect_err("unrelated histories should not have a merge base");

        assert!(error.message.contains("no common history"));
    }

    #[tokio::test]
    async fn merge_base_errors_when_best_common_ancestor_is_ambiguous() {
        let storage = StorageAdapter::new(Memory::new());
        append_changes(
            &storage,
            &[
                commit_change("commit-root-change", "commit-root", &[], &[]),
                commit_change("commit-left-change", "commit-left", &[], &["commit-root"]),
                commit_change("commit-right-change", "commit-right", &[], &["commit-root"]),
                commit_change(
                    "commit-head-left-change",
                    "commit-head-left",
                    &[],
                    &["commit-left", "commit-right"],
                ),
                commit_change(
                    "commit-head-right-change",
                    "commit-head-right",
                    &[],
                    &["commit-right", "commit-left"],
                ),
                commit_change(
                    "commit-left-tail-1-change",
                    "commit-left-tail-1",
                    &[],
                    &["commit-head-left"],
                ),
                commit_change(
                    "commit-left-tail-2-change",
                    "commit-left-tail-2",
                    &[],
                    &["commit-left-tail-1"],
                ),
                commit_change(
                    "commit-right-tail-1-change",
                    "commit-right-tail-1",
                    &[],
                    &["commit-head-right"],
                ),
                commit_change(
                    "commit-right-tail-2-change",
                    "commit-right-tail-2",
                    &[],
                    &["commit-right-tail-1"],
                ),
            ],
        )
        .await;

        let graph = CommitGraphContext::new();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut reader = graph.reader(read);
        let commit_head_left = commit_id("commit-left-tail-2");
        let commit_head_right = commit_id("commit-right-tail-2");
        let error = reader
            .merge_base(&commit_head_left, &commit_head_right)
            .await
            .expect_err("ambiguous best common ancestors should fail");

        assert_eq!(error.code, LixError::CODE_AMBIGUOUS_MERGE_BASE);
        assert_eq!(
            error
                .details
                .as_ref()
                .and_then(|details| details.get("left_commit_id")),
            Some(&json!(commit_id("commit-left-tail-2").to_string()))
        );
        assert_eq!(
            error
                .details
                .as_ref()
                .and_then(|details| details.get("right_commit_id")),
            Some(&json!(commit_id("commit-right-tail-2").to_string()))
        );
        assert_eq!(
            error
                .details
                .as_ref()
                .and_then(|details| details.get("candidates")),
            Some(&json!(
                sorted_commit_ids(["commit-left", "commit-right"])
                    .into_iter()
                    .map(|id| id.to_string())
                    .collect::<Vec<_>>()
            ))
        );
    }

    #[derive(Clone)]
    struct TestCommitChange {
        change: CommitGraphChange,
        parent_commit_ids: Vec<CommitId>,
    }

    async fn append_changes(storage: &StorageAdapter, changes: &[TestCommitChange]) {
        append_changes_result(storage, changes)
            .await
            .expect("changelog fixture should append");
    }

    async fn append_changes_result(
        storage: &StorageAdapter,
        changes: &[TestCommitChange],
    ) -> Result<(), LixError> {
        let mut read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let mut writes = storage.new_write_set();
        let mut append = ChangelogAppend::default();
        let mut generations = std::collections::BTreeMap::<CommitId, u64>::new();
        let mut topology_records = std::collections::BTreeMap::<CommitId, CommitRecord>::new();
        for change in changes {
            let commit_id = change
                .change
                .row_pk
                .as_single_string()
                .expect("commit fixture should have single id")
                .to_string();
            let parent_commit_ids = change.parent_commit_ids.iter().copied().collect::<Vec<_>>();
            let generation = parent_commit_ids
                .iter()
                .filter_map(|parent| generations.get(parent).copied())
                .max()
                .map_or_else(
                    || usize::from(!parent_commit_ids.is_empty()) as u64,
                    |parent_generation| parent_generation + 1,
                );
            let typed_commit_id = CommitId::for_test_label(&commit_id);
            let parent = match parent_commit_ids.as_slice() {
                [parent_commit_id] => topology_records.get(parent_commit_id),
                _ => None,
            };
            let (first_parent_jump_commit_id, first_parent_jump_span) = match parent {
                Some(parent) => {
                    let parent_jump = topology_records
                        .get(&parent.first_parent_jump_commit_id)
                        .expect("test parent jump target exists");
                    crate::changelog::next_first_parent_jump(
                        typed_commit_id,
                        &parent_commit_ids,
                        Some(parent),
                        Some(parent_jump),
                    )
                    .expect("test commit jump should derive")
                }
                None => match parent_commit_ids.as_slice() {
                    [missing_parent] => (*missing_parent, 1),
                    _ => (typed_commit_id, 0),
                },
            };
            let record = CommitRecord {
                touched_scope_digest: crate::changelog::CommitTouchedScopeDigest::absent(),
                format_version: 4,
                commit_id: typed_commit_id,
                generation,
                parent_commit_ids,
                first_parent_jump_commit_id,
                first_parent_jump_span,
                account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
                created_at: change.change.created_at,
            };
            append.commits.push(record.clone());
            topology_records.insert(typed_commit_id, record);
            generations.insert(typed_commit_id, generation);
        }
        let commit_records = append.commits.clone();
        ChangelogContext::new()
            .writer(&mut read, &mut writes)
            .stage_append(append)
            .await?;
        for record in &commit_records {
            stage_test_commit_manifest(&mut writes, record)?;
        }
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("commit should succeed");
        Ok(())
    }

    fn stage_test_commit_manifest(
        writes: &mut crate::storage_adapter::StorageWriteSet,
        record: &CommitRecord,
    ) -> Result<(), LixError> {
        crate::tracked_state::stage_resealed_commit_state_manifest_for_test(
            writes,
            &CommitStateManifest {
                commit_id: record.commit_id,
                change_account_id: record.account_id.clone(),
                replay_debt: CommitStateReplayDebt {
                    depth: 1,
                    rows: 0,
                    bytes: 0,
                },
                mutations: CommitStateMutationInventory::default(),
                touched_scope_filter: Default::default(),
                current_state_scoped_ranges: None,
                snapshot_root: None,
            },
        )
    }

    fn commit_change(
        change_id: &str,
        commit_id: &str,
        change_ids: &[&str],
        parent_commit_ids: &[&str],
    ) -> TestCommitChange {
        let _ = change_ids;
        TestCommitChange {
            change: CommitGraphChange {
                id: ChangeId::for_test_label(change_id),
                account_id: crate::ANONYMOUS_ACCOUNT_ID.to_string(),
                row_pk: crate::row_pk::RowPk::single(commit_id),
                schema_key: "lix_commit".to_string(),
                file_id: None,
                snapshot: crate::json_store::JsonSlot::None,
                metadata: crate::json_store::JsonSlot::None,
                created_at: ts("2026-01-01T00:00:00Z"),
                origin_key: None,
            },
            parent_commit_ids: parent_commit_ids
                .iter()
                .map(|id| CommitId::for_test_label(id))
                .collect(),
        }
    }
}