hawdb 0.39.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;
use crate::{SystemSchemaMigration, SystemSchemaRegistry};

fn registry_v1() -> SystemSchemaRegistry {
    SystemSchemaRegistry::new(
        "nowledge.content_store",
        [SystemSchemaMigration::new(
            1,
            "create_documents",
            ["CREATE TABLE content_documents (id TEXT PRIMARY KEY, body TEXT NOT NULL)"],
        )],
    )
}

fn registry_v2() -> SystemSchemaRegistry {
    SystemSchemaRegistry::new(
        "nowledge.content_store",
        [
            SystemSchemaMigration::new(
                1,
                "create_documents",
                ["CREATE TABLE content_documents (id TEXT PRIMARY KEY, body TEXT NOT NULL)"],
            ),
            SystemSchemaMigration::new(
                2,
                "add_document_kind",
                ["ALTER TABLE content_documents ADD COLUMN kind TEXT NOT NULL DEFAULT 'text'"],
            ),
        ],
    )
}

const SYSTEM_SCHEMA_CRASH_CHILD_ENV: &str = "HAWDB_TEST_SYSTEM_SCHEMA_CRASH_CHILD";
const SYSTEM_SCHEMA_CRASH_PATH_ENV: &str = "HAWDB_TEST_SYSTEM_SCHEMA_CRASH_PATH";

#[test]
fn system_schema_upgrade_crash_child() {
    if std::env::var_os(SYSTEM_SCHEMA_CRASH_CHILD_ENV).is_none() {
        return;
    }
    let path = std::path::PathBuf::from(
        std::env::var_os(SYSTEM_SCHEMA_CRASH_PATH_ENV)
            .expect("system schema crash test database path"),
    );
    let point =
        std::env::var("HAWDB_TEST_PROCESS_CRASH_POINT").expect("system schema crash test point");
    let mut db = Database::open(&path).unwrap();
    db.apply_system_schema_registry(&registry_v2()).unwrap();
    panic!("system schema crash failpoint {point} did not terminate the child process");
}

#[test]
fn application_system_schema_upgrade_crash_recovers_a_consistent_registry_and_schema() {
    let stages = [
        ("before_wal_append", Some(1)),
        ("after_wal_append", None),
        ("after_wal_sync", Some(2)),
        ("during_checkpoint_publication", Some(2)),
        ("after_manifest_publication", Some(2)),
    ];

    for (stage, required_version) in stages {
        let path = unique_test_dir(&format!("system_schema_upgrade_crash_{stage}"));
        {
            let mut db = Database::open(&path).unwrap();
            db.apply_system_schema_registry(&registry_v1()).unwrap();
            db.query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'body')")
                .unwrap();
            db.checkpoint().unwrap();
        }

        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .arg("--exact")
            .arg("api::tests::system_schema_registry::system_schema_upgrade_crash_child")
            .arg("--nocapture")
            .env(SYSTEM_SCHEMA_CRASH_CHILD_ENV, "1")
            .env(SYSTEM_SCHEMA_CRASH_PATH_ENV, &path)
            .env("HAWDB_TEST_PROCESS_CRASH_POINT", stage)
            .status()
            .unwrap();
        assert_eq!(
            status.code(),
            Some(86),
            "child did not terminate at {stage}"
        );

        if stage == "after_wal_sync" {
            let mut read_only = Database::open_with_config(
                &path,
                DatabaseConfig {
                    read_only: true,
                    recovery_mode: crate::RecoveryMode::Strict,
                    ..DatabaseConfig::default()
                },
            )
            .unwrap();
            assert!(matches!(
                read_only
                    .runtime
                    .get()
                    .unwrap()
                    .store
                    .relational_row_page_recovery_status(),
                crate::RelationalRowPageRecoveryStatus::Unavailable {
                    recovered_commit_epoch: 4,
                    checkpoint_required: true,
                    ..
                }
            ));
            // Resident rows recovered from the WAL serve reads while the
            // schema checkpoint is pending (#1593).
            let rows = read_only
                .query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
                .unwrap();
            assert_eq!(rows.rows.len(), 1);
            assert_eq!(rows.rows[0]["kind"], Value::String("text".to_string()));
        }

        let mut reopened = Database::open(&path).unwrap();
        let mut versions = reopened
            .query_sql(
                "SELECT version FROM hawdb_schema_migrations WHERE owner = 'nowledge.content_store'",
            )
            .unwrap()
            .rows
            .into_iter()
            .map(|row| match row.get("version") {
                Some(Value::Int(version)) => *version,
                value => panic!("expected migration version after {stage}, got {value:?}"),
            })
            .collect::<Vec<_>>();
        versions.sort_unstable();
        let current_version = versions.last().copied().expect("application migration");
        if let Some(required_version) = required_version {
            assert_eq!(current_version, required_version, "recovery at {stage}");
        }

        let kind = reopened
            .query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
            .map(|output| output.rows[0]["kind"].clone());
        let registry = match current_version {
            1 => {
                assert_eq!(versions, vec![1]);
                assert!(kind.is_err(), "version 1 exposed the version 2 column");
                registry_v1()
            }
            2 => {
                assert_eq!(versions, vec![1, 2]);
                assert_eq!(kind.unwrap(), Value::String("text".to_string()));
                assert!(matches!(
                    reopened
                        .runtime
                        .get()
                        .unwrap()
                        .store
                        .relational_row_page_recovery_status(),
                    crate::RelationalRowPageRecoveryStatus::CheckpointReady {
                        source_commit_epoch: 4,
                        ..
                    }
                ));
                registry_v2()
            }
            version => panic!("unexpected recovered schema version {version} after {stage}"),
        };
        let epoch_before_validation = reopened.commit_epoch().unwrap();
        let validation = reopened.apply_system_schema_registry(&registry).unwrap();
        assert!(validation.applied_versions.is_empty());
        assert_eq!(reopened.commit_epoch().unwrap(), epoch_before_validation);

        drop(reopened);
        std::fs::remove_dir_all(path).unwrap();
    }
}

