alkgit-substrate 0.1.0

The shipped alkgit backend composition: the reactive alkstore + alkblobs backend implementing alkgit's backend seam — reactive halves, cached read provider, engine twins, migrations, GC wiring, and the LFS surface (ADR-019/025)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! The sqlite registry twin — the family adapter pattern's default
//! engine assembly (ADR-019 §3, substrate.md §registry: "one trait
//! pair, two implements — the sqlite adapter (`sqlite` feature,
//! `alkstore-sqlite` + the co-tenant rusqlite connection)").
//!
//! - [`SqliteRegistry`] — the durable write side ([`RegistryWrite`])
//!   over the co-tenant `git_repos` rows. Every mutation bumps the
//!   durable `registry_seq` singleton **inside the row-write
//!   transaction** (transactionally exact — the watermark's anchor,
//!   ADR-019 §5; failed mutations consume none, the tx rolls back
//!   whole), and the twins' row commits also carry the refs-table legs
//!   the composition owes: **put_repo seeds `HEAD → refs/heads/main`**
//!   (substrate.md §refs — git parity: `git init --bare` creates the
//!   dangling HEAD at init, not at first push; git's push grammar
//!   carries no HEAD. The dangling symref is exactly the unborn-HEAD
//!   shape `ls-refs=unborn` serves — the OQ-19 rider (a) fixture — and
//!   is CAS-unreachable from a push per git parity; the row is
//!   CAS-rewriteable, so the v1-pinned target is a two-way door, the
//!   constructor knob additive later) and **remove_repo removes the
//!   registry row, the repo's ref rows, and the repo's mutation-marker
//!   rows together** (backend.md — deletion is a GC consequence; objects
//!   stay for the sweep, no synchronous object deletion exists — the
//!   removal only touches co-tenant rows). Plus
//!   `SqliteRegistry::record_mutation` — the per-push mutation-marker
//!   write (ADR-019 §7, composition-internal: bumps the
//!   seq/watermark legs without touching the record; the receive-pack
//!   composition is the consumer).
//! - [`SqliteRegistryAssembly`] — the adapter constructor: one
//!   fallible assembly call (loud failure — ADR-024 §1) that opens the
//!   co-tenant connection ([`CoTenantSqlite::open`] — WAL, the pinned
//!   `busy_timeout` 5000 ms, the migrations run at construction) beside
//!   the engine on one file, opens the `alkstore-sqlite` engine, loads
//!   the cached read provider's initial snapshot, wires the reactive
//!   halves ([`Reactor`]) plus the announced write side
//!   ([`AnnouncingRegistry`]) and the refs twin, and hands back the
//!   pieces. The wave-8 single composition entry unifies construction;
//!   this is the per-piece constructor (the recorded interpretation).
//!   Post-commit announce (publish + notify + enqueue — each
//!   independent, fail-soft) is wired by default: mutations ride
//!   [`AnnouncingRegistry`], never a non-reactive shipped path
//!   (ADR-019 §5).
//!
//! # The sqlite asymmetry carried (substrate.md §the reactive halves)
//!
//! The co-tenant file is itself the invalidation bus: the watcher's
//! file-wide `data_version` bump fans a wake to listeners on *any*
//! commit to the file — including alkgit's own registry writes on
//! their own connection, including cross-process (~3.2 ms measured,
//! POC-R; the probe is test-pinned here). A lost hint cannot exist
//! while any write lands; the reconcile sweep is the correctness
//! backstop, not a latency bound. The post-commit notify leg stays
//! redundant but kept — for semantics and for postgres.
//!
//! Concurrency model: rusqlite is blocking — the trait methods bridge
//! their SQL off the async executor (`spawn_blocking`) under the
//! co-tenant handle's short-held lock, exactly the refs twin's shape;
//! the pinned busy timeout absorbs the cross-process write-lock waits.

use std::path::Path;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;

use alkgit::{RegistryError, RepoRecord};
use async_trait::async_trait;

use crate::error::OpenError;
use crate::migrations::CoTenantSqlite;
use crate::reactor::{AnnouncingRegistry, Reactor, RegistryEvent};
use crate::refs::{SqliteRefTable, VersionedRefTable};
use crate::registry::{
    row_to_record, validate_record, visibility_str, CachedRegistryProvider, RegistryBackend,
    RegistryRow, RegistryWrite,
};

/// The HEAD seed target moved engine-neutral ([`crate::registry`]) —
/// the sqlite twin re-exports it under its own name for the twin's
/// consumers.
pub use crate::registry::HEAD_SEED_TARGET;

/// The durable write side of the family pair over the co-tenant
/// `git_repos` rows (the pair's sqlite implement). Reads ride the
/// cached provider in the composed assemblies — the hot path never
/// touches this side except the refresh reads.
///
/// Mount over an already-migrated co-tenant handle (the refs twin's
/// shape — the same handle the composition opens once for both twins;
/// the migrations run at the handle's construction, loud, ADR-024 §1).
pub struct SqliteRegistry {
    handle: CoTenantSqlite,
}

impl SqliteRegistry {
    /// Mount the twin over a co-tenant handle.
    pub fn new(handle: CoTenantSqlite) -> Self {
        SqliteRegistry { handle }
    }

    /// The marker write's transaction rides its own `BEGIN IMMEDIATE`
    /// (`durable_record_mutation`): the marker row upserted with a
    /// `registry_seq` bump inside one transaction — the watermark's
    /// anchor moves on every push while the record row and its schema
    /// stay untouched (`rows_since` never carries markers; the seq is
    /// the reconcile watermark's currency). The record must exist (the
    /// receive flow resolved it) — a removed repo's marker is refused
    /// ([`RegistryError::NotFound`]). Consuming composition: the
    /// assembly's fused mutation legs ([`crate::pins::RegistryMutations`]
    /// — the receive flow's post-CAS legs), which announce the write
    /// post-commit.
    pub(crate) async fn record_mutation(&self, repo_id: &str) -> Result<i64, RegistryError> {
        let handle = self.handle.clone();
        let repo_id = repo_id.to_owned();
        blocking(move || durable_record_mutation(&handle, &repo_id)).await
    }
}

#[async_trait]
impl RegistryWrite for SqliteRegistry {
    async fn put(&self, record: &RepoRecord) -> Result<i64, RegistryError> {
        validate_record(record)?;
        let handle = self.handle.clone();
        let record = record.clone();
        blocking(move || durable_put(&handle, &record)).await
    }

