lix 0.18.0

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
use lix::Value;
use serde_json::json;

use super::assert_rows_eq;

simulation_test!(
    state_at_reads_tracked_schema_state_at_a_commit,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );

        session
        .execute(
            "INSERT INTO lix_key_value (key, value) VALUES ('state-at-key', CAST('{\"v\":1}' AS JSONB))",
            &[],
        )
        .await
        .expect("row should insert");
        let commit = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(commit_id)] = commit.rows()[0].values() else {
            panic!("expected commit id");
        };

        session
        .execute(
            "UPDATE lix_key_value SET value = CAST('{\"v\":2}' AS JSONB) WHERE key = 'state-at-key'",
            &[],
        )
        .await
        .expect("row should update");

        crate::sql2::arm_state_at_traversal_probe(commit_id);
        let result = session
            .execute(
                "SELECT key, value, lixcol_untracked FROM lix_as_of('lix_key_value', $1) \
             WHERE key IN ('state-at-key', 'absent')",
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("historical state should load");
        assert_rows_eq(
            result,
            vec![vec![
                Value::Text("state-at-key".into()),
                Value::Jsonb(json!({ "v": 1 }).into()),
                Value::Boolean(false),
            ]],
        );
        assert_eq!(
            crate::sql2::take_state_at_traversal_probe(commit_id),
            vec![(2, 1)],
            "schema primary-key IN must resolve only matching identities before exact tree reads"
        );

        let root = session
            .execute(
                "SELECT key FROM lix_as_of('lix_key_value', lix_root_commit_id())",
                &[],
            )
            .await
            .expect("root state should load");
        assert!(root.rows().is_empty());

        let contradiction = session
            .execute(
                "SELECT key FROM lix_as_of('lix_key_value', $1) WHERE key = 'a' AND key = 'b'",
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("contradictory point state should load");
        assert!(contradiction.rows().is_empty());
    }
);

simulation_test!(
    state_at_primary_key_keeps_duplicate_file_scopes,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );
        let first = "01991b1d-6d8b-7000-8000-000000000011";
        let second = "01991b1d-6d8b-7000-8000-000000000012";
        session
            .execute(
                "INSERT INTO lix_file (id, path, content) VALUES \
             ($1, '/state-at-first', CAST('a' AS BYTEA)), \
             ($2, '/state-at-second', CAST('b' AS BYTEA))",
                &[Value::Text(first.into()), Value::Text(second.into())],
            )
            .await
            .expect("files should insert");
        session
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_file_id) VALUES \
             ('shared-pk', 'first', $1)",
                &[Value::Text(first.into())],
            )
            .await
            .expect("first scoped row should insert");
        session
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_file_id) VALUES \
             ('shared-pk', 'second', $1)",
                &[Value::Text(second.into())],
            )
            .await
            .expect("second scoped row should insert");
        let commit = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(commit_id)] = commit.rows()[0].values() else {
            panic!("expected commit id");
        };

        crate::sql2::arm_state_at_traversal_probe(commit_id);
        let result = session
            .execute(
                "SELECT lixcol_file_id, value \
             FROM lix_as_of('lix_key_value', $1) \
             WHERE key = 'shared-pk' ORDER BY lixcol_file_id",
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("both scoped identities should load");
        assert_rows_eq(
            result,
            vec![
                vec![
                    Value::Text(first.into()),
                    Value::Jsonb(json!("first").into()),
                ],
                vec![
                    Value::Text(second.into()),
                    Value::Jsonb(json!("second").into()),
                ],
            ],
        );
        assert_eq!(
            crate::sql2::take_state_at_traversal_probe(commit_id),
            vec![(1, 2)],
            "one primary-key prefix must discover both file-scoped identities"
        );
    }
);

