hawdb 0.29.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
// 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
    };

    let incompatible = Database::open(&path).unwrap().commit_epoch().unwrap_err();
    assert!(incompatible
        .to_string()
        .contains("reopen requires OutOfCore residency with Authoritative relational indexes"));

    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());
}