    async fn update(&self, record: &RepoRecord) -> Result<i64, RegistryError> {
        validate_record(record)?;
        let handle = self.handle.clone();
        let record = record.clone();
        blocking(move || durable_update(&handle, &record)).await
    }

    async fn remove(&self, repo_id: &str) -> Result<i64, RegistryError> {
        let handle = self.handle.clone();
        let repo_id = repo_id.to_owned();
        blocking(move || durable_remove(&handle, &repo_id)).await
    }

    async fn watermark(&self) -> Result<i64, RegistryError> {
        let handle = self.handle.clone();
        blocking(move || durable_watermark(&handle)).await
    }

    async fn rows_since(&self, seq: i64) -> Result<Vec<RegistryRow>, RegistryError> {
        let handle = self.handle.clone();
        blocking(move || durable_rows_since(&handle, seq)).await
    }
}

/// The per-mutation blocking-task bridge — the trait methods move their
/// owned inputs into the spawn_blocking task; join failure is a
/// substrate failure (message-only, the family posture).
async fn blocking<R, T>(work: T) -> Result<R, RegistryError>
where
    T: FnOnce() -> Result<R, RegistryError> + Send + 'static,
    R: Send + 'static,
{
    tokio::task::spawn_blocking(work)
        .await
        .map_err(|e| RegistryError::Io(format!("registry blocking task: {e}")))?
}

fn io_err(context: &str, error: rusqlite::Error) -> RegistryError {
    RegistryError::Io(format!("{context}: {error}"))
}