simulation_test!(
    state_at_materializes_historical_file_content_and_path,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );
        let id = "01991b1d-6d8b-7000-8000-000000000001";

        session
        .execute(
            &format!(
                "INSERT INTO lix_file (id, path, content) VALUES ('{id}', '/nested/before.txt', CAST('before' AS BYTEA))"
            ),
            &[],
        )
        .await
        .expect("file should insert");
        let commit = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(commit_id)] = commit.rows()[0].values() else {
            panic!("expected commit id");
        };

        session
        .execute(
            &format!("UPDATE lix_file SET path = '/after.txt', content = CAST('after' AS BYTEA) WHERE id = '{id}'"),
            &[],
        )
        .await
        .expect("file should update");

        let result = session
            .execute(
                "SELECT id, path, content FROM lix_as_of('lix_file', $1) WHERE id = $2",
                &[Value::Text(commit_id.clone()), Value::Text(id.into())],
            )
            .await
            .expect("historical file should load");
        assert_rows_eq(
            result,
            vec![vec![
                Value::Text(id.into()),
                Value::Text("/nested/before.txt".into()),
                Value::Blob(b"before".to_vec().into()),
            ]],
        );
    }
);

simulation_test!(
    state_at_reads_historical_empty_file_content,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );
        let empty_id = "01991b1d-6d8b-7000-8000-000000000002";

        session
        .execute(
            "INSERT INTO lix_file (id, path, content) VALUES ($1, '/empty.csv', CAST('' AS BYTEA))",
            &[Value::Text(empty_id.into())],
        )
        .await
        .expect("empty file should insert");
        let commit = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(commit_id)] = commit.rows()[0].values() else {
            panic!("expected commit id");
        };

        let result = session
            .execute(
                "SELECT id, path, content FROM lix_as_of('lix_file', $1) WHERE path = '/empty.csv'",
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("historical empty file should load");
        assert_rows_eq(
            result,
            vec![vec![
                Value::Text(empty_id.into()),
                Value::Text("/empty.csv".into()),
                Value::Blob(Vec::new().into()),
            ]],
        );
    }
);

simulation_test!(
    state_at_matches_live_columns_and_unchanged_row_metadata,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );

        session
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('stable', 'value')",
                &[],
            )
            .await
            .expect("stable row should insert");
        let commit = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(commit_id)] = commit.rows()[0].values() else {
            panic!("expected commit id");
        };
        session
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('later', 'unrelated')",
                &[],
            )
            .await
            .expect("unrelated row should insert");

        let columns = "key, value, lixcol_file_id, lixcol_metadata, \
                   lixcol_created_at, lixcol_updated_at, lixcol_global, lixcol_change_id, \
                   lixcol_commit_id, lixcol_untracked";
        let live = session
            .execute(
                &format!("SELECT {columns} FROM lix_key_value WHERE key = 'stable'"),
                &[],
            )
            .await
            .expect("live row should load");
        let historical = session
            .execute(
                &format!(
                    "SELECT {columns} FROM lix_as_of('lix_key_value', $1) WHERE key = 'stable'"
                ),
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("historical row should load");
        assert_eq!(historical.columns(), live.columns());
        assert_eq!(historical.rows(), live.rows());
        let historical_star = session
            .execute(
                "SELECT * FROM lix_as_of('lix_key_value', $1) WHERE key = 'stable'",
                &[Value::Text(commit_id.clone())],
            )
            .await
            .expect("historical wildcard should load");
        let current_star = session
            .execute("SELECT * FROM lix_key_value WHERE key = 'stable'", &[])
            .await
            .expect("current wildcard should load");
        assert_eq!(historical_star.columns(), current_star.columns());
    }
);

simulation_test!(
    state_at_omits_deleted_and_untracked_rows,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );

        session
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('deleted', 'before')",
                &[],
            )
            .await
            .expect("tracked row should insert");
        let before_delete = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("commit should load");
        let [Value::Text(before_delete_id)] = before_delete.rows()[0].values() else {
            panic!("expected commit id");
        };
        session
            .execute("DELETE FROM lix_key_value WHERE key = 'deleted'", &[])
            .await
            .expect("tracked row should delete");
        session
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_untracked) \
             VALUES ('untracked', 'local', true)",
                &[],
            )
            .await
            .expect("untracked row should insert");

        let before = session
            .execute(
                "SELECT key FROM lix_as_of('lix_key_value', $1) WHERE key = 'deleted'",
                &[Value::Text(before_delete_id.clone())],
            )
            .await
            .expect("pre-deletion row should load");
        assert_eq!(before.rows().len(), 1);

        let head = session
            .execute(
                "SELECT key FROM lix_as_of('lix_key_value', lix_active_branch_commit_id()) \
             WHERE key IN ('deleted', 'untracked')",
                &[],
            )
            .await
            .expect("head state should load");
        assert!(head.rows().is_empty());
    }
);