#[test]
fn engine_system_schema_bootstraps_during_persistent_open() {
    let path = unique_test_dir("engine_system_schema_bootstrap");
    let first_epoch = {
        let mut db = Database::open(&path).unwrap();
        let rows = db
            .query_sql("SELECT owner, version FROM hawdb_schema_migrations")
            .unwrap()
            .rows;
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["owner"], Value::String("hawdb.engine".to_string()));
        assert_eq!(rows[0]["version"], Value::Int(1));
        let changefeed = db.search_projection_changefeed_status().unwrap();
        assert_eq!(changefeed.retained_mutation_count, 0);
        assert_eq!(changefeed.required_projection_commit_epoch(), 0);
        assert_eq!(changefeed.projection_commit_lag_after(0), 0);
        let delta = db
            .build_search_projection_graph_delta_request_after(0, Some(1))
            .unwrap()
            .unwrap();
        assert!(delta.upsert_node_ids.is_empty());
        assert!(delta.delete_document_ids.is_empty());
        assert_eq!(delta.complete_through_graph_commit_epoch, Some(1));
        db.commit_epoch()
    };
    let reopened = Database::open(&path).unwrap();
    assert_eq!(reopened.commit_epoch(), first_epoch);
    drop(reopened);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn read_only_out_of_core_open_validates_system_schema_through_canonical_rows() {
    let path = unique_test_dir("read_only_out_of_core_system_schema");
    let body = "x".repeat(8 * 1024);
    {
        let mut db = Database::open_with_config(
            &path,
            DatabaseConfig {
                relational_index_mode: hawdb_storage::config::RelationalIndexMode::Shadow,
                ..DatabaseConfig::default()
            },
        )
        .unwrap();
        db.apply_system_schema_registry(&registry_v1()).unwrap();
        db.query_sql_with_params(
            "INSERT INTO content_documents (id, body) VALUES ($1, $2)",
            &[
                Value::String("doc-1".to_string()),
                Value::String(body.clone()),
            ],
        )
        .unwrap();
        db.checkpoint().unwrap();
    }

    let mut db = Database::open_with_config(
        &path,
        DatabaseConfig {
            read_only: true,
            recovery_mode: crate::RecoveryMode::Strict,
            storage_residency_mode: hawdb_storage::config::StorageResidencyMode::OutOfCore,
            relational_index_mode: hawdb_storage::config::RelationalIndexMode::Authoritative,
            ..DatabaseConfig::default()
        },
    )
    .unwrap();

    assert!(!db
        .runtime
        .get()
        .unwrap()
        .store
        .relational_state()
        .materialized_rows_resident());
    assert!(db
        .runtime
        .get()
        .unwrap()
        .store
        .relational_state()
        .canonical_row_metadata_only());
    assert_eq!(
        db.runtime
            .get()
            .unwrap()
            .store
            .relational_state()
            .overflow_segment_count(),
        0
    );
    assert!(
        db.storage_residency_report()
            .unwrap()
            .relational_rows
            .overflow_extent_count
            > 0
    );
    assert_eq!(
        db.query_sql("SELECT body FROM content_documents WHERE id = 'doc-1'")
            .unwrap()
            .rows[0]["body"],
        Value::String(body)
    );
    let validation = db.apply_system_schema_registry(&registry_v1()).unwrap();
    assert!(validation.applied_versions.is_empty());

    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn writable_metadata_only_transaction_checkpoints_rows_and_indexes() {
    let path = unique_test_dir("writable_metadata_only_transaction");
    let config = DatabaseConfig {
        storage_residency_mode: hawdb_storage::config::StorageResidencyMode::OutOfCore,
        relational_index_mode: hawdb_storage::config::RelationalIndexMode::Authoritative,
        ..DatabaseConfig::default()
    };
    {
        let mut db = Database::open_with_config(
            &path,
            DatabaseConfig {
                relational_index_mode: hawdb_storage::config::RelationalIndexMode::Shadow,
                ..DatabaseConfig::default()
            },
        )
        .unwrap();
        db.apply_system_schema_registry(&registry_v1()).unwrap();
        db.query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'base')")
            .unwrap();
        db.checkpoint().unwrap();
    }

    let committed_epoch = {
        let mut db = Database::open_with_config(&path, config.clone()).unwrap();
        assert!(db
            .runtime
            .get()
            .unwrap()
            .store
            .relational_state()
            .canonical_row_metadata_only());
        let mut transaction = db.begin_transaction().unwrap();
        transaction
            .query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-2', 'private')")
            .unwrap();
        let private = transaction
            .query_sql("SELECT body FROM content_documents WHERE id = 'doc-2'")
            .unwrap();
        assert_eq!(
            private.rows[0]["body"],
            Value::String("private".to_string())
        );
        let duplicate = transaction
            .query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-2', 'rejected')")
            .unwrap_err();
        assert!(
            duplicate.to_string().contains("duplicate primary key"),
            "unexpected duplicate-key error: {duplicate}"
        );
        let after_rejection = transaction
            .query_sql("SELECT body FROM content_documents WHERE id = 'doc-2'")
            .unwrap();
        assert_eq!(after_rejection.rows, private.rows);
        transaction.commit().unwrap();
        let committed_epoch = db.commit_epoch().unwrap();
        db.checkpoint().unwrap();
        committed_epoch
    };

    // Default residency rebuilds resident rows from the same row root (#1737).
    {
        let mut materialized = Database::open(&path).unwrap();
        assert_eq!(materialized.commit_epoch().unwrap(), committed_epoch);
        assert!(!materialized
            .runtime
            .get()
            .unwrap()
            .store
            .relational_state()
            .canonical_row_metadata_only());
        let rows = materialized
            .query_sql("SELECT id, body FROM content_documents ORDER BY id")
            .unwrap();
        assert_eq!(rows.rows.len(), 2);
        assert_eq!(rows.rows[1]["body"], Value::String("private".to_string()));
    }

    let mut reopened = Database::open_with_config(&path, config).unwrap();
    assert_eq!(reopened.commit_epoch().unwrap(), committed_epoch);
    assert!(reopened
        .runtime
        .get()
        .unwrap()
        .store
        .relational_state()
        .canonical_row_metadata_only());
    let rows = reopened
        .query_sql("SELECT id, body FROM content_documents ORDER BY id")
        .unwrap();
    assert_eq!(rows.rows.len(), 2);
    assert_eq!(rows.rows[0]["id"], Value::String("doc-1".to_string()));
    assert_eq!(rows.rows[1]["id"], Value::String("doc-2".to_string()));
    let validation = reopened
        .apply_system_schema_registry(&registry_v1())
        .unwrap();
    assert!(validation.applied_versions.is_empty());

    drop(reopened);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn application_system_schema_upgrades_and_reopens_idempotently() {
    let path = unique_test_dir("application_system_schema_upgrade");
    {
        let mut db = Database::open(&path).unwrap();
        let report = db.apply_system_schema_registry(&registry_v1()).unwrap();
        assert_eq!(report.previous_version, 0);
        assert_eq!(report.current_version, 1);
        assert_eq!(report.applied_versions, vec![1]);
        db.query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'body')")
            .unwrap();
    }
    {
        let mut db = Database::open(&path).unwrap();
        let report = db.apply_system_schema_registry(&registry_v2()).unwrap();
        assert_eq!(report.previous_version, 1);
        assert_eq!(report.current_version, 2);
        assert_eq!(report.applied_versions, vec![2]);
        assert_eq!(
            db.query_sql("SELECT id FROM content_documents WHERE id = 'doc-1'")
                .unwrap()
                .rows
                .len(),
            1
        );
        assert_eq!(
            db.query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
                .unwrap()
                .rows[0]["kind"],
            Value::String("text".to_string())
        );
    }
    {
        let mut db = Database::open(&path).unwrap();
        let report = db.apply_system_schema_registry(&registry_v2()).unwrap();
        assert_eq!(report.previous_version, 2);
        assert_eq!(report.current_version, 2);
        assert!(report.applied_versions.is_empty());
        assert_eq!(report.commit_epoch_before, report.commit_epoch_after);
        assert_eq!(
            db.query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
                .unwrap()
                .rows[0]["kind"],
            Value::String("text".to_string())
        );
    }
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn schema_upgrade_publishes_a_canonical_row_checkpoint_before_returning() {
    let path = unique_test_dir("application_schema_row_checkpoint");
    let mut db = Database::open(&path).unwrap();
    db.apply_system_schema_registry(&registry_v1()).unwrap();
    db.query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'body')")
        .unwrap();
    db.checkpoint().unwrap();
    let generation_before = db
        .storage_reclamation_watermark()
        .unwrap()
        .checkpoint_epoch
        .expect("checkpoint generation");

    let report = db.apply_system_schema_registry(&registry_v2()).unwrap();

    assert_eq!(report.applied_versions, vec![2]);
    assert!(
        db.storage_reclamation_watermark()
            .unwrap()
            .checkpoint_epoch
            .unwrap()
            > generation_before
    );
    assert!(matches!(
        db.runtime.get().unwrap().store.relational_row_page_recovery_status(),
        crate::RelationalRowPageRecoveryStatus::CheckpointReady {
            source_commit_epoch,
            ..
        } if *source_commit_epoch == db.commit_epoch().unwrap()
    ));
    assert_eq!(
        db.query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
            .unwrap()
            .rows[0]["kind"],
        Value::String("text".to_string())
    );

    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn application_system_schema_rejects_changed_applied_migration() {
    let path = unique_test_dir("application_system_schema_checksum_drift");
    {
        let mut db = Database::open(&path).unwrap();
        db.apply_system_schema_registry(&registry_v1()).unwrap();
    }
    let drifted = SystemSchemaRegistry::new(
        "nowledge.content_store",
        [SystemSchemaMigration::new(
            1,
            "create_documents",
            ["CREATE TABLE content_documents (id TEXT PRIMARY KEY, body BYTEA NOT NULL)"],
        )],
    );
    let mut db = Database::open(&path).unwrap();
    let error = db.apply_system_schema_registry(&drifted).unwrap_err();
    assert!(error.to_string().contains("checksum or identity drifted"));
    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn application_system_schema_rejects_a_database_from_a_newer_binary() {
    let path = unique_test_dir("application_system_schema_future_version");
    {
        let mut db = Database::open(&path).unwrap();
        db.apply_system_schema_registry(&registry_v2()).unwrap();
    }
    let mut db = Database::open(&path).unwrap();
    let error = db.apply_system_schema_registry(&registry_v1()).unwrap_err();
    assert!(error.to_string().contains("binary supports 1"));
    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn failed_application_system_schema_upgrade_does_not_publish_version() {
    let path = unique_test_dir("failed_application_system_schema_upgrade");
    {
        let mut db = Database::open(&path).unwrap();
        db.apply_system_schema_registry(&registry_v1()).unwrap();
    }
    let invalid_v2 = SystemSchemaRegistry::new(
        "nowledge.content_store",
        [
            registry_v1().migrations()[0].clone(),
            SystemSchemaMigration::new(
                2,
                "invalid_table",
                ["CREATE TABLE invalid_table (body TEXT PRIMARY KEY, other TEXT PRIMARY KEY)"],
            ),
        ],
    );
    {
        let mut db = Database::open(&path).unwrap();
        let error = db.apply_system_schema_registry(&invalid_v2).unwrap_err();
        assert!(error.to_string().contains("more than one primary key"));
    }
    {
        let mut db = Database::open(&path).unwrap();
        let report = db.apply_system_schema_registry(&registry_v1()).unwrap();
        assert_eq!(report.previous_version, 1);
        assert!(report.applied_versions.is_empty());
        assert!(db
            .query_sql("SELECT * FROM invalid_table")
            .unwrap_err()
            .to_string()
            .contains("unknown relational table"));
    }
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn read_only_database_rejects_pending_application_system_schema_upgrade() {
    let path = unique_test_dir("read_only_application_system_schema_upgrade");
    {
        let mut db = Database::open(&path).unwrap();
        db.apply_system_schema_registry(&registry_v1()).unwrap();
    }
    let mut db = Database::open_with_config(
        &path,
        DatabaseConfig {
            read_only: true,
            recovery_mode: crate::RecoveryMode::Strict,
            ..DatabaseConfig::default()
        },
    )
    .unwrap();
    let error = db.apply_system_schema_registry(&registry_v2()).unwrap_err();
    assert!(error.to_string().contains("database is read-only"));
    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn application_system_schema_requires_contiguous_versions() {
    let mut db = Database::new();
    let registry = SystemSchemaRegistry::new(
        "nowledge.content_store",
        [SystemSchemaMigration::new(
            2,
            "create_documents",
            ["CREATE TABLE content_documents (id TEXT PRIMARY KEY)"],
        )],
    );
    let error = db.apply_system_schema_registry(&registry).unwrap_err();
    assert!(error.to_string().contains("contiguous from version 1"));
    assert_eq!(db.commit_epoch().unwrap(), 0);
}

#[test]
fn application_sql_cannot_modify_system_schema_registry() {
    let mut db = Database::new();
    db.apply_system_schema_registry(&registry_v1()).unwrap();

    let direct_error = db
        .query_sql("DELETE FROM hawdb_schema_migrations WHERE owner = 'nowledge.content_store'")
        .unwrap_err();
    assert!(direct_error
        .to_string()
        .contains("read-only outside system schema upgrade"));

    let mut transaction = db.begin_transaction().unwrap();
    let transaction_error = transaction
        .query_sql(
            "UPDATE hawdb_schema_migrations SET version = 9 WHERE owner = 'nowledge.content_store'",
        )
        .unwrap_err();
    assert!(transaction_error
        .to_string()
        .contains("read-only outside system schema upgrade"));
    transaction.rollback();

    let rows = db
        .query_sql(
            "SELECT version FROM hawdb_schema_migrations WHERE owner = 'nowledge.content_store'",
        )
        .unwrap()
        .rows;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0]["version"], Value::Int(1));
}

#[test]
fn application_migration_cannot_modify_system_schema_registry() {
    let mut db = Database::new();
    db.apply_system_schema_registry(&registry_v1()).unwrap();
    let malicious = SystemSchemaRegistry::new(
        "nowledge.content_store",
        [
            registry_v1().migrations()[0].clone(),
            SystemSchemaMigration::new(
                2,
                "rewrite_engine_registry",
                ["UPDATE hawdb_schema_migrations SET version = 9 WHERE owner = 'hawdb.engine'"],
            ),
        ],
    );

    let error = db.apply_system_schema_registry(&malicious).unwrap_err();
    assert!(error
        .to_string()
        .contains("read-only outside system schema upgrade"));
    let report = db.apply_system_schema_registry(&registry_v1()).unwrap();
    assert_eq!(report.previous_version, 1);
    assert!(report.applied_versions.is_empty());
}

#[test]
fn application_cannot_claim_the_engine_system_schema_owner() {
    let mut db = Database::new();
    let registry = SystemSchemaRegistry::new(
        "hawdb.engine",
        [SystemSchemaMigration::new(
            1,
            "untrusted_engine_schema",
            ["CREATE TABLE untrusted (id TEXT PRIMARY KEY)"],
        )],
    );

    let error = db.apply_system_schema_registry(&registry).unwrap_err();
    assert!(error.to_string().contains("reserved by the engine"));
    assert_eq!(db.commit_epoch().unwrap(), 0);
}

#[test]
fn embedded_open_applies_application_schema_before_returning_the_store() {
    let path = unique_test_dir("embedded_application_schema_open");
    let options = crate::EmbeddedStoreOpenOptions::graph_only(
        path.clone(),
        crate::GraphMode::WritableCutover,
    )
    .with_system_schema_registry(registry_v1());

    let (mut store, report) = crate::EmbeddedStore::open_with_options(options).unwrap();
    assert!(report.graph_opened);
    assert_eq!(report.system_schema_upgrades.len(), 1);
    assert_eq!(
        report.system_schema_upgrades[0].owner,
        "nowledge.content_store"
    );
    assert_eq!(report.system_schema_upgrades[0].applied_versions, vec![1]);
    store
        .graph_mut()
        .database_mut()
        .query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'ready')")
        .unwrap();
    drop(store);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn embedded_open_rejects_duplicate_application_schema_owners_before_open() {
    let path = unique_test_dir("duplicate_application_schema_owner");
    let options = crate::EmbeddedStoreOpenOptions::graph_only(
        path.clone(),
        crate::GraphMode::WritableCutover,
    )
    .with_system_schema_registry(registry_v1())
    .with_system_schema_registry(registry_v1());

    let error = crate::EmbeddedStoreHandle::open_with_options(options).unwrap_err();
    assert!(error.to_string().contains("registered more than once"));
    assert!(!path.exists());
}

/// One registry per owner, each creating an empty table and an index on it,
/// like an embedding host's first-open schema set (#1942).
fn batch_registries(count: usize) -> Vec<SystemSchemaRegistry> {
    (0..count)
        .map(|ordinal| {
            SystemSchemaRegistry::new(
                format!("batch.owner{ordinal}"),
                [SystemSchemaMigration::new(
                    1,
                    "initial",
                    [
                        format!(
                            "CREATE TABLE batch_{ordinal} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, n BIGINT)"
                        ),
                        format!("CREATE INDEX batch_{ordinal}_kind ON batch_{ordinal} (kind)"),
                    ],
                )],
            )
        })
        .collect()
}

/// The canonical row-page generation. Every published checkpoint advances it
/// by the same step; tests measure that step with an explicit checkpoint.
fn checkpoint_generation(db: &Database) -> u64 {
    match db
        .runtime
        .get()
        .unwrap()
        .store
        .relational_row_page_recovery_status()
    {
        crate::RelationalRowPageRecoveryStatus::CheckpointReady { generation, .. } => *generation,
        crate::RelationalRowPageRecoveryStatus::LiveCurrent {
            base_generation, ..
        } => *base_generation,
        status => panic!("expected a current canonical row checkpoint, got {status:?}"),
    }
}

/// The generation advance of one published checkpoint.
fn checkpoint_step(db: &mut Database) -> u64 {
    let before = checkpoint_generation(db);
    db.checkpoint().unwrap();
    let step = checkpoint_generation(db) - before;
    assert!(step > 0, "a checkpoint must publish a new generation");
    step
}

fn owner_versions(db: &mut Database, owner: &str) -> Vec<i64> {
    let mut versions = db
        .query_sql_with_params(
            "SELECT version FROM hawdb_schema_migrations WHERE owner = $1",
            &[Value::String(owner.to_string())],
        )
        .unwrap()
        .rows
        .into_iter()
        .map(|row| match row.get("version") {
            Some(Value::Int(version)) => *version,
            value => panic!("expected a migration version for {owner}, got {value:?}"),
        })
        .collect::<Vec<_>>();
    versions.sort_unstable();
    versions
}

fn kind_ids(db: &mut Database, table: &str, kind: &str) -> Vec<String> {
    let mut ids = db
        .query_sql_with_params(
            &format!("SELECT id FROM {table} WHERE kind = $1"),
            &[Value::String(kind.to_string())],
        )
        .unwrap()
        .rows
        .into_iter()
        .map(|row| match row.get("id") {
            Some(Value::String(id)) => id.clone(),
            value => panic!("expected an id in {table}, got {value:?}"),
        })
        .collect::<Vec<_>>();
    ids.sort_unstable();
    ids
}

#[test]
fn batched_system_schema_registries_publish_one_commit_and_one_checkpoint() {
    const REGISTRIES: usize = 6;
    let path = unique_test_dir("batched_system_schema_registries");
    let registries = batch_registries(REGISTRIES);
    {
        let mut db = Database::open(&path).unwrap();
        let step = checkpoint_step(&mut db);
        let generation_before = checkpoint_generation(&db);
        let epoch_before = db.commit_epoch().unwrap();

        let reports = db.apply_system_schema_registries(&registries).unwrap();

        // N new-table registries cost one WAL commit and one schema
        // checkpoint, not N of each.
        assert_eq!(db.commit_epoch().unwrap(), epoch_before + 1);
        assert_eq!(
            checkpoint_generation(&db),
            generation_before + step,
            "batched registries must publish exactly one checkpoint"
        );
        assert!(matches!(
            db.runtime.get().unwrap().store.relational_row_page_recovery_status(),
            crate::RelationalRowPageRecoveryStatus::CheckpointReady {
                source_commit_epoch,
                ..
            } if *source_commit_epoch == epoch_before + 1
        ));
        assert_eq!(reports.len(), REGISTRIES);
        for (ordinal, report) in reports.iter().enumerate() {
            assert_eq!(report.owner, format!("batch.owner{ordinal}"));
            assert_eq!(report.previous_version, 0);
            assert_eq!(report.current_version, 1);
            assert_eq!(report.applied_versions, vec![1]);
            assert_eq!(report.commit_epoch_before, epoch_before);
            assert_eq!(report.commit_epoch_after, epoch_before + 1);
        }

        for ordinal in 0..REGISTRIES {
            db.query_sql(&format!(
                "INSERT INTO batch_{ordinal} (id, kind, n) VALUES ('a', 'k', 1), ('b', 'other', 2), ('c', 'k', 3)"
            ))
            .unwrap();
            assert_eq!(
                kind_ids(&mut db, &format!("batch_{ordinal}"), "k"),
                vec!["a", "c"]
            );
        }

        // The same registries one owner at a time pay one checkpoint each.
        let generation = checkpoint_generation(&db);
        for registry in batch_registries(REGISTRIES + 2).iter().skip(REGISTRIES) {
            db.apply_system_schema_registry(registry).unwrap();
        }
        assert_eq!(checkpoint_generation(&db), generation + 2 * step);

        // A current batch neither commits nor checkpoints.
        let generation = checkpoint_generation(&db);
        let epoch = db.commit_epoch().unwrap();
        let reports = db.apply_system_schema_registries(&registries).unwrap();
        assert!(reports
            .iter()
            .all(|report| report.applied_versions.is_empty()
                && report.commit_epoch_before == report.commit_epoch_after));
        assert_eq!(db.commit_epoch().unwrap(), epoch);
        assert_eq!(checkpoint_generation(&db), generation);
    }
    {
        let mut db = Database::open(&path).unwrap();
        let epoch = db.commit_epoch().unwrap();
        let reports = db.apply_system_schema_registries(&registries).unwrap();
        assert!(reports
            .iter()
            .all(|report| report.applied_versions.is_empty()));
        assert_eq!(db.commit_epoch().unwrap(), epoch);
        for ordinal in 0..REGISTRIES {
            assert_eq!(
                kind_ids(&mut db, &format!("batch_{ordinal}"), "k"),
                vec!["a", "c"]
            );
        }
    }
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn batched_system_schema_registries_index_existing_rows_and_skip_current_owners() {
    let path = unique_test_dir("batched_system_schema_existing_rows");
    let mut db = Database::open(&path).unwrap();
    db.apply_system_schema_registry(&registry_v1()).unwrap();
    db.query_sql(
        "INSERT INTO content_documents (id, body) VALUES ('doc-1', 'x'), ('doc-2', 'y'), ('doc-3', 'x')",
    )
    .unwrap();
    let step = checkpoint_step(&mut db);
    let generation_before = checkpoint_generation(&db);
    let indexed_v2 = SystemSchemaRegistry::new(
        "nowledge.content_store",
        [
            registry_v1().migrations()[0].clone(),
            SystemSchemaMigration::new(
                2,
                "index_body",
                ["CREATE INDEX content_documents_body ON content_documents (body)"],
            ),
        ],
    );
    let mut registries = vec![indexed_v2];
    registries.extend(batch_registries(2));

    let reports = db.apply_system_schema_registries(&registries).unwrap();

    assert_eq!(reports[0].previous_version, 1);
    assert_eq!(reports[0].applied_versions, vec![2]);
    assert_eq!(reports[1].applied_versions, vec![1]);
    assert_eq!(reports[2].applied_versions, vec![1]);
    assert_eq!(checkpoint_generation(&db), generation_before + step);
    let mut ids = db
        .query_sql("SELECT id FROM content_documents WHERE body = 'x'")
        .unwrap()
        .rows
        .into_iter()
        .map(|row| row["id"].clone())
        .collect::<Vec<_>>();
    ids.sort_by_key(|value| format!("{value:?}"));
    assert_eq!(
        ids,
        vec![
            Value::String("doc-1".to_string()),
            Value::String("doc-3".to_string())
        ]
    );

    // A batch where one owner is current applies only the pending owner.
    let mut registries = batch_registries(3);
    registries.swap(0, 2);
    let epoch = db.commit_epoch().unwrap();
    let reports = db.apply_system_schema_registries(&registries).unwrap();
    assert_eq!(reports[0].owner, "batch.owner2");
    assert_eq!(reports[0].applied_versions, vec![1]);
    assert_eq!(reports[0].commit_epoch_after, epoch + 1);
    assert!(reports[1].applied_versions.is_empty());
    assert_eq!(reports[1].commit_epoch_after, epoch);
    assert!(reports[2].applied_versions.is_empty());
    assert_eq!(db.commit_epoch().unwrap(), epoch + 1);

    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn failed_batched_system_schema_registry_publishes_no_owner() {
    let path = unique_test_dir("failed_batched_system_schema_registries");
    let mut db = Database::open(&path).unwrap();
    let epoch = db.commit_epoch().unwrap();
    let mut registries = batch_registries(2);
    registries.push(SystemSchemaRegistry::new(
        "batch.invalid",
        [SystemSchemaMigration::new(
            1,
            "invalid_table",
            ["CREATE TABLE invalid_table (body TEXT PRIMARY KEY, other TEXT PRIMARY KEY)"],
        )],
    ));

    let error = db.apply_system_schema_registries(&registries).unwrap_err();

    assert!(error.to_string().contains("more than one primary key"));
    assert_eq!(db.commit_epoch().unwrap(), epoch);
    for owner in ["batch.owner0", "batch.owner1", "batch.invalid"] {
        assert!(owner_versions(&mut db, owner).is_empty(), "{owner}");
    }
    assert!(db.query_sql("SELECT * FROM batch_0").is_err());

    let duplicate = [registry_v1(), registry_v1()];
    assert!(db
        .apply_system_schema_registries(&duplicate)
        .unwrap_err()
        .to_string()
        .contains("registered more than once"));
    let engine_claim = [
        registry_v1(),
        SystemSchemaRegistry::new(
            "hawdb.engine",
            [SystemSchemaMigration::new(
                1,
                "claim",
                ["CREATE TABLE claimed (id TEXT PRIMARY KEY)"],
            )],
        ),
    ];
    assert!(db
        .apply_system_schema_registries(&engine_claim)
        .unwrap_err()
        .to_string()
        .contains("reserved by the engine"));
    assert_eq!(db.commit_epoch().unwrap(), epoch);
    assert!(owner_versions(&mut db, "nowledge.content_store").is_empty());

    drop(db);
    std::fs::remove_dir_all(path).unwrap();
}

#[test]
fn batched_system_schema_crash_child() {
    if std::env::var_os(SYSTEM_SCHEMA_CRASH_CHILD_ENV).is_none() {
        return;
    }
    let path = std::path::PathBuf::from(
        std::env::var_os(SYSTEM_SCHEMA_CRASH_PATH_ENV)
            .expect("batched system schema crash test database path"),
    );
    let point = std::env::var("HAWDB_TEST_PROCESS_CRASH_POINT")
        .expect("batched system schema crash test point");
    let mut db = Database::open(&path).unwrap();
    let mut registries = vec![registry_v2()];
    registries.extend(batch_registries(3));
    db.apply_system_schema_registries(&registries).unwrap();
    panic!("batched system schema crash failpoint {point} did not terminate the child process");
}

#[test]
fn batched_system_schema_crash_recovers_every_owner_or_none() {
    let stages = [
        ("before_wal_append", Some(false)),
        ("after_wal_append", None),
        ("after_wal_sync", Some(true)),
        ("during_checkpoint_publication", Some(true)),
        ("after_manifest_publication", Some(true)),
    ];

    for (stage, required_applied) in stages {
        let path = unique_test_dir(&format!("batched_system_schema_crash_{stage}"));
        {
            let mut db = Database::open(&path).unwrap();
            db.apply_system_schema_registry(&registry_v1()).unwrap();
            db.query_sql("INSERT INTO content_documents (id, body) VALUES ('doc-1', 'body')")
                .unwrap();
            db.checkpoint().unwrap();
        }

        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .arg("--exact")
            .arg("api::tests::system_schema_registry::batched_system_schema_crash_child")
            .arg("--nocapture")
            .env(SYSTEM_SCHEMA_CRASH_CHILD_ENV, "1")
            .env(SYSTEM_SCHEMA_CRASH_PATH_ENV, &path)
            .env("HAWDB_TEST_PROCESS_CRASH_POINT", stage)
            .status()
            .unwrap();
        assert_eq!(
            status.code(),
            Some(86),
            "child did not terminate at {stage}"
        );

        let mut reopened = Database::open(&path).unwrap();
        let content_versions = owner_versions(&mut reopened, "nowledge.content_store");
        let applied = content_versions == vec![1, 2];
        if let Some(required_applied) = required_applied {
            assert_eq!(applied, required_applied, "recovery at {stage}");
        }
        if !applied {
            assert_eq!(content_versions, vec![1], "recovery at {stage}");
        }
        for ordinal in 0..3 {
            let owner = format!("batch.owner{ordinal}");
            let table = format!("batch_{ordinal}");
            if applied {
                assert_eq!(owner_versions(&mut reopened, &owner), vec![1], "{stage}");
                // Recovered tables and indexes accept and serve new rows.
                reopened
                    .query_sql(&format!(
                        "INSERT INTO {table} (id, kind) VALUES ('after-{stage}', 'k')"
                    ))
                    .unwrap();
                assert_eq!(
                    kind_ids(&mut reopened, &table, "k"),
                    vec![format!("after-{stage}")]
                );
            } else {
                assert!(owner_versions(&mut reopened, &owner).is_empty(), "{stage}");
                assert!(reopened
                    .query_sql(&format!("SELECT * FROM {table}"))
                    .is_err());
            }
        }
        let kind = reopened
            .query_sql("SELECT kind FROM content_documents WHERE id = 'doc-1'")
            .map(|output| output.rows[0]["kind"].clone());
        if applied {
            assert_eq!(kind.unwrap(), Value::String("text".to_string()));
        } else {
            assert!(kind.is_err(), "version 1 exposed the version 2 column");
        }

        // Reapplying the whole batch completes an absent upgrade or is a
        // no-op, and rows inserted after recovery survive a reopen.
        let mut registries = vec![registry_v2()];
        registries.extend(batch_registries(3));
        reopened
            .apply_system_schema_registries(&registries)
            .unwrap();
        drop(reopened);
        let mut reopened = Database::open(&path).unwrap();
        let epoch = reopened.commit_epoch().unwrap();
        let reports = reopened
            .apply_system_schema_registries(&registries)
            .unwrap();
        assert!(reports
            .iter()
            .all(|report| report.applied_versions.is_empty()));
        assert_eq!(reopened.commit_epoch().unwrap(), epoch);
        if applied {
            assert_eq!(
                kind_ids(&mut reopened, "batch_0", "k"),
                vec![format!("after-{stage}")]
            );
        }

        drop(reopened);
        std::fs::remove_dir_all(path).unwrap();
    }
}