/// The `put`'s transaction: the existence check first (a taken id is
/// [`RegistryError::AlreadyExists`], no seq consumed), then the seq
/// bump, the record row, and the HEAD seed row — commit or roll back
/// whole.
fn durable_put(handle: &CoTenantSqlite, record: &RepoRecord) -> Result<i64, RegistryError> {
    let mut conn = handle.lock();
    let tx = conn
        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
        .map_err(|e| io_err("registry put BEGIN IMMEDIATE", e))?;
    let taken: i64 = tx
        .query_row(
            "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
            rusqlite::params![record.repo_id],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry put existence read", e))?;
    if taken > 0 {
        return Err(RegistryError::AlreadyExists);
    }
    let grants = serde_json::to_string(&record.grants).map_err(|_| RegistryError::Invalid)?;
    let seq: i64 = tx
        .query_row(
            "UPDATE registry_seq SET value = value + 1 WHERE id = 1 RETURNING value",
            [],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry put seq bump", e))?;
    tx.execute(
        "INSERT INTO git_repos (repo_id, visibility, grants, seq) VALUES (?1, ?2, ?3, ?4)",
        rusqlite::params![
            record.repo_id,
            visibility_str(record.visibility),
            grants,
            seq
        ],
    )
    .map_err(|e| io_err("registry put record row", e))?;
    tx.execute(
        "INSERT INTO git_refs (repo_id, name, oid_hex, symref_target) \
         VALUES (?1, 'HEAD', NULL, ?2)",
        rusqlite::params![record.repo_id, HEAD_SEED_TARGET],
    )
    .map_err(|e| io_err("registry put HEAD seed", e))?;
    tx.commit().map_err(|e| io_err("registry put commit", e))?;
    Ok(seq)
}

/// The `update`'s transaction: existence first
/// ([`RegistryError::NotFound`]), the seq bump, the record row's
/// replace. The refs-table rows are untouched (HEAD belongs to the
/// record's creation).
fn durable_update(handle: &CoTenantSqlite, record: &RepoRecord) -> Result<i64, RegistryError> {
    let mut conn = handle.lock();
    let tx = conn
        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
        .map_err(|e| io_err("registry update BEGIN IMMEDIATE", e))?;
    let exists: i64 = tx
        .query_row(
            "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
            rusqlite::params![record.repo_id],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry update existence read", e))?;
    if exists == 0 {
        return Err(RegistryError::NotFound);
    }
    let grants = serde_json::to_string(&record.grants).map_err(|_| RegistryError::Invalid)?;
    let seq: i64 = tx
        .query_row(
            "UPDATE registry_seq SET value = value + 1 WHERE id = 1 RETURNING value",
            [],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry update seq bump", e))?;
    tx.execute(
        "UPDATE git_repos SET visibility = ?2, grants = ?3, seq = ?4 WHERE repo_id = ?1",
        rusqlite::params![
            record.repo_id,
            visibility_str(record.visibility),
            grants,
            seq
        ],
    )
    .map_err(|e| io_err("registry update record row", e))?;
    tx.commit()
        .map_err(|e| io_err("registry update commit", e))?;
    Ok(seq)
}

/// The `remove`'s transaction: existence first
/// ([`RegistryError::NotFound`]), the seq bump, then the record row,
/// the repo's ref rows (the HEAD seed included), the repo's
/// mutation-marker rows, and the repo's LFS liveness rows — the whole
/// repo's co-tenant state in one removal. The `lfs_objects` leg is
/// unconditional (the table ships unconditionally in the step set;
/// the rows only exist when the `lfs` surface wrote them, and a mixed
/// deployment that turned the feature off must not leak), followed by
/// the shared-oids' refcount recompute (`substrate/src/lfs.rs`'s
/// semantics — every surviving row of an oid reads the same count at
/// commit). Objects and packs are not touched (deletion is a GC
/// consequence).
fn durable_remove(handle: &CoTenantSqlite, repo_id: &str) -> Result<i64, RegistryError> {
    let mut conn = handle.lock();
    let tx = conn
        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
        .map_err(|e| io_err("registry remove BEGIN IMMEDIATE", e))?;
    let exists: i64 = tx
        .query_row(
            "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
            rusqlite::params![repo_id],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry remove existence read", e))?;
    if exists == 0 {
        return Err(RegistryError::NotFound);
    }
    let seq: i64 = tx
        .query_row(
            "UPDATE registry_seq SET value = value + 1 WHERE id = 1 RETURNING value",
            [],
            |r| r.get(0),
        )
        .map_err(|e| io_err("registry remove seq bump", e))?;
    tx.execute(
        "DELETE FROM git_repos WHERE repo_id = ?1",
        rusqlite::params![repo_id],
    )
    .map_err(|e| io_err("registry remove record row", e))?;
    tx.execute(
        "DELETE FROM git_refs WHERE repo_id = ?1",
        rusqlite::params![repo_id],
    )
    .map_err(|e| io_err("registry remove ref rows", e))?;
    tx.execute(
        "DELETE FROM repo_mutation_markers WHERE repo_id = ?1",
        rusqlite::params![repo_id],
    )
    .map_err(|e| io_err("registry remove marker rows", e))?;
    tx.execute(
        "DELETE FROM lfs_objects WHERE repo_id = ?1",
        rusqlite::params![repo_id],
    )
    .map_err(|e| io_err("registry remove lfs rows", e))?;
    tx.execute(
        "UPDATE lfs_objects \
         SET refcount = (SELECT count(*) FROM lfs_objects AS c WHERE c.oid = lfs_objects.oid)",
        [],
    )
    .map_err(|e| io_err("registry remove lfs recount", e))?;
    tx.commit()
        .map_err(|e| io_err("registry remove commit", e))?;
    Ok(seq)
}

fn durable_watermark(handle: &CoTenantSqlite) -> Result<i64, RegistryError> {
    let conn = handle.lock();
    conn.query_row("SELECT value FROM registry_seq WHERE id = 1", [], |r| {
        r.get(0)
    })
    .map_err(|e| io_err("registry watermark read", e))
}

fn durable_rows_since(
    handle: &CoTenantSqlite,
    seq: i64,
) -> Result<Vec<RegistryRow>, RegistryError> {
    let conn = handle.lock();
    let mut stmt = conn
        .prepare(
            "SELECT repo_id, visibility, grants, seq FROM git_repos \
             WHERE seq > ?1 ORDER BY seq",
        )
        .map_err(|e| io_err("registry rows_since prepare", e))?;
    let rows = stmt
        .query_map(rusqlite::params![seq], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, i64>(3)?,
            ))
        })
        .map_err(|e| io_err("registry rows_since query", e))?;
    let mut since = Vec::new();
    for row in rows {
        let (repo_id, visibility, grants, row_seq) =
            row.map_err(|e| io_err("registry rows_since row", e))?;
        since.push(row_to_record(&repo_id, &visibility, &grants, row_seq)?);
    }
    Ok(since)
}

/// The marker row upsert inside its one transaction: existence first
/// (the receive flow resolved the record), the seq bump, the marker
/// row.
fn durable_record_mutation(handle: &CoTenantSqlite, repo_id: &str) -> Result<i64, RegistryError> {
    let mut conn = handle.lock();
    let tx = conn
        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
        .map_err(|e| io_err("mutation marker BEGIN IMMEDIATE", e))?;
    let exists: i64 = tx
        .query_row(
            "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
            rusqlite::params![repo_id],
            |r| r.get(0),
        )
        .map_err(|e| io_err("mutation marker existence read", e))?;
    if exists == 0 {
        return Err(RegistryError::NotFound);
    }
    let seq: i64 = tx
        .query_row(
            "UPDATE registry_seq SET value = value + 1 WHERE id = 1 RETURNING value",
            [],
            |r| r.get(0),
        )
        .map_err(|e| io_err("mutation marker seq bump", e))?;
    tx.execute(
        "INSERT INTO repo_mutation_markers (repo_id, seq) VALUES (?1, ?2) \
         ON CONFLICT(repo_id) DO UPDATE SET seq = excluded.seq",
        rusqlite::params![repo_id, seq],
    )
    .map_err(|e| io_err("mutation marker row", e))?;
    tx.commit()
        .map_err(|e| io_err("mutation marker commit", e))?;
    Ok(seq)
}

/// The sqlite twin assembly — the pieces one adapter constructor wires
/// over the default engine assembly (single-host shape, substrate.md
/// §assembly: `alkstore-sqlite` + the co-tenant twin on one file):
///
/// - [`SqliteRegistryAssembly::store`] — the opened alkstore engine
///   handle (the reactive halves' substrate).
/// - [`SqliteRegistryAssembly::write`] — the **announced write side**
///   ([`AnnouncingRegistry`]): the pair with the post-commit announce
///   wired by default (ADR-019 §5 — no non-reactive shipped path).
/// - [`SqliteRegistryAssembly::durable`] — the bare twin (announce
///   free — the probe legs run here).
/// - [`SqliteRegistryAssembly::provider`] — the cached read provider,
///   loaded once from the durable side at construction (loud — a
///   registry serving an empty snapshot over a populated table would
///   contradict the definite-miss read contract).
/// - [`SqliteRegistryAssembly::reactor`] — the wake runner/stream
///   consumer/reconcile machinery, holding the durable side.
/// - [`SqliteRegistryAssembly::refs`] — the refs row CAS over the same
///   co-tenant handle, write-counter-wrapped ([`VersionedRefTable`];
///   the seeded HEAD row is its unborn shape) — the counter
///   [`SqliteRegistryAssembly::refs_version`] exposes is the liveness
///   source's arbitration-window signal.
/// - [`SqliteRegistryAssembly::backend`] — the core-traits binding
///   ([`RegistryBackend::with_cached_provider`]) over the announced
///   write side: the store methods announce post-commit and write
///   through.
/// - [`SqliteRegistryAssembly::lfs_rows`] — the LFS pointer-lifecycle
///   row CAS over the same co-tenant handle, write-counter-wrapped
///   ([`VersionedLfsRows`](crate::lfs::VersionedLfsRows) — the
///   refs-twins' wrap posture; the composition entry composes it
///   unchanged) — the counter [`SqliteRegistryAssembly::lfs_version`]
///   exposes is the LFS liveness source's arbitration-window signal.
///
/// The wave-8 single composition entry unifies construction; this is
/// the per-piece constructor (the recorded interpretation, flagged for
/// the gate).
pub struct SqliteRegistryAssembly {
    store: Arc<dyn alkstore::Store>,
    durable: Arc<SqliteRegistry>,
    registry: Arc<dyn RegistryWrite>,
    provider: Arc<CachedRegistryProvider>,
    reactor: Arc<Reactor>,
    refs: Arc<VersionedRefTable<SqliteRefTable>>,
    refs_version: Arc<AtomicU64>,
    backend: Arc<RegistryBackend>,
    #[cfg(feature = "lfs")]
    lfs: Arc<crate::lfs::VersionedLfsRows<crate::lfs::SqliteLfsRows>>,
    #[cfg(feature = "lfs")]
    lfs_version: Arc<AtomicU64>,
}

impl SqliteRegistryAssembly {
    /// The adapter constructor: open the co-tenant connection at
    /// `path` (migrations at construction, loud — a half-migrated
    /// store refuses service; `:memory:` confers no co-tenancy and is
    /// rejected before the engine opens), open the alkstore-sqlite
    /// engine at the same path, load the provider's initial snapshot,
    /// and wire the reactive composition. Every failure is
    /// [`OpenError`].
    pub async fn open(path: impl AsRef<Path>) -> Result<Self, OpenError> {
        let path = path.as_ref();
        let handle = CoTenantSqlite::open(path)?;
        let path_str = path.to_str().ok_or_else(|| {
            OpenError::Invalid(format!(
                "sqlite registry path is not valid utf-8: {}",
                path.display()
            ))
        })?;
        let store: Arc<dyn alkstore::Store> = Arc::from(
            alkstore_sqlite::open(path_str, Default::default()).map_err(|e| {
                OpenError::Engine(format!("alkstore-sqlite open ({}): {e}", path.display()))
            })?,
        );
        let durable: Arc<SqliteRegistry> = Arc::new(SqliteRegistry::new(handle));

        let provider = Arc::new(CachedRegistryProvider::new());
        let rows = durable
            .rows_since(0)
            .await
            .map_err(|e| OpenError::Engine(format!("cached provider initial load: {e}")))?;
        provider.install(rows);

        let durable_side: Arc<dyn RegistryWrite> = durable.clone();
        let reactor = Arc::new(Reactor::new(
            store.clone(),
            durable_side.clone(),
            provider.clone(),
        ));
        let registry: Arc<dyn RegistryWrite> = Arc::new(AnnouncingRegistry::new(
            durable_side.clone(),
            reactor.clone(),
        ));
        let backend = Arc::new(RegistryBackend::with_cached_provider(
            registry.clone(),
            provider.clone(),
        ));
        let refs_version = Arc::new(AtomicU64::new(0));
        let refs = Arc::new(VersionedRefTable::new(
            Arc::new(SqliteRefTable::new(durable.handle.clone())),
            refs_version.clone(),
        ));
        #[cfg(feature = "lfs")]
        let lfs_version = Arc::new(AtomicU64::new(0));
        #[cfg(feature = "lfs")]
        let lfs = Arc::new(crate::lfs::VersionedLfsRows::new(
            Arc::new(crate::lfs::SqliteLfsRows::new(durable.handle.clone())),
            lfs_version.clone(),
        ));
        Ok(SqliteRegistryAssembly {
            store,
            durable,
            registry,
            provider,
            reactor,
            refs,
            refs_version,
            backend,
            #[cfg(feature = "lfs")]
            lfs,
            #[cfg(feature = "lfs")]
            lfs_version,
        })
    }

    /// The opened alkstore engine handle (the reactive halves'
    /// substrate; the wave-7 maintenance chain rides the same).
    pub fn store(&self) -> &Arc<dyn alkstore::Store> {
        &self.store
    }

    /// The announced write side — the pair with the post-commit
    /// announce wired (the write surface the composition's callers
    /// use).
    pub fn write(&self) -> &Arc<dyn RegistryWrite> {
        &self.registry
    }

    /// The bare twin (announce-free — the transactional legs' probe
    /// surface).
    pub fn durable(&self) -> &Arc<SqliteRegistry> {
        &self.durable
    }

    /// The cached read provider (the hot read).
    pub fn provider(&self) -> &Arc<CachedRegistryProvider> {
        &self.provider
    }

    /// The reactor (the wake runner / stream consumer / reconcile
    /// sweep run through it).
    pub fn reactor(&self) -> &Arc<Reactor> {
        &self.reactor
    }

    /// The refs row CAS over the same co-tenant handle — the
    /// write-counter-wrapped composition refs ([`VersionedRefTable`]):
    /// the CAS semantics are unchanged (verbatim delegation), every
    /// CAS call bumps the shared counter the liveness source's
    /// arbitration consult reads (crate::liveness — the composition's
    /// invalidation half). Pushes route through this impl.
    pub fn refs(&self) -> &Arc<VersionedRefTable<SqliteRefTable>> {
        &self.refs
    }

    /// The refs writes' shared counter — the same handle
    /// [`Self::refs`] bumps and the [`crate::liveness::RefClosure`]
    /// source consults; hand it to the closure's constructor.
    pub fn refs_version(&self) -> &Arc<AtomicU64> {
        &self.refs_version
    }

    /// The core-traits binding (the engine-twin binding announced and
    /// write-through wired).
    pub fn backend(&self) -> &Arc<RegistryBackend> {
        &self.backend
    }

    /// The LFS pointer-lifecycle row CAS over the same co-tenant
    /// handle — the write-counter-wrapped rows
    /// ([`crate::lfs::VersionedLfsRows`]; the refs twins' wrap posture,
    /// the per-piece parity posture the per-piece-path embedder
    /// composes): the row semantics are unchanged (verbatim
    /// delegation), every `assert` bumps the shared counter the LFS
    /// liveness source's arbitration consult reads (`crate::liveness`
    /// — the composition's invalidation half). The record-removal leg
    /// takes a removed repo's rows with the record transactionally
    /// (the twins' unconditional in-SQL copy).
    #[cfg(feature = "lfs")]
    pub fn lfs_rows(&self) -> &Arc<crate::lfs::VersionedLfsRows<crate::lfs::SqliteLfsRows>> {
        &self.lfs
    }

    /// The LFS rows' asserts' shared counter — the same handle
    /// [`Self::lfs_rows`] bumps and the
    /// [`crate::liveness::LfsMedia`] source consults; hand it to the
    /// media source's constructor.
    #[cfg(feature = "lfs")]
    pub fn lfs_version(&self) -> &Arc<AtomicU64> {
        &self.lfs_version
    }
}

/// The per-push mutation-marker write, announced
/// ([`RegistryEvent::Mutation`] post-commit, fail-soft) — the receive
/// flow's watermark leg (ADR-019 §7; the composition-internal
/// [`RegistryMutations`](crate::pins::RegistryMutations) legs the
/// wrapped refs implement rides — [`crate::pins::CommittedRefs`]; the
/// record schema untouched). The durable leg carries no marker-driven
/// record change: `rows_since` never carries markers.
#[async_trait]
impl crate::pins::RegistryMutations for SqliteRegistryAssembly {
    async fn record_mutation(&self, repo_id: &str) -> Result<i64, RegistryError> {
        let seq = self.durable.record_mutation(repo_id).await?;
        self.reactor
            .announce(&RegistryEvent::Mutation {
                seq,
                repo_id: repo_id.to_owned(),
            })
            .await;
        Ok(seq)
    }
}

#[cfg(all(test, feature = "sqlite"))]
mod tests {
    use std::time::Duration;

    use crate::registry::RegistryRead;
    use crate::testutil::{
        private_record, record, spawn_wake_runner, stop_and_join, unique_db_path, wait_until,
    };

    use alkgit::{AccessAction, GitRefs, GitRegistry, GitRegistryStore, Visibility};
    use alkstore::{QueueOpts, StopToken, Store, StreamEvent, WakeReceiver};
    use serde_json::Value;

    use super::*;

    /// One co-tenant file with the twin mounted — the durable-side
    /// probe without the reactive wiring (the assembly is over it).
    async fn durable_twin(tag: &str) -> (CoTenantSqlite, SqliteRegistry) {
        let path = unique_db_path("sqlite", tag);
        let handle = CoTenantSqlite::open(&path).unwrap();
        let twin = SqliteRegistry::new(handle.clone());
        (handle, twin)
    }

    fn count(handle: &CoTenantSqlite, sql: &str, repo_id: &str) -> i64 {
        handle
            .lock()
            .query_row(sql, rusqlite::params![repo_id], |r| r.get(0))
            .unwrap()
    }

    #[tokio::test]
    async fn durable_twin_carries_the_family_write_semantics() {
        let (_, twin) = durable_twin("family").await;

        let seq_put = twin.put(&record("owner/r")).await.unwrap();
        assert_eq!(seq_put, 1, "first mutation carries seq 1");

        let mut granted = record("owner/r");
        granted.visibility = Visibility::Private;
        granted
            .grants
            .insert("u-7731".to_owned(), vec![AccessAction::Write]);
        let seq_update = twin.update(&granted).await.unwrap();
        assert_eq!(seq_update, 2);
        let rows = twin.rows_since(0).await.unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].seq, seq_update);
        assert_eq!(
            rows[0].record, granted,
            "the record round-trips the columns"
        );

        assert_eq!(twin.watermark().await.unwrap(), 2);
        let seq_remove = twin.remove("owner/r").await.unwrap();
        assert_eq!(seq_remove, 3);
        assert_eq!(twin.watermark().await.unwrap(), 3);
        assert!(
            twin.rows_since(0).await.unwrap().is_empty(),
            "the committed removal leaves no row"
        );
    }

    #[tokio::test]
    async fn durable_twin_error_map_matches_the_family() {
        let (_, twin) = durable_twin("errors").await;

        assert_eq!(
            twin.update(&record("ghost")).await.unwrap_err(),
            RegistryError::NotFound
        );
        assert_eq!(
            twin.remove("ghost").await.unwrap_err(),
            RegistryError::NotFound
        );
        assert_eq!(
            twin.record_mutation("ghost").await.unwrap_err(),
            RegistryError::NotFound,
            "a marker write is refused for a removed repo"
        );

        assert_eq!(twin.put(&record("owner/r")).await.unwrap(), 1);
        assert_eq!(
            twin.put(&record("owner/r")).await.unwrap_err(),
            RegistryError::AlreadyExists
        );
        assert_eq!(
            twin.watermark().await.unwrap(),
            1,
            "the failed duplicate put consumed no seq"
        );

        let malformed = record("Owner/name");
        assert_eq!(
            twin.put(&malformed).await.unwrap_err(),
            RegistryError::Invalid
        );
        let mut empty_key = record("empty");
        empty_key
            .grants
            .insert(String::new(), vec![AccessAction::Read]);
        assert_eq!(
            twin.put(&empty_key).await.unwrap_err(),
            RegistryError::Invalid
        );
        assert_eq!(
            twin.watermark().await.unwrap(),
            1,
            "the rejections consumed no seq"
        );
    }

    /// The seq is transactionally exact (the watermark's anchor,
    /// ADR-019 §5): the bump lives in the row-write transaction — a
    /// read on a second connection right after the commit sees the
    /// bumped seq and the row, before any announce could fire.
    #[tokio::test]
    async fn the_seq_bump_is_transactionally_exact() {
        let path = unique_db_path("sqlite", "tx-seq");
        let handle = CoTenantSqlite::open(&path).unwrap();
        let twin = SqliteRegistry::new(handle.clone());
        let second = CoTenantSqlite::open(&path).unwrap();

        let seq = twin.put(&record("owner/tx")).await.unwrap();

        {
            let db = second.lock();
            assert_eq!(
                db.query_row("SELECT value FROM registry_seq WHERE id = 1", [], |r| r
                    .get::<_, i64>(0))
                    .unwrap(),
                seq,
                "the second connection sees the bumped seq — it committed with the row"
            );
            assert_eq!(
                db.query_row(
                    "SELECT seq FROM git_repos WHERE repo_id = 'owner/tx'",
                    [],
                    |r| r.get::<_, i64>(0)
                )
                .unwrap(),
                seq,
            );
            assert_eq!(
                db.query_row(
                    "SELECT symref_target FROM git_refs WHERE repo_id = 'owner/tx' AND name = 'HEAD'",
                    [],
                    |r| r.get::<_, String>(0)
                )
                .unwrap(),
                HEAD_SEED_TARGET,
                "the refs-table leg rode the same transaction"
            );
        }

        twin.update(&private_record("owner/tx")).await.unwrap();
        twin.remove("owner/tx").await.unwrap();

        {
            let db = second.lock();
            assert_eq!(
                db.query_row("SELECT value FROM registry_seq WHERE id = 1", [], |r| r
                    .get::<_, i64>(0))
                    .unwrap(),
                3,
            );
        }

        let reopened = CoTenantSqlite::open(&path).unwrap();
        let fresh = SqliteRegistry::new(reopened);
        assert_eq!(
            fresh.watermark().await.unwrap(),
            3,
            "the seq singleton is durable"
        );
        assert!(
            fresh.put(&record("owner/tx")).await.unwrap() > 3,
            "the bump continues from the durable watermark"
        );
        drop(fresh);
        drop(handle);
        drop(second);
        let _ = std::fs::remove_file(&path);
    }

    /// put_repo seeds `HEAD → refs/heads/main` in the record
    /// transaction (substrate.md §refs): a fresh repo lists the unborn
    /// HEAD line via the refs twin; update leaves the row alone;
    /// remove clears it with the record.
    #[tokio::test]
    async fn put_repo_seeds_the_unborn_head_line() {
        let path = unique_db_path("sqlite", "seed-head");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
        let repo = record("owner/seeded");

        assembly.durable().put(&repo).await.unwrap();
        let listed = assembly.refs().list_refs(&repo).await.unwrap();
        assert_eq!(
            listed,
            vec![alkgit::RefLine {
                name: "HEAD".to_owned(),
                oid: None,
                peeled: None,
                symref_target: Some(HEAD_SEED_TARGET.to_owned()),
            }],
            "the fresh repo lists the unborn HEAD line (the OQ-19 rider (a) fixture)"
        );

        assembly
            .durable()
            .update(&private_record("owner/seeded"))
            .await
            .unwrap();
        assert_eq!(
            assembly.refs().list_refs(&repo).await.unwrap().len(),
            1,
            "the update's transaction does not touch the seeded row"
        );

        assembly.durable().remove("owner/seeded").await.unwrap();
        assert!(
            assembly.refs().list_refs(&repo).await.unwrap().is_empty(),
            "the removal cleared the seeded row with the record"
        );
    }

    /// remove_repo removes the registry row + the repo's ref rows +
    /// the repo's marker rows in the same removal (backend.md:
    /// deletion is a GC consequence — objects stay for the sweep; the
    /// only durable changes are the co-tenant rows).
    #[tokio::test]
    async fn remove_repo_drops_the_rows_the_removal_owes_together() {
        let path = unique_db_path("sqlite", "remove");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();

        assembly.durable().put(&record("survivor")).await.unwrap();
        assembly.durable().put(&record("victim")).await.unwrap();
        assembly.durable().record_mutation("victim").await.unwrap();
        assembly
            .refs()
            .apply_updates(
                &record("victim"),
                vec![alkgit::RefUpdate {
                    name: "refs/heads/main".to_owned(),
                    expected: None,
                    new: Some(gix_hash::ObjectId::from([7; 20])),
                }],
                false,
            )
            .await
            .unwrap();

        let engine_event = assembly
            .store()
            .stream(crate::reactor::EVENTS_STREAM)
            .await
            .unwrap()
            .publish(serde_json::json!("kept — no object deletion exists"))
            .await
            .unwrap();

        assembly.backend().remove_repo("victim").await.unwrap();

        let handle = CoTenantSqlite::open(&path).unwrap();
        assert_eq!(
            count(
                &handle,
                "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
                "victim"
            ),
            0
        );
        assert_eq!(
            count(
                &handle,
                "SELECT count(*) FROM git_refs WHERE repo_id = ?1",
                "victim"
            ),
            0
        );
        assert_eq!(
            count(
                &handle,
                "SELECT count(*) FROM repo_mutation_markers WHERE repo_id = ?1",
                "victim"
            ),
            0
        );
        assert_eq!(
            count(
                &handle,
                "SELECT count(*) FROM git_repos WHERE repo_id = ?1",
                "survivor"
            ),
            1
        );
        drop(handle);

        let events = assembly
            .store()
            .stream(crate::reactor::EVENTS_STREAM)
            .await
            .unwrap()
            .read_since(0, 100)
            .await
            .unwrap();
        assert!(
            events.iter().any(|event: &StreamEvent| {
                event.payload_as::<Value>().is_ok_and(|payload| {
                    payload == serde_json::json!("kept — no object deletion exists")
                })
            }),
            "the engine-side data is untouched by the removal"
        );
        assert!(engine_event > 0);
    }

    /// The LFS liveness rows go with the removed repo — the
    /// unconditional `lfs_objects` leg inside the record-removal
    /// transaction (the rows only exist when the `lfs` surface wrote
    /// them; the leg is unconditional so a mixed deployment that
    /// turned the feature off must not leak). The rows seed directly
    /// here (the leg's SQL is unconditional — the test holds with the
    /// surface off too), a shared oid's surviving row recomputes, and
    /// the victim's oids leave no row at all.
    #[tokio::test]
    async fn remove_repo_takes_the_lfs_rows_and_recounts_the_survivors() {
        let path = unique_db_path("sqlite", "remove-lfs");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
        assembly.durable().put(&record("victim")).await.unwrap();
        assembly.durable().put(&record("survivor")).await.unwrap();

        let shared_oid = "01".repeat(32);
        let victim_only_oid = "02".repeat(32);
        {
            let conn = assembly.durable().handle.lock();
            conn.execute(
                "INSERT INTO lfs_objects (repo_id, oid, size, refcount) \
                 VALUES ('victim', ?1, 8, 2), ('survivor', ?1, 8, 2), \
                         ('victim', ?2, 4, 1)",
                rusqlite::params![shared_oid, victim_only_oid],
            )
            .unwrap();
        }

        assembly.backend().remove_repo("victim").await.unwrap();

        {
            let conn = assembly.durable().handle.lock();
            let victim_only: i64 = conn
                .query_row(
                    "SELECT count(*) FROM lfs_objects WHERE oid = ?1",
                    rusqlite::params![victim_only_oid],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(victim_only, 0, "the victim's own oid left no row at all");
            let shared_count: i64 = conn
                .query_row(
                    "SELECT refcount FROM lfs_objects WHERE repo_id = 'survivor' AND oid = ?1",
                    rusqlite::params![shared_oid],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(
                shared_count, 1,
                "the surviving row carries the recomputed count (the re-protection contract's data)"
            );
        }

        #[cfg(feature = "lfs")]
        assert_eq!(
            crate::lfs::LfsRows::repo_rows(assembly.lfs_rows().as_ref(), "survivor")
                .await
                .unwrap(),
            vec![crate::lfs::LfsRow {
                repo_id: "survivor".to_owned(),
                oid: shared_oid,
                size: 8,
                refcount: 1,
            }],
            "the surface reads back the same state (the composition's row store)"
        );
    }

    /// The per-push mutation-marker write: the seq/watermark legs move
    /// without touching the record (ADR-019 §7 — the receive flow's
    /// watermark leg; rows_since never carries markers).
    #[tokio::test]
    async fn record_mutation_bumps_the_watermark_without_touching_the_record() {
        let (handle, twin) = durable_twin("marker").await;

        let put_seq = twin.put(&record("owner/m")).await.unwrap();
        assert_eq!(put_seq, 1);
        let seq = twin.record_mutation("owner/m").await.unwrap();

        assert_eq!(seq, 2);
        assert_eq!(twin.watermark().await.unwrap(), 2);
        let rows = twin.rows_since(0).await.unwrap();
        assert_eq!(
            rows.iter().map(|row| row.seq).collect::<Vec<_>>(),
            vec![put_seq],
            "the marker left no record row — the record schema is untouched"
        );
        let marker: i64 = handle
            .lock()
            .query_row(
                "SELECT seq FROM repo_mutation_markers WHERE repo_id = 'owner/m'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(marker, seq, "the marker row carries its seq");

        twin.remove("owner/m").await.unwrap();
        let left: i64 = handle
            .lock()
            .query_row(
                "SELECT count(*) FROM repo_mutation_markers WHERE repo_id = 'owner/m'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(left, 0, "the removal took the repo's marker rows with it");
    }

    /// The announcement through the composed store binding fires
    /// post-commit: the Put event is keyed in the feed, the wake lands
    /// on a listener, the pack-housekeeping job is on the maintenance
    /// queue, and the resolve rides the write-through provider.
    #[tokio::test]
    async fn announced_store_binding_fires_the_composition_post_commit() {
        use crate::reactor::MaintenanceJob;
        use crate::reactor::{RegistryEvent, MAINTENANCE_QUEUE};

        let path = unique_db_path("sqlite", "announce");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
        let mut listener = assembly
            .store()
            .listen(crate::reactor::WAKE_CHANNEL)
            .await
            .unwrap();
        let mut granted = record("owner/a");
        granted
            .grants
            .insert("u-1".to_owned(), vec![AccessAction::Read]);

        assembly.backend().put_repo(&granted).await.unwrap();

        let events = assembly
            .store()
            .stream(crate::reactor::EVENTS_STREAM)
            .await
            .unwrap()
            .read_since(0, 10)
            .await
            .unwrap();
        assert_eq!(events.len(), 1, "one announced put = one feed event");
        assert_eq!(events[0].key.as_deref(), Some("owner/a"));
        assert_eq!(
            crate::reactor::RegistryEvent::decode_event(&events[0]),
            Some(RegistryEvent::Put {
                seq: 1,
                record: granted.clone(),
            })
        );
        let wake = listener
            .recv_timeout(Duration::from_secs(2))
            .await
            .unwrap()
            .expect("wake source open");
        assert_eq!(wake.channel, crate::reactor::WAKE_CHANNEL);

        let queue = assembly
            .store()
            .queue(MAINTENANCE_QUEUE, QueueOpts::default())
            .await
            .unwrap();
        let claimed = queue
            .claim_one("probe")
            .await
            .unwrap()
            .expect("the pack-housekeeping job");
        assert_eq!(
            claimed.job().payload_as::<MaintenanceJob>().unwrap(),
            MaintenanceJob::PackHousekeeping {
                repo_id: "owner/a".to_owned(),
            }
        );

        assert_eq!(
            assembly.backend().resolve("owner/a").await.unwrap(),
            granted,
            "the write-through provider serves the mutation"
        );

        assembly.backend().remove_repo("owner/a").await.unwrap();
        let events = assembly
            .store()
            .stream(crate::reactor::EVENTS_STREAM)
            .await
            .unwrap()
            .read_since(1, 10)
            .await
            .unwrap();
        assert_eq!(
            events.first().and_then(RegistryEvent::decode_event),
            Some(RegistryEvent::Removed {
                seq: 2,
                repo_id: "owner/a".to_owned(),
            })
        );
    }

    /// A store double with every announce leg's entry point failing
    /// (the rest rides the mem engine).
    struct LegsDeadStore {
        inner: Box<dyn Store>,
    }

    impl Store for LegsDeadStore {
        fn begin_tx(
            &self,
        ) -> alkstore::BoxedFuture<'_, alkstore::Result<Box<dyn alkstore::TxHandle + Send>>>
        {
            self.inner.begin_tx()
        }

        fn notify<'a>(
            &'a self,
            channel: &str,
            payload: Value,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<()>> {
            self.inner.notify(channel, payload)
        }

        fn listen<'a>(
            &'a self,
            channel: &str,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<Box<dyn WakeReceiver>>> {
            self.inner.listen(channel)
        }

        fn stream<'a>(
            &'a self,
            _name: &str,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<Box<dyn alkstore::StreamHandle>>> {
            Box::pin(async { Err(alkstore::Error::database("publish leg suppressed (probe)")) })
        }

        fn queue<'a>(
            &'a self,
            _name: &str,
            _opts: alkstore::QueueOpts,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<Box<dyn alkstore::Queue>>> {
            Box::pin(async { Err(alkstore::Error::database("enqueue leg suppressed (probe)")) })
        }

        fn outbox<'a>(
            &'a self,
            name: &str,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<Box<dyn alkstore::Outbox>>> {
            self.inner.outbox(name)
        }

        fn try_lock<'a>(
            &'a self,
            name: &str,
            owner: &str,
            ttl: i64,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<Option<Box<dyn alkstore::Lock>>>> {
            self.inner.try_lock(name, owner, ttl)
        }

        fn schedule<'a>(
            &'a self,
            name: &str,
            spec: &str,
            queue: &str,
            payload: Value,
            opts: alkstore::ScheduleOpts,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<alkstore::Schedule>> {
            self.inner.schedule(name, spec, queue, payload, opts)
        }

        fn unschedule<'a>(
            &'a self,
            name: &str,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<bool>> {
            self.inner.unschedule(name)
        }

        fn run_schedules<'a>(
            &'a self,
            stop: StopToken,
        ) -> alkstore::BoxedFuture<'a, alkstore::Result<()>> {
            self.inner.run_schedules(stop)
        }
    }

    /// The announce's legs are fail-soft and the write's seq is
    /// transactionally exact: every leg dead still lands the durable
    /// commit (a read between write and announce sees the bumped seq),
    /// and the reconcile sweep closes the window.
    #[tokio::test]
    async fn dead_announce_legs_fail_soft_and_the_seq_stays_exact() {
        let path = unique_db_path("sqlite", "fail-soft");
        let handle = CoTenantSqlite::open(&path).unwrap();
        let durable: Arc<dyn RegistryWrite> = Arc::new(SqliteRegistry::new(handle));
        let provider = Arc::new(CachedRegistryProvider::new());
        let reactor = Arc::new(Reactor::new(
            Arc::new(LegsDeadStore {
                inner: Box::new(alkstore_mem::MemStore::new()),
            }) as Arc<dyn Store>,
            durable.clone(),
            provider.clone(),
        ));
        let announced: Arc<dyn RegistryWrite> =
            Arc::new(AnnouncingRegistry::new(durable.clone(), reactor.clone()));
        let backend = RegistryBackend::with_cached_provider(announced.clone(), provider.clone());

        backend.put_repo(&record("owner/x")).await.unwrap();
        assert_eq!(
            durable.watermark().await.unwrap(),
            1,
            "the seq is transactionally exact — not announce-dependent"
        );
        assert_eq!(durable.rows_since(0).await.unwrap().len(), 1);
        assert_eq!(
            provider.resolve("owner/x"),
            Some(record("owner/x")),
            "the write-through install is separate machinery and still landed"
        );

        let stream = alkstore_sqlite::open(path.to_str().unwrap(), Default::default()).unwrap();
        let events: Vec<StreamEvent> = stream
            .stream(crate::reactor::EVENTS_STREAM)
            .await
            .unwrap()
            .read_since(0, 10)
            .await
            .unwrap();
        assert!(
            events.is_empty(),
            "the suppressed publish leg left no event — the crash window"
        );

        let applied = crate::reactor::AppliedWatermark::new();
        let caught = reactor.reconcile(&applied).await.unwrap();
        assert_eq!(caught.len(), 1, "the crash window closes in one pass");
        assert_eq!(provider.resolve("owner/x"), Some(record("owner/x")));
        drop(stream);
        drop(backend);
        drop(durable);
        drop(reactor);
        let _ = std::fs::remove_file(&path);
    }

    /// The co-tenant file is itself the invalidation bus (substrate.md
    /// §the reactive halves, POC-R's backstop): an unannounced
    /// registry write on its own connection wakes a listener on a
    /// second engine connection, and the wake runner's refresh
    /// surfaces the row in the provider — milliseconds, not the
    /// reconcile cadence.
    #[tokio::test]
    async fn the_co_tenant_file_is_the_invalidation_bus() {
        let path = unique_db_path("sqlite", "backstop");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
        let mut listener = assembly
            .store()
            .listen(crate::reactor::WAKE_CHANNEL)
            .await
            .unwrap();
        let (stop, runner) = spawn_wake_runner(assembly.reactor().clone());
        tokio::time::sleep(Duration::from_millis(200)).await;

        let seq = assembly
            .durable()
            .put(&private_record("owner/silent"))
            .await
            .unwrap();

        let wake = listener
            .recv_timeout(Duration::from_secs(2))
            .await
            .unwrap()
            .expect(
                "the file-wide data_version bump fans the wake cross-connection — \
                 no notify involved",
            );
        assert_eq!(wake.channel, crate::reactor::WAKE_CHANNEL);
        drop(listener);

        wait_until(|| assembly.provider().resolve("owner/silent").is_some()).await;
        assert_eq!(
            assembly.provider().resolve("owner/silent"),
            Some(private_record("owner/silent")),
            "the unannounced write surfaced through the wake-driven refresh"
        );
        assert!(assembly.provider().refresh_count() >= 1);

        assert_eq!(
            assembly.durable().watermark().await.unwrap(),
            seq,
            "the watermark advanced though nothing announced"
        );
        stop_and_join(stop, runner).await;
    }

    /// The assembly constructor is loud and loads the persisted
    /// registry: a reopened assembly resolves the stored record with
    /// no refresh, the seq singleton persists, and `:memory:` is
    /// rejected before the engine opens (DQ-7).
    #[tokio::test]
    async fn assembly_open_is_loud_and_loads_the_persisted_registry() {
        let path = unique_db_path("sqlite", "reopen");
        {
            let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
            assembly
                .backend()
                .put_repo(&private_record("owner/kept"))
                .await
                .unwrap();
            assert_eq!(assembly.durable().watermark().await.unwrap(), 1);
        }

        let reopened = SqliteRegistryAssembly::open(&path).await.unwrap();
        assert_eq!(
            reopened.backend().resolve("owner/kept").await.unwrap(),
            private_record("owner/kept"),
            "the initial snapshot load carried the persisted table"
        );
        assert_eq!(reopened.durable().watermark().await.unwrap(), 1);
        assert_eq!(reopened.provider().refresh_count(), 1, "load only");

        // the initial load is loud: a broken durable side refuses
        // assembly (the twin's reads fail as the provider load maps
        // into OpenError)

        assert!(matches!(
            SqliteRegistryAssembly::open(":memory:").await,
            Err(OpenError::Invalid(_))
        ));

        let _ = std::fs::remove_file(&path);
    }

    /// The corrupt row defenses: a row the composition did not write
    /// (malformed grants JSON) is structurally invalid row state —
    /// `RegistryError::Invalid` on the catch-up read, never a poison
    /// row wedging the reconcile.
    #[tokio::test]
    async fn corrupt_record_rows_map_registry_invalid() {
        let path = unique_db_path("sqlite", "corrupt");
        let handle = CoTenantSqlite::open(&path).unwrap();
        let twin = SqliteRegistry::new(handle.clone());
        twin.put(&record("owner/ok")).await.unwrap();
        handle
            .lock()
            .execute(
                "INSERT INTO git_repos (repo_id, visibility, grants, seq) \
             VALUES ('owner/bent', 'public', 'not-json', 2)",
                [],
            )
            .unwrap();

        let err = twin.rows_since(0).await.unwrap_err();
        assert_eq!(err, RegistryError::Invalid, "{err:?}");

        let _ = std::fs::remove_file(&path);
    }

    /// The core-traits error map through the assembled binding — the
    /// closed registry family set exactly as the mem binding's.
    #[tokio::test]
    async fn the_assembled_binding_matches_the_family_error_map() {
        let path = unique_db_path("sqlite", "binding");
        let assembly = SqliteRegistryAssembly::open(&path).await.unwrap();
        let backend = assembly.backend().clone();

        assert_eq!(
            backend.update_repo(&record("ghost")).await.unwrap_err(),
            RegistryError::NotFound
        );
        assert_eq!(
            backend.remove_repo("ghost").await.unwrap_err(),
            RegistryError::NotFound
        );
        backend.put_repo(&record("owner/b")).await.unwrap();
        assert_eq!(
            backend.put_repo(&record("owner/b")).await.unwrap_err(),
            RegistryError::AlreadyExists
        );
        let malformed = record("Bad/id");
        assert_eq!(
            backend.put_repo(&malformed).await.unwrap_err(),
            RegistryError::Invalid
        );

        backend.remove_repo("owner/b").await.unwrap();
        assert_eq!(
            backend.resolve("owner/b").await.unwrap_err(),
            RegistryError::NotFound,
            "the unknown ≡ unauthorized collapse is at resolve's caller"
        );
    }
}