simulation_test!(
    state_at_rejects_internal_relations_and_unknown_commits,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(
            engine.open_session().await.expect("session should open"),
            &engine,
        );

        let internal = session
            .execute(
                "SELECT * FROM lix_as_of('lix_file_descriptor', lix_active_branch_commit_id())",
                &[],
            )
            .await
            .expect_err("internal descriptor relation must be rejected");
        assert!(internal.message.contains("does not support relation"));

        let unknown = session
        .execute(
            "SELECT * FROM lix_as_of('lix_key_value', '0000000000000000000000000000000000000000000000000000000000000000')",
            &[],
        )
        .await
        .expect_err("unknown commit must fail");
        assert!(
            unknown.message.contains("commit") || unknown.message.contains("root"),
            "unknown commit should produce a commit/root error: {}",
            unknown.message
        );
    }
);

simulation_test!(
    state_at_branch_scope_is_session_independent,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let local = sim.wrap_session(
            engine
                .open_session()
                .await
                .expect("local session should open"),
            &engine,
        );
        let global = sim.wrap_session(
            engine
                .open_session_at(lix::GLOBAL_BRANCH_ID)
                .await
                .expect("global session should open"),
            &engine,
        );
        let global_before = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("global parent commit should load");
        let [Value::Text(global_before_id)] = global_before.rows()[0].values() else {
            panic!("expected global parent commit id");
        };

        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) \
             VALUES ('composed', 'global-value', true)",
                &[],
            )
            .await
            .expect("global row should insert");
        let global_commit = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("global commit should load");
        let [Value::Text(global_commit_id)] = global_commit.rows()[0].values() else {
            panic!("expected global commit id");
        };

        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('composed', 'local-value')",
                &[],
            )
            .await
            .expect("local override should insert");
        let local_commit = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("local commit should load");
        let [Value::Text(local_commit_id)] = local_commit.rows()[0].values() else {
            panic!("expected local commit id");
        };

        let global_state = local
            .execute(
                "SELECT value, lixcol_global \
             FROM lix_as_of('lix_key_value', $1) \
             WHERE key = 'composed'",
                &[Value::Text(global_commit_id.clone())],
            )
            .await
            .expect("global branch state should load from a local session");
        assert_rows_eq(
            global_state,
            vec![vec![
                Value::Jsonb(json!("global-value").into()),
                Value::Boolean(true),
            ]],
        );
        let global_diff = local
            .execute(
                "SELECT to_lixcol_global \
             FROM lix_diff('lix_key_value', $1, $2) \
             WHERE key = 'composed'",
                &[
                    Value::Text(global_before_id.clone()),
                    Value::Text(global_commit_id.clone()),
                ],
            )
            .await
            .expect("global diff metadata should load");
        assert_rows_eq(global_diff, vec![vec![Value::Boolean(true)]]);

        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) \
             VALUES ('later-global', 'later', true)",
                &[],
            )
            .await
            .expect("global head should advance");
        let pinned_again = local
            .execute(
                "SELECT lixcol_global FROM lix_as_of('lix_key_value', $1) \
             WHERE key = 'composed'",
                &[Value::Text(global_commit_id.clone())],
            )
            .await
            .expect("pinned global metadata should remain immutable");
        assert_rows_eq(pinned_again, vec![vec![Value::Boolean(true)]]);

        let local_state = global
            .execute(
                "SELECT value, lixcol_global \
             FROM lix_as_of('lix_key_value', $1) \
             WHERE key = 'composed'",
                &[Value::Text(local_commit_id.clone())],
            )
            .await
            .expect("local branch state should load from a global session");
        assert_rows_eq(
            local_state,
            vec![vec![
                Value::Jsonb(json!("local-value").into()),
                Value::Boolean(false),
            ]],
        );

        let live = local
            .execute(
                "SELECT value FROM lix_key_value WHERE key = 'composed'",
                &[],
            )
            .await
            .expect("composed live view should load");
        assert_rows_eq(live, vec![vec![Value::Jsonb(json!("local-value").into())]]);
    }
);

simulation_test!(
    state_at_branch_scopes_compose_with_local_shadow_history,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let local = sim.wrap_session(
            engine
                .open_session()
                .await
                .expect("local session should open"),
            &engine,
        );
        let global = sim.wrap_session(
            engine
                .open_session_at(lix::GLOBAL_BRANCH_ID)
                .await
                .expect("global session should open"),
            &engine,
        );

        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) VALUES \
             ('global-only', 'global-only-value', true), \
             ('overridden', 'global-old-value', true), \
             ('suppressed', 'global-suppressed-value', true)",
                &[],
            )
            .await
            .expect("global rows should insert");
        let global_commit = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("global commit should load");
        let [Value::Text(global_commit_id)] = global_commit.rows()[0].values() else {
            panic!("expected global commit id");
        };

        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES \
             ('overridden', 'local-value'), ('suppressed', 'local-before-delete')",
                &[],
            )
            .await
            .expect("local override should insert");
        local
            .execute("DELETE FROM lix_key_value WHERE key = 'suppressed'", &[])
            .await
            .expect("local tombstone should suppress the global row");
        let local_commit = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("local commit should load");
        let [Value::Text(local_commit_id)] = local_commit.rows()[0].values() else {
            panic!("expected local commit id");
        };

        let local_base = local
            .execute(
                "SELECT base_commit_id FROM lix_commit WHERE id = $1",
                &[Value::Text(local_commit_id.clone())],
            )
            .await
            .expect("local base should load");
        assert_rows_eq(
            local_base,
            vec![vec![Value::Text(global_commit_id.clone())]],
        );
        let complete_local_state = local
            .execute(
                "SELECT key, value, lixcol_global \
             FROM lix_as_of('lix_key_value', $1) \
             WHERE key IN ('global-only', 'overridden', 'suppressed') ORDER BY key",
                &[Value::Text(local_commit_id.clone())],
            )
            .await
            .expect("one local commit id should resolve the complete effective state");
        assert_rows_eq(
            complete_local_state,
            vec![
                vec![
                    Value::Text("global-only".into()),
                    Value::Jsonb(json!("global-only-value").into()),
                    Value::Boolean(true),
                ],
                vec![
                    Value::Text("overridden".into()),
                    Value::Jsonb(json!("local-value").into()),
                    Value::Boolean(false),
                ],
            ],
        );
        let global_history = local
            .execute(
                "SELECT key FROM lix_history('lix_key_value', $1) \
             WHERE key = 'global-only' LIMIT 1",
                &[Value::Text(local_commit_id.clone())],
            )
            .await
            .expect("history should report inherited state when the mainline adopts it");
        assert_rows_eq(
            global_history,
            vec![vec![Value::Text("global-only".into())]],
        );
        let ancestry = local
            .execute(
                "SELECT commit_id FROM lix_commit_ancestry($1) WHERE commit_id = $2",
                &[
                    Value::Text(local_commit_id.clone()),
                    Value::Text(global_commit_id.clone()),
                ],
            )
            .await
            .expect("ancestry should remain chronology-only");
        assert!(
            ancestry.rows().is_empty(),
            "base_commit_id is a state dependency, not a merge/ancestry parent"
        );

        let expected = vec![
            vec![
                Value::Text("global-only".into()),
                Value::Jsonb(json!("global-only-value").into()),
            ],
            vec![
                Value::Text("overridden".into()),
                Value::Jsonb(json!("local-value").into()),
            ],
        ];

        global
            .execute(
                "UPDATE lix_key_value SET value = 'global-new-value' \
             WHERE key = 'overridden'",
                &[],
            )
            .await
            .expect("global head should advance");
        global
            .execute(
                "UPDATE lix_key_value SET value = 'global-new-suppressed-value' \
             WHERE key = 'suppressed'",
                &[],
            )
            .await
            .expect("global suppressed row should advance");
        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) \
             VALUES ('later-global', 'later', true)",
                &[],
            )
            .await
            .expect("a later global row should insert");
        let latest_global = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("latest global commit should load");
        let [Value::Text(latest_global_id)] = latest_global.rows()[0].values() else {
            panic!("expected latest global commit id");
        };

        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-after-global', 'local')",
                &[],
            )
            .await
            .expect("the next local commit should fold in the latest global base");

        let live = local
            .execute(
                "SELECT key, value FROM lix_key_value \
             WHERE key IN ('global-only', 'later-global', 'overridden', 'suppressed') ORDER BY key",
                &[],
            )
            .await
            .expect("live composed view should load");
        let mut latest_expected = expected;
        latest_expected.insert(
            1,
            vec![
                Value::Text("later-global".into()),
                Value::Jsonb(json!("later").into()),
            ],
        );
        assert_rows_eq(live, latest_expected.clone());

        let refreshed_head = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("refreshed local head should load");
        let [Value::Text(refreshed_head_id)] = refreshed_head.rows()[0].values() else {
            panic!("expected refreshed local head id");
        };
        assert_ne!(refreshed_head_id, local_commit_id);
        let effective_diff = local
            .execute(
                "SELECT key, diff_type, to_lixcol_global \
             FROM lix_diff('lix_key_value', $1, $2) \
             WHERE key IN \
                 ('global-only', 'later-global', 'overridden', 'suppressed') \
             ORDER BY key",
                &[
                    Value::Text(local_commit_id.clone()),
                    Value::Text(refreshed_head_id.clone()),
                ],
            )
            .await
            .expect("effective diff should include only visible base changes");
        assert_rows_eq(
            effective_diff,
            vec![vec![
                Value::Text("later-global".into()),
                Value::Text("added".into()),
                Value::Boolean(true),
            ]],
        );
        let refreshed_base = local
            .execute(
                "SELECT base_commit_id FROM lix_commit WHERE id = $1",
                &[Value::Text(refreshed_head_id.clone())],
            )
            .await
            .expect("refreshed base should load");
        assert_rows_eq(
            refreshed_base,
            vec![vec![Value::Text(latest_global_id.clone())]],
        );
        let refreshed_state = local
            .execute(
                "SELECT key, value FROM lix_as_of('lix_key_value', $1) \
             WHERE key IN ('global-only', 'later-global', 'overridden', 'suppressed') ORDER BY key",
                &[Value::Text(refreshed_head_id.clone())],
            )
            .await
            .expect("refreshed commit should be a complete state handle");
        assert_rows_eq(refreshed_state, latest_expected);
    }
);

simulation_test!(
    local_overlay_does_not_inherit_a_global_causal_parent,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let main = sim.wrap_session(
            engine
                .open_session()
                .await
                .expect("main session should open"),
            &engine,
        );
        let global = sim.wrap_session(
            engine
                .open_session_at(lix::GLOBAL_BRANCH_ID)
                .await
                .expect("global session should open"),
            &engine,
        );
        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) \
             VALUES ('branch-base', 'v1', true)",
                &[],
            )
            .await
            .expect("global base row should insert");
        let g1 = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("global head should load");
        let [Value::Text(g1)] = g1.rows()[0].values() else {
            panic!("expected global commit id");
        };
        let branch_id = "73716c2d-6272-816e-8368-2d6f76657200";
        main.execute(
            "INSERT INTO lix_branch (id, name, commit_id) VALUES ($1, 'Overlay', $2)",
            &[Value::Text(branch_id.into()), Value::Text(g1.clone())],
        )
        .await
        .expect("branch should start at the global commit");
        let local = sim.wrap_session(
            engine
                .open_session_at(branch_id)
                .await
                .expect("local branch session should open"),
            &engine,
        );
        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-one', 'one')",
                &[],
            )
            .await
            .expect("first local overlay row should insert");
        global
            .execute(
                "UPDATE lix_key_value SET value = 'v2' WHERE key = 'branch-base'",
                &[],
            )
            .await
            .expect("global row should advance");
        let g2 = global
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("advanced global head should load");
        let [Value::Text(g2)] = g2.rows()[0].values() else {
            panic!("expected global commit id");
        };
        let live_after_global = local
            .execute(
                "SELECT value FROM lix_key_value WHERE key = 'branch-base'",
                &[],
            )
            .await
            .expect("live read should lazily refresh the composite handle");
        assert_rows_eq(
            live_after_global,
            vec![vec![Value::Jsonb(json!("v2").into())]],
        );
        let refreshed = local
            .execute(
                "SELECT base_commit_id FROM lix_commit WHERE id = lix_active_branch_commit_id()",
                &[],
            )
            .await
            .expect("refreshed base should load");
        assert_rows_eq(refreshed, vec![vec![Value::Text(g2.clone())]]);
        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-two', 'two')",
                &[],
            )
            .await
            .expect("second local overlay row should insert");
        let head = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("local head should load");
        let [Value::Text(head)] = head.rows()[0].values() else {
            panic!("expected local commit id");
        };
        let historical = local
            .execute(
                "SELECT key, value FROM lix_as_of('lix_key_value', $1) \
             WHERE key IN ('branch-base', 'local-one', 'local-two') ORDER BY key",
                &[Value::Text(head.clone())],
            )
            .await
            .expect("composite state should load");
        assert_rows_eq(
            historical,
            vec![
                vec![
                    Value::Text("branch-base".into()),
                    Value::Jsonb(json!("v2").into()),
                ],
                vec![
                    Value::Text("local-one".into()),
                    Value::Jsonb(json!("one").into()),
                ],
                vec![
                    Value::Text("local-two".into()),
                    Value::Jsonb(json!("two").into()),
                ],
            ],
        );
    }
);

simulation_test!(
    local_collection_replacement_fences_the_global_base,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let local = sim.wrap_session(
            engine
                .open_session()
                .await
                .expect("local session should open"),
            &engine,
        );
        let global = sim.wrap_session(
            engine
                .open_session_at(lix::GLOBAL_BRANCH_ID)
                .await
                .expect("global session should open"),
            &engine,
        );
        global
            .execute(
                "INSERT INTO lix_key_value (key, value, lixcol_global) VALUES \
             ('retired-global', 'v1', true), ('also-retired', 'v1', true)",
                &[],
            )
            .await
            .expect("global rows should insert");
        local
            .execute("DELETE FROM lix_key_value", &[])
            .await
            .expect("local collection should be replaced with empty state");
        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-survivor', 'local')",
                &[],
            )
            .await
            .expect("sparse local replacement member should insert");
        let before = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("replacement commit should load");
        let [Value::Text(before)] = before.rows()[0].values() else {
            panic!("expected local commit id");
        };
        global
            .execute(
                "UPDATE lix_key_value SET value = 'v2' WHERE key = 'retired-global'",
                &[],
            )
            .await
            .expect("retired global row should advance");
        local
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-after-base', 'later')",
                &[],
            )
            .await
            .expect("local head should pin the advanced base");
        let head = local
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .expect("local head should load");
        let [Value::Text(head)] = head.rows()[0].values() else {
            panic!("expected local commit id");
        };
        let state = local
            .execute(
                "SELECT key FROM lix_as_of('lix_key_value', $1) ORDER BY key",
                &[Value::Text(head.clone())],
            )
            .await
            .expect("replacement state should load");
        assert_rows_eq(
            state,
            vec![
                vec![Value::Text("local-after-base".into())],
                vec![Value::Text("local-survivor".into())],
            ],
        );
        let hidden_base_diff = local
            .execute(
                "SELECT key \
             FROM lix_diff('lix_key_value', $1, $2) \
             WHERE key = 'retired-global'",
                &[Value::Text(before.clone()), Value::Text(head.clone())],
            )
            .await
            .expect("effective diff should respect the replacement fence");
        assert!(hidden_base_diff.rows().is_empty());
    }
);

simulation_test!(
    state_at_preserves_absent_columns_before_schema_amendment,
    |sim| async move {
        let engine = sim.boot_engine().await;
        let session = sim.wrap_session(engine.open_session().await.unwrap(), &engine);
        let mut schema = json!({
            "$schema":"https://lix.dev/schema-v1.json", "key":"historical_amendment",
            "columns":[{"name":"id","type":"text","nullable":false},
                       {"name":"body","type":"text","nullable":false}],
            "primary_key":["id"]
        });
        session
            .execute(
                "INSERT INTO lix_registered_schema(value) VALUES ($1)",
                &[Value::Jsonb(schema.clone().into())],
            )
            .await
            .unwrap();
        session
            .execute(
                "INSERT INTO historical_amendment(id,body) VALUES ('old','before')",
                &[],
            )
            .await
            .unwrap();
        let before = session
            .execute("SELECT lix_active_branch_commit_id()", &[])
            .await
            .unwrap();
        let [Value::Text(before)] = before.rows()[0].values() else {
            panic!("commit")
        };
        schema["columns"].as_array_mut().unwrap().extend([
            json!({"name":"literal","type":"text","nullable":false,"default_value":"added"}),
            json!({"name":"optional","type":"int8","nullable":true}),
            json!({"name":"generated_id","type":"uuid","nullable":false,"default_expression":"uuidv7()"}),
            json!({"name":"generated_at","type":"timestamptz","nullable":false,"default_expression":"CURRENT_TIMESTAMP"}),
        ]);
        session
            .execute(
                "UPDATE lix_registered_schema SET value=$1 WHERE schema_key='historical_amendment'",
                &[Value::Jsonb(schema.into())],
            )
            .await
            .unwrap();
        let advertised = session.execute(
            "SELECT result_column, data_type, is_nullable FROM information_schema.table_functions \
             WHERE function_name = 'lix_as_of' AND source_relation = 'historical_amendment' \
             AND result_column IN ('id', 'body', 'literal', 'optional', 'generated_id', 'generated_at') \
             ORDER BY ordinal_position", &[]).await.unwrap();
        assert_rows_eq(
            advertised,
            vec![
                vec![
                    Value::Text("id".into()),
                    Value::Text("TEXT".into()),
                    Value::Text("NO".into()),
                ],
                vec![
                    Value::Text("body".into()),
                    Value::Text("TEXT".into()),
                    Value::Text("YES".into()),
                ],
                vec![
                    Value::Text("literal".into()),
                    Value::Text("TEXT".into()),
                    Value::Text("YES".into()),
                ],
                vec![
                    Value::Text("optional".into()),
                    Value::Text("BIGINT".into()),
                    Value::Text("YES".into()),
                ],
                vec![
                    Value::Text("generated_id".into()),
                    Value::Text("UUID".into()),
                    Value::Text("YES".into()),
                ],
                vec![
                    Value::Text("generated_at".into()),
                    Value::Text("TIMESTAMPTZ".into()),
                    Value::Text("YES".into()),
                ],
            ],
        );
        let current_contract = session
            .execute(
                "SELECT is_nullable FROM information_schema.columns \
             WHERE table_name = 'historical_amendment' AND column_name = 'literal'",
                &[],
            )
            .await
            .unwrap();
        assert_rows_eq(current_contract, vec![vec![Value::Text("NO".into())]]);
        for predicate in ["", " WHERE id='old'", " WHERE literal IS NULL"] {
            let rows = session.execute(&format!(
                "SELECT id, body, literal, optional, generated_id, generated_at FROM lix_as_of('historical_amendment', $1){predicate}"),
                &[Value::Text(before.clone())]).await.unwrap();
            assert_eq!(
                rows.rows()[0].values(),
                &[
                    Value::Text("old".into()),
                    Value::Text("before".into()),
                    Value::Null,
                    Value::Null,
                    Value::Null,
                    Value::Null
                ]
            );
            assert_eq!(rows.len(), 1);
        }
        let current = session
            .execute(
                "SELECT literal, optional FROM historical_amendment WHERE id='old'",
                &[],
            )
            .await
            .unwrap();
        assert_eq!(
            current.rows()[0].values(),
            &[Value::Text("added".into()), Value::Null]
        );
        let count = session
            .execute(
                "SELECT count(*) FROM lix_as_of('historical_amendment',$1)",
                &[Value::Text(before.clone())],
            )
            .await
            .unwrap();
        assert_eq!(count.rows()[0].values(), &[Value::Integer(1)]);
    }
);