1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
//! collection index — tracks which collections exist per repo
//!
//! Two ordered namespaces in one atomic batch: rbc and cbr.
const std = @import("std");
const zkv = @import("zkv");
const zat = @import("zat");
const owner_mod = @import("batch_owner.zig");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const BackgroundWriter = struct {
inner: zkv.DirStore,
writes: usize = 0,
elapsed_ns: i96 = 0,
pub fn put(self: *BackgroundWriter, key: []const u8, bytes: []const u8) !void {
const started = Io.Clock.awake.now(self.inner.io).nanoseconds;
defer {
self.writes += 1;
self.elapsed_ns += Io.Clock.awake.now(self.inner.io).nanoseconds - started;
}
try self.inner.put(key, bytes);
}
};
const Store = zkv.AsyncStore(zkv.DirStore, BackgroundWriter);
const Db = zkv.Db(Store);
const ReaderStore = zkv.DirStoreWithHandles(32);
const ReadDb = zkv.Db(ReaderStore);
const log = std.log.scoped(.collection_index);
const separator = '\x00';
const rbc = "\x01";
const cbr = "\x02";
const IndexPair = struct { did: []const u8, collection: []const u8 };
const ResyncGuard = struct { did: [128]u8, len: usize, token: u64, changed: bool, destructive: bool };
const SnapshotResult = enum { replaced, merged, superseded };
const Mutation = union(enum) {
pair: struct { pair: IndexPair, delete: bool },
pairs: []const IndexPair,
page: struct { dids: []const []const u8, collection: []const u8, delete: bool = false },
replace: struct { did: []const u8, collections: []const []const u8 },
frame: struct { did: []const u8, ops: zat.cbor.Value },
guarded_replace: struct { did: []const u8, collections: []const []const u8, token: u64, applied: *SnapshotResult },
};
pub const CollectionIndex = struct {
const WriteOwner = owner_mod.OwnerWithMaintenance(@This(), Mutation, applyMutations, mayDelay, maintainAfterAck);
const PageQuery = struct {
collection: []const u8,
limit: usize,
cursor: ?[]const u8,
bytes: []u8,
offsets: []Span,
result: *ListResult,
};
const PageOwner = owner_mod.Owner(@This(), PageQuery, readPages);
pub const MaintenancePolicy = struct {
max_segments: u64 = 256,
step_bytes: usize = 0,
max_memtable_bytes: usize = 4 << 20,
log_gc_names: usize = 0,
};
maintenance_policy: MaintenancePolicy = .{},
write_owner: ?*WriteOwner = null,
page_owner: ?*PageOwner = null,
maintenance_after_ack: bool = false,
background_writes: bool = false,
log_collector: Db.LogCollector = .{},
log_gc_pending: bool = false,
maintenance_detail: struct {
changed_commits: usize = 0,
flushed_bytes: usize = 0,
flushed_segments: u64 = 0,
flush_ns: i96 = 0,
compact_ns: i96 = 0,
collect_ns: i96 = 0,
collect_max_ns: i96 = 0,
log_gc_steps: usize = 0,
log_gc_max_ns: i96 = 0,
compactions: usize = 0,
compaction_steps: usize = 0,
pending_polls: usize = 0,
} = .{},
maintenance_runs: usize = 0,
maintenance_ns: i96 = 0,
maintenance_max_ns: i96 = 0,
resync_counter: u64 = 0,
resync_guard: ?ResyncGuard = null,
db: *Db,
store: *zkv.DirStore,
maintenance_store: *BackgroundWriter,
async_store: *Store,
read_db: *ReadDb,
read_store: *ReaderStore,
read_mutex: Io.Mutex = .init,
read_io: Io,
allocator: Allocator,
io: Io,
mutex: Io.Mutex = .init,
failed: std.atomic.Value(bool) = .init(false),
/// Both handles keep one fence key in 32 resident per table and fetch
/// the rest through the block cache: with every fence resident, the
/// 2026-11-08 index (2,595 tables, 22.8 GB) pinned about 1 GB per
/// handle. The cache is wider than zkv's 1 MiB default so fence
/// partitions and data blocks do not evict each other on every page.
const db_options: zkv.Options = .{ .fence_stride = 32, .cache_bytes = 64 << 20 };
pub fn open(allocator: Allocator, io: Io, data_dir: []const u8) !CollectionIndex {
return openWithReaderIo(allocator, io, io, data_dir);
}
pub fn openWithReaderIo(allocator: Allocator, io: Io, read_io: Io, data_dir: []const u8) !CollectionIndex {
var dir = try Io.Dir.cwd().createDirPathOpen(io, data_dir, .{ .open_options = .{ .iterate = true } });
errdefer dir.close(io);
// Refuse a RocksDB directory.
if (dir.access(io, "CURRENT", .{})) |_| {
return error.ExistingRocksDB;
} else |err| if (err != error.FileNotFound) return err;
const store = try allocator.create(zkv.DirStore);
errdefer allocator.destroy(store);
store.* = .init(allocator, io, dir);
errdefer store.deinit();
const maintenance_dir = try dir.openDir(io, ".", .{ .iterate = true });
errdefer maintenance_dir.close(io);
const maintenance_store = try allocator.create(BackgroundWriter);
errdefer allocator.destroy(maintenance_store);
maintenance_store.* = .{ .inner = .init(allocator, io, maintenance_dir) };
errdefer maintenance_store.inner.deinit();
const async_store = try allocator.create(Store);
errdefer allocator.destroy(async_store);
async_store.* = .init(io, store, maintenance_store);
errdefer async_store.deinit();
const db = try Db.open(allocator, async_store, db_options);
errdefer db.close();
const read_dir = try dir.openDir(read_io, ".", .{ .iterate = true });
errdefer read_dir.close(read_io);
const read_store = try allocator.create(ReaderStore);
errdefer allocator.destroy(read_store);
read_store.* = .init(allocator, read_io, read_dir);
errdefer read_store.deinit();
const read_db = try ReadDb.openReader(allocator, read_store, db_options);
return .{ .db = db, .store = store, .maintenance_store = maintenance_store, .async_store = async_store, .read_db = read_db, .read_store = read_store, .read_io = read_io, .allocator = allocator, .io = io };
}
pub fn memoryUsage(self: *CollectionIndex) ?struct {
blocks: usize,
memtable: usize,
resident_meta: usize,
unflushed_segments: u64,
l0_tables: usize,
compaction_active: bool,
changed_commits: usize,
flushed_segments: u64,
compaction_steps: usize,
log_gc_steps: usize,
} {
if (!self.mutex.tryLock()) return null;
defer self.mutex.unlock(self.io);
if (!self.read_mutex.tryLock()) return null;
defer self.read_mutex.unlock(self.read_io);
return .{ .blocks = self.db.cache.bytes + self.read_db.cache.bytes, .memtable = self.db.memtableBytes(), .resident_meta = self.db.residentMetadataBytes() + self.read_db.residentMetadataBytes(), .unflushed_segments = self.db.unflushedSegments(), .l0_tables = self.db.version.tables[0].len, .compaction_active = self.db.compaction != null, .changed_commits = self.maintenance_detail.changed_commits, .flushed_segments = self.maintenance_detail.flushed_segments, .compaction_steps = self.maintenance_detail.compaction_steps, .log_gc_steps = self.maintenance_detail.log_gc_steps };
}
pub fn deinit(self: *CollectionIndex) void {
if (self.write_owner) |owner| {
owner.close();
self.async_store.cancelPut();
self.allocator.destroy(owner);
}
if (self.page_owner) |owner| {
owner.close();
self.allocator.destroy(owner);
}
self.read_db.close();
self.read_store.deinit();
self.read_store.dir.close(self.read_io);
self.allocator.destroy(self.read_store);
self.log_collector.deinit(self.allocator);
self.db.close();
self.async_store.deinit();
self.allocator.destroy(self.async_store);
self.maintenance_store.inner.deinit();
self.maintenance_store.inner.dir.close(self.io);
self.allocator.destroy(self.maintenance_store);
self.store.deinit();
self.store.dir.close(self.io);
self.allocator.destroy(self.store);
}
fn lock(self: *CollectionIndex) !void {
self.mutex.lockUncancelable(self.io);
if (self.failed.load(.acquire)) {
self.mutex.unlock(self.io);
return error.IndexUnavailable;
}
}
fn lockReader(self: *CollectionIndex) !void {
self.read_mutex.lockUncancelable(self.read_io);
if (self.failed.load(.acquire)) {
self.read_mutex.unlock(self.read_io);
return error.IndexUnavailable;
}
}
fn commit(self: *CollectionIndex) !void {
self.db.commit() catch |err| {
self.failed.store(true, .release);
return err;
};
self.maintenance_detail.changed_commits += 1;
if (!self.maintenance_after_ack) _ = try self.maintain();
}
fn maintainAfterAck(self: *CollectionIndex) owner_mod.Maintenance {
if (!self.maintenance_after_ack) return .idle;
self.lock() catch return .idle;
defer self.mutex.unlock(self.io);
return self.maintain() catch |err| {
self.failed.store(true, .release);
log.warn("collection index deferred maintenance failed: {t}", .{err});
return .idle;
};
}
fn compactMaintenance(self: *CollectionIndex) !zkv.CompactionProgress {
if (self.background_writes) return self.db.compactPoll(self.maintenance_policy.step_bytes);
return if (try self.db.compactStep(self.maintenance_policy.step_bytes)) .progress else .idle;
}
fn collectMaintenance(self: *CollectionIndex) !void {
if (self.maintenance_policy.log_gc_names == 0) return self.db.collect();
try self.db.collectTables();
self.log_gc_pending = true;
}
fn maintain(self: *CollectionIndex) !owner_mod.Maintenance {
var worked = false;
var waiting = false;
if (self.db.unflushedSegments() >= self.maintenance_policy.max_segments or self.db.memtableBytes() >= self.maintenance_policy.max_memtable_bytes) {
worked = true;
const maintenance_started = Io.Clock.awake.now(self.io).nanoseconds;
defer {
const elapsed = Io.Clock.awake.now(self.io).nanoseconds - maintenance_started;
self.maintenance_runs += 1;
self.maintenance_ns += elapsed;
self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
}
const flush_started = Io.Clock.awake.now(self.io).nanoseconds;
self.maintenance_detail.flushed_bytes += self.db.memtableBytes();
self.maintenance_detail.flushed_segments += self.db.unflushedSegments();
self.db.flush() catch |err| {
self.failed.store(true, .release);
log.warn("collection index flush failed: {t}", .{err});
return err;
};
const compact_started = Io.Clock.awake.now(self.io).nanoseconds;
self.maintenance_detail.flush_ns += compact_started - flush_started;
while (self.maintenance_policy.step_bytes == 0 and (self.db.compact() catch |err| {
self.failed.store(true, .release);
log.warn("collection index compaction failed: {t}", .{err});
return err;
})) {
self.maintenance_detail.compactions += 1;
}
const collect_started = Io.Clock.awake.now(self.io).nanoseconds;
self.maintenance_detail.compact_ns += collect_started - compact_started;
self.collectMaintenance() catch |err| {
self.failed.store(true, .release);
log.warn("collection index collection failed: {t}", .{err});
return err;
};
const collect_elapsed = Io.Clock.awake.now(self.io).nanoseconds - collect_started;
self.maintenance_detail.collect_ns += collect_elapsed;
self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, collect_elapsed);
}
if (self.maintenance_policy.step_bytes > 0) {
if (comptime @hasDecl(Db, "compactStep")) {
const started = Io.Clock.awake.now(self.io).nanoseconds;
const progress = self.compactMaintenance() catch |err| {
self.failed.store(true, .release);
return err;
};
const elapsed = Io.Clock.awake.now(self.io).nanoseconds - started;
self.maintenance_detail.compact_ns += elapsed;
if (progress != .idle) {
worked = worked or progress != .waiting;
waiting = progress == .waiting;
if (progress == .waiting) self.maintenance_detail.pending_polls += 1 else self.maintenance_detail.compaction_steps += 1;
self.maintenance_runs += 1;
self.maintenance_ns += elapsed;
self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
if (progress != .waiting and self.maintenance_after_ack and self.db.compaction == null) {
const collect_started = Io.Clock.awake.now(self.io).nanoseconds;
try self.collectMaintenance();
const collect_elapsed = Io.Clock.awake.now(self.io).nanoseconds - collect_started;
self.maintenance_detail.collect_ns += collect_elapsed;
self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, collect_elapsed);
self.maintenance_ns += collect_elapsed;
self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed + collect_elapsed);
}
}
} else return error.SteppedCompactionUnavailable;
}
if (self.log_gc_pending) {
const started = Io.Clock.awake.now(self.io).nanoseconds;
const applied = if (self.log_collector.names != null) self.log_collector.applied else self.db.version.applied;
const more = self.db.collectLogStep(&self.log_collector, self.maintenance_policy.log_gc_names) catch |err| {
self.failed.store(true, .release);
return err;
};
self.log_gc_pending = more or self.db.version.applied > applied;
const elapsed = Io.Clock.awake.now(self.io).nanoseconds - started;
self.maintenance_detail.log_gc_steps += 1;
self.maintenance_detail.log_gc_max_ns = @max(self.maintenance_detail.log_gc_max_ns, elapsed);
self.maintenance_detail.collect_ns += elapsed;
self.maintenance_detail.collect_max_ns = @max(self.maintenance_detail.collect_max_ns, elapsed);
self.maintenance_runs += 1;
self.maintenance_ns += elapsed;
self.maintenance_max_ns = @max(self.maintenance_max_ns, elapsed);
worked = true;
}
return if (worked) .progress else if (waiting) .waiting else .idle;
}
pub const Pair = IndexPair;
pub const BatchOptions = struct {
max_batch: usize = 16,
queue_limit: usize = 64,
delay_ns: i96 = 1_000_000,
maintenance_after_ack: bool = false,
background_writes: bool = false,
};
pub fn enableBatching(self: *CollectionIndex, options: BatchOptions) !void {
if (self.write_owner != null) return error.AlreadyStarted;
if (options.background_writes and (!options.maintenance_after_ack or self.maintenance_policy.step_bytes == 0)) return error.InvalidBatchPolicy;
const owner = try self.allocator.create(WriteOwner);
errdefer self.allocator.destroy(owner);
owner.* = .{ .context = self, .io = self.read_io, .max_batch = options.max_batch, .queue_limit = options.queue_limit, .delay_ns = options.delay_ns };
self.maintenance_after_ack = options.maintenance_after_ack;
errdefer self.maintenance_after_ack = false;
self.background_writes = options.background_writes;
errdefer self.background_writes = false;
if (options.background_writes) self.async_store.notify = .{ .context = owner, .call = wakeMaintenance };
errdefer self.async_store.notify = null;
try owner.start();
self.write_owner = owner;
}
fn wakeMaintenance(context: *anyopaque) void {
const owner: *WriteOwner = @ptrCast(@alignCast(context));
owner.wakeMaintenance();
}
fn submitMutation(self: *CollectionIndex, mutation: Mutation) !void {
try validateMutation(mutation);
if (self.write_owner) |owner| {
var request: WriteOwner.Request = .{ .item = mutation };
try owner.submit(&request);
request.done.waitUncancelable(self.read_io);
try request.outcome;
} else {
try self.applyMutations(&.{mutation});
}
}
fn mayDelay(self: *CollectionIndex, mutation: Mutation) bool {
self.lock() catch return false;
defer self.mutex.unlock(self.io);
return switch (mutation) {
.frame => |frame| blk: {
const items = switch (frame.ops) {
.array => |items| items,
else => break :blk false,
};
for (items) |op| {
const action = op.getString("action") orelse continue;
if (!std.mem.eql(u8, action, "create") and !std.mem.eql(u8, action, "update")) continue;
const path = op.getString("path") orelse continue;
const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
if (slash == 0) continue;
if (!(self.knownPair(frame.did, path[0..slash]) catch return true)) break :blk true;
}
break :blk false;
},
.pair => |item| item.delete or !(self.knownPair(item.pair.did, item.pair.collection) catch return true),
.pairs => |pairs| blk: {
for (pairs) |pair| if (!(self.knownPair(pair.did, pair.collection) catch return true)) break :blk true;
break :blk false;
},
.page => |page| blk: {
if (page.delete) break :blk true;
for (page.dids) |did| if (!(self.knownPair(did, page.collection) catch return true)) break :blk true;
break :blk false;
},
.replace, .guarded_replace => true,
};
}
fn knownPair(self: *CollectionIndex, did: []const u8, collection: []const u8) !bool {
const forward = try makeKey(self.allocator, rbc, collection, did);
defer self.allocator.free(forward);
const reverse = try makeKey(self.allocator, cbr, did, collection);
defer self.allocator.free(reverse);
return (try self.db.get(forward)) != null and (try self.db.get(reverse)) != null;
}
fn applyMutations(self: *CollectionIndex, mutations: []const Mutation) anyerror!void {
try self.lock();
defer self.mutex.unlock(self.io);
errdefer self.discard();
for (mutations) |mutation| switch (mutation) {
.pair => |item| try self.stagePair(item.pair.did, item.pair.collection, item.delete),
.pairs => |pairs| for (pairs) |pair| {
try self.stagePair(pair.did, pair.collection, false);
},
.page => |page| for (page.dids) |did| {
try self.stagePair(did, page.collection, page.delete);
},
.replace => |replacement| {
try self.stageRemoveAll(replacement.did);
for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
},
.frame => |frame| try self.stageCommitOps(frame.did, frame.ops),
.guarded_replace => |replacement| {
replacement.applied.* = .superseded;
if (self.resync_guard) |guard| {
if (guard.token == replacement.token and std.mem.eql(u8, guard.did[0..guard.len], replacement.did)) {
if (!guard.changed) {
try self.stageRemoveAll(replacement.did);
for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
replacement.applied.* = .replaced;
} else if (!guard.destructive) {
for (replacement.collections) |collection| try self.stagePair(replacement.did, collection, false);
replacement.applied.* = .merged;
}
self.resync_guard = null;
}
}
},
};
if (self.db.stagedBytes() != 0) try self.commit();
}
fn validateKey(key: []const u8) !void {
if (key.len == 0 or std.mem.indexOfScalar(u8, key, separator) != null) return error.InvalidIndexKey;
}
fn validateMutation(mutation: Mutation) !void {
switch (mutation) {
.pair => |item| {
try validateKey(item.pair.did);
try validateKey(item.pair.collection);
},
.pairs => |pairs| for (pairs) |pair| {
try validateKey(pair.did);
try validateKey(pair.collection);
},
.page => |page| {
try validateKey(page.collection);
for (page.dids) |did| try validateKey(did);
},
.replace => |replacement| {
try validateKey(replacement.did);
for (replacement.collections) |collection| try validateKey(collection);
},
.guarded_replace => |replacement| {
try validateKey(replacement.did);
for (replacement.collections) |collection| try validateKey(collection);
},
.frame => |frame| {
const items = switch (frame.ops) {
.array => |items| items,
else => return,
};
for (items) |op| {
const action = op.getString("action") orelse continue;
if (!std.mem.eql(u8, action, "create") and !std.mem.eql(u8, action, "update")) continue;
const path = op.getString("path") orelse continue;
const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
if (slash == 0) continue;
try validateKey(frame.did);
try validateKey(path[0..slash]);
}
},
}
}
pub fn addPairs(self: *CollectionIndex, pairs: []const Pair) !void {
try self.submitMutation(.{ .pairs = pairs });
}
fn stagePair(self: *CollectionIndex, did: []const u8, collection: []const u8, delete: bool) !void {
self.noteMutation(did, delete);
if (did.len == 0 or collection.len == 0 or
std.mem.indexOfScalar(u8, did, separator) != null or
std.mem.indexOfScalar(u8, collection, separator) != null) return error.InvalidIndexKey;
const a = try makeKey(self.allocator, rbc, collection, did);
defer self.allocator.free(a);
const b = try makeKey(self.allocator, cbr, did, collection);
defer self.allocator.free(b);
if (delete) {
try self.db.del(a);
try self.db.del(b);
} else {
// Sources other than validated firehose commits (describeRepo
// snapshots, backfill pages) can carry arbitrary strings.
if (!isValidCollection(collection)) return;
if ((try self.db.get(a)) != null and (try self.db.get(b)) != null) return;
try self.db.put(a, "");
try self.db.put(b, "");
}
}
fn discard(self: *CollectionIndex) void {
self.db.discard() catch {
self.failed.store(true, .release);
};
}
fn mutatePair(self: *CollectionIndex, did: []const u8, collection: []const u8, delete: bool) !void {
try self.submitMutation(.{ .pair = .{ .pair = .{ .did = did, .collection = collection }, .delete = delete } });
}
pub fn addCollection(self: *CollectionIndex, did: []const u8, collection: []const u8) !void {
try self.mutatePair(did, collection, false);
}
pub fn removeCollection(self: *CollectionIndex, did: []const u8, collection: []const u8) !void {
try self.mutatePair(did, collection, true);
}
pub fn addCollectionPage(self: *CollectionIndex, dids: []const []const u8, collection: []const u8) !void {
try self.submitMutation(.{ .page = .{ .dids = dids, .collection = collection } });
}
pub fn removeCollectionPage(self: *CollectionIndex, dids: []const []const u8, collection: []const u8) !void {
try self.submitMutation(.{ .page = .{ .dids = dids, .collection = collection, .delete = true } });
}
/// Remove every pair filed under a collection name that is not an NSID.
/// Pages through each such name with a cursor, so it does not depend on
/// the reader observing its own deletions.
pub fn purgeInvalidCollections(
self: *CollectionIndex,
allocator: Allocator,
stop: *const std.atomic.Value(bool),
removed: *std.atomic.Value(u64),
) !void {
const known = try self.listKnownCollections(allocator);
defer {
for (known) |collection| allocator.free(collection);
allocator.free(known);
}
const bytes = try allocator.alloc(u8, 65536);
defer allocator.free(bytes);
const spans = try allocator.alloc(Span, 1000);
defer allocator.free(spans);
const dids = try allocator.alloc([]const u8, spans.len);
defer allocator.free(dids);
var cursor_buf: [2048]u8 = undefined;
for (known) |collection| {
if (isValidCollection(collection)) continue;
var cursor: ?[]const u8 = null;
while (!stop.load(.acquire)) {
const page = try self.listReposByCollection(collection, spans.len, cursor, bytes, spans);
if (page.count == 0) break;
for (0..page.count) |i| dids[i] = page.getDid(i);
try self.removeCollectionPage(dids[0..page.count], collection);
_ = removed.fetchAdd(page.count, .monotonic);
const last = page.last_did.?;
if (last.len > cursor_buf.len) return error.BufferTooSmall;
@memcpy(cursor_buf[0..last.len], last);
cursor = cursor_buf[0..last.len];
}
}
}
pub fn removeAll(self: *CollectionIndex, did: []const u8) !void {
try self.replaceCollections(did, &.{});
}
pub fn replaceCollections(self: *CollectionIndex, did: []const u8, collections: []const []const u8) !void {
try self.submitMutation(.{ .replace = .{ .did = did, .collections = collections } });
}
pub const ResyncResult = SnapshotResult;
pub fn beginResync(self: *CollectionIndex, did: []const u8) !u64 {
try validateKey(did);
if (did.len > 128) return error.InvalidIndexKey;
try self.lock();
defer self.mutex.unlock(self.io);
if (self.resync_guard != null) return error.ResyncBusy;
if (self.resync_counter == std.math.maxInt(u64)) return error.ResyncTokenExhausted;
self.resync_counter += 1;
var guard: ResyncGuard = .{ .did = undefined, .len = did.len, .token = self.resync_counter, .changed = false, .destructive = false };
@memcpy(guard.did[0..did.len], did);
self.resync_guard = guard;
return guard.token;
}
pub fn cancelResync(self: *CollectionIndex, token: u64) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (self.resync_guard) |guard| if (guard.token == token) {
self.resync_guard = null;
};
}
pub fn finishResync(self: *CollectionIndex, did: []const u8, token: u64, collections: []const []const u8) !ResyncResult {
var applied: ResyncResult = .superseded;
try self.submitMutation(.{ .guarded_replace = .{ .did = did, .token = token, .collections = collections, .applied = &applied } });
return applied;
}
fn noteMutation(self: *CollectionIndex, did: []const u8, destructive: bool) void {
if (self.resync_guard) |*guard| if (std.mem.eql(u8, guard.did[0..guard.len], did)) {
guard.changed = true;
guard.destructive = guard.destructive or destructive;
};
}
fn stageRemoveAll(self: *CollectionIndex, did: []const u8) !void {
self.noteMutation(did, true);
if (did.len == 0 or std.mem.indexOfScalar(u8, did, separator) != null)
return error.InvalidIndexKey;
const prefix = try makeKey(self.allocator, cbr, did, "");
defer self.allocator.free(prefix);
{
var iter = try self.db.scan(.{ .start = prefix });
defer iter.deinit();
while (try iter.next()) |entry| {
if (!std.mem.startsWith(u8, entry.key, prefix)) break;
try self.stagePair(did, entry.key[prefix.len..], true);
}
}
}
/// process commit ops to update collection index.
/// extracts collection from each op path (<collection>/<rkey>).
/// for creates: ensures collection is tracked.
///
/// `ops` is a cbor Value (expected to be an array of {action, path, cid?} maps).
pub fn trackCommitOps(self: *CollectionIndex, did: []const u8, ops: zat.cbor.Value) !void {
try self.submitMutation(.{ .frame = .{ .did = did, .ops = ops } });
}
fn stageCommitOps(self: *CollectionIndex, did: []const u8, ops: zat.cbor.Value) !void {
self.noteMutation(did, false);
const items = switch (ops) {
.array => |items| items,
else => return,
};
for (items) |op| {
const action = op.getString("action") orelse continue;
const path = op.getString("path") orelse continue;
const slash = std.mem.indexOfScalar(u8, path, '/') orelse continue;
if (slash == 0) continue;
if (std.mem.eql(u8, action, "create") or std.mem.eql(u8, action, "update")) {
try self.stagePair(did, path[0..slash], false);
}
// A record delete does not establish that the collection is empty.
}
}
/// list DIDs that have records in a collection. returns up to `limit` DIDs
/// starting after `cursor_did` (or from the beginning if null).
/// The result borrows both caller-owned output buffers.
pub fn listReposByCollection(
self: *CollectionIndex,
collection: []const u8,
limit: usize,
cursor_did: ?[]const u8,
out_buf: []u8,
did_offsets: []Span,
) !ListResult {
if (limit > did_offsets.len) return error.BufferTooSmall;
if (self.page_owner) |owner| {
var result: ListResult = undefined;
var request: PageOwner.Request = .{ .item = .{
.collection = collection,
.limit = limit,
.cursor = cursor_did,
.bytes = out_buf,
.offsets = did_offsets,
.result = &result,
} };
try owner.submit(&request);
request.done.waitUncancelable(self.read_io);
try request.outcome;
return result;
}
return self.listReposDirect(collection, limit, cursor_did, out_buf, did_offsets);
}
pub fn enablePageWorker(self: *CollectionIndex, queue_limit: usize) !void {
if (self.page_owner != null) return error.AlreadyStarted;
const owner = try self.allocator.create(PageOwner);
errdefer self.allocator.destroy(owner);
owner.* = .{ .context = self, .io = self.read_io, .max_batch = 1, .queue_limit = queue_limit, .delay_ns = 0 };
try owner.start();
self.page_owner = owner;
}
fn readPages(self: *CollectionIndex, queries: []const PageQuery) !void {
for (queries) |query| query.result.* = try self.listReposDirect(query.collection, query.limit, query.cursor, query.bytes, query.offsets);
}
fn listReposDirect(self: *CollectionIndex, collection: []const u8, limit: usize, cursor_did: ?[]const u8, out_buf: []u8, did_offsets: []Span) !ListResult {
try self.lockReader();
defer self.read_mutex.unlock(self.read_io);
for (0..3) |_| {
self.read_db.refresh() catch |err| {
if (err == error.Missing) continue;
return err;
};
return self.pageOnce(collection, limit, cursor_did, out_buf, did_offsets) catch |err| {
if (err == error.Missing) continue;
return err;
};
}
return error.ReaderRetryExhausted;
}
fn pageOnce(self: *CollectionIndex, collection: []const u8, limit: usize, cursor_did: ?[]const u8, out_buf: []u8, did_offsets: []Span) !ListResult {
const prefix = try makeKey(self.allocator, rbc, collection, "");
defer self.allocator.free(prefix);
const seek_key = if (cursor_did) |cursor|
try std.mem.concat(self.allocator, u8, &.{ prefix, cursor, "\x00" })
else
prefix;
defer if (cursor_did != null) self.allocator.free(seek_key);
var iter = try self.read_db.scan(.{ .start = seek_key });
defer iter.deinit();
var count: usize = 0;
var buf_pos: usize = 0;
var last_did: ?[]const u8 = null;
while (count < limit) {
const entry = (try iter.next()) orelse break;
const key_data = entry.key;
// stop when prefix no longer matches
if (!std.mem.startsWith(u8, key_data, prefix)) break;
// extract DID after prefix
const did = key_data[prefix.len..];
if (did.len == 0) continue;
// copy DID into output buffer
if (buf_pos + did.len > out_buf.len) break;
@memcpy(out_buf[buf_pos..][0..did.len], did);
did_offsets[count] = .{ .start = buf_pos, .len = did.len };
buf_pos += did.len;
last_did = out_buf[did_offsets[count].start..][0..did_offsets[count].len];
count += 1;
}
return .{
.count = count,
.offsets = did_offsets[0..count],
.buf = out_buf[0..buf_pos],
.last_did = last_did,
};
}
/// scan the RBC column family for unique collection prefixes.
/// returns a deduplicated list of collection names (caller owns the slice and each string).
/// Every collection with at least one RBC entry, found by seeking from
/// one collection's last possible key to the next: one short scan per
/// collection instead of a walk over every pair, and the reader is held
/// only for that seek, so pages keep being served while this runs. The
/// reader is refreshed once up front; a table collected mid-walk surfaces
/// as Missing and refreshes again.
pub fn listKnownCollections(self: *CollectionIndex, allocator: Allocator) ![][]const u8 {
var found: std.ArrayListUnmanaged([]const u8) = .empty;
errdefer {
for (found.items) |c| allocator.free(c);
found.deinit(allocator);
}
var cursor: std.ArrayListUnmanaged(u8) = .empty;
defer cursor.deinit(allocator);
try cursor.appendSlice(allocator, rbc);
{
try self.lockReader();
defer self.read_mutex.unlock(self.read_io);
try self.read_db.refresh();
}
while (try self.nextCollectionFrom(allocator, cursor.items)) |collection| {
errdefer allocator.free(collection);
try found.append(allocator, collection);
cursor.clearRetainingCapacity();
try cursor.appendSlice(allocator, rbc);
try cursor.appendSlice(allocator, collection);
try cursor.append(allocator, separator + 1);
}
return found.toOwnedSlice(allocator);
}
fn nextCollectionFrom(self: *CollectionIndex, allocator: Allocator, start: []const u8) !?[]const u8 {
try self.lockReader();
defer self.read_mutex.unlock(self.read_io);
for (0..3) |attempt| {
if (attempt > 0) self.read_db.refresh() catch |err| {
if (err == error.Missing) continue;
return err;
};
return self.firstCollectionOnce(allocator, start) catch |err| {
if (err == error.Missing) continue;
return err;
};
}
return error.ReaderRetryExhausted;
}
fn firstCollectionOnce(self: *CollectionIndex, allocator: Allocator, start: []const u8) !?[]const u8 {
var iter = try self.read_db.scan(.{ .start = start, .end = cbr });
defer iter.deinit();
while (try iter.next()) |entry| {
const key_data = entry.key[1..];
const sep_pos = std.mem.indexOfScalar(u8, key_data, separator) orelse continue;
const collection = key_data[0..sep_pos];
if (collection.len == 0) continue;
return try allocator.dupe(u8, collection);
}
return null;
}
/// check if a DID has any collection entries
pub fn hasCollections(self: *CollectionIndex, did: []const u8) bool {
return self.hasCollectionsChecked(did) catch false;
}
pub fn hasCollectionsChecked(self: *CollectionIndex, did: []const u8) !bool {
try self.lockReader();
defer self.read_mutex.unlock(self.read_io);
const prefix = try makeKey(self.allocator, cbr, did, "");
defer self.allocator.free(prefix);
for (0..3) |_| {
self.read_db.refresh() catch |err| {
if (err == error.Missing) continue;
return err;
};
return self.hasOnce(prefix) catch |err| {
if (err == error.Missing) continue;
return err;
};
}
return error.ReaderRetryExhausted;
}
fn hasOnce(self: *CollectionIndex, prefix: []const u8) !bool {
var iter = try self.read_db.scan(.{ .start = prefix });
defer iter.deinit();
const entry = (try iter.next()) orelse return false;
return std.mem.startsWith(u8, entry.key, prefix);
}
};
pub fn isValidCollection(collection: []const u8) bool {
return zat.Nsid.parse(collection) != null;
}
pub const Span = struct { start: usize, len: usize };
pub const ListResult = struct {
count: usize,
offsets: []const Span,
buf: []const u8,
last_did: ?[]const u8,
/// get the DID at index i
pub fn getDid(self: ListResult, i: usize) []const u8 {
const off = self.offsets[i];
return self.buf[off.start..][0..off.len];
}
};
fn makeKey(allocator: Allocator, namespace: []const u8, a: []const u8, b: []const u8) ![]u8 {
return std.mem.concat(allocator, u8, &.{ namespace, a, "\x00", b });
}
// --- tests ---
test "collection index: open and close" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
ci.deinit();
}
test "collection index: basic put and get" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
// add a single collection entry
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try testing.expect(ci.hasCollections("did:plc:alice"));
}
test "collection index: list and cursor" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.addCollection("did:plc:bob", "app.bsky.feed.post");
try ci.addCollection("did:plc:carol", "app.bsky.graph.follow");
// list repos by collection
var buf: [4096]u8 = undefined;
var offsets: [2000]Span = undefined;
const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
try testing.expectEqual(@as(usize, 2), result.count);
try testing.expectEqualStrings("did:plc:alice", result.getDid(0));
try testing.expectEqualStrings("did:plc:bob", result.getDid(1));
// cursor pagination
const result2 = try ci.listReposByCollection("app.bsky.feed.post", 100, "did:plc:alice", &buf, &offsets);
try testing.expectEqual(@as(usize, 1), result2.count);
try testing.expectEqualStrings("did:plc:bob", result2.getDid(0));
}
test "collection index: removeAll" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.addCollection("did:plc:alice", "app.bsky.feed.like");
try ci.addCollection("did:plc:bob", "app.bsky.feed.post");
try ci.removeAll("did:plc:alice");
try testing.expect(!ci.hasCollections("did:plc:alice"));
var buf: [4096]u8 = undefined;
var offsets: [2000]Span = undefined;
const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
try testing.expectEqual(@as(usize, 1), result.count);
try testing.expectEqualStrings("did:plc:bob", result.getDid(0));
}
test "collection index: listKnownCollections" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.addCollection("did:plc:bob", "app.bsky.feed.post");
try ci.addCollection("did:plc:alice", "app.bsky.feed.like");
try ci.addCollection("did:plc:carol", "app.bsky.graph.follow");
const collections = try ci.listKnownCollections(allocator);
defer {
for (collections) |c| allocator.free(c);
allocator.free(collections);
}
try testing.expectEqual(@as(usize, 3), collections.len);
// verify all three collections are present (order not guaranteed)
var found_post = false;
var found_like = false;
var found_follow = false;
for (collections) |c| {
if (std.mem.eql(u8, c, "app.bsky.feed.post")) found_post = true;
if (std.mem.eql(u8, c, "app.bsky.feed.like")) found_like = true;
if (std.mem.eql(u8, c, "app.bsky.graph.follow")) found_follow = true;
}
try testing.expect(found_post);
try testing.expect(found_like);
try testing.expect(found_follow);
}
test "collection index: listKnownCollections seeks across flushed tables and adjacent prefixes" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
const names = [_][]const u8{ "app.bsky.feed.post", "app.bsky.feed.post.extra", "app.bsky.feed.postscript", "sh.tangled.repo" };
var buffers: [64][64]u8 = undefined;
var ids: [64][]const u8 = undefined;
for (names, 0..) |name, n| {
for (0..4) |chunk| {
for (&buffers, &ids, 0..) |*buf, *id, i| id.* = try std.fmt.bufPrint(buf, "did:plc:{d:0>3}{d:0>3}{d:0>18}", .{ n, chunk, i });
try ci.addCollectionPage(&ids, name);
if (chunk % 2 == 1) try ci.db.flush();
}
}
while (try ci.db.compact()) {}
try ci.addCollection("did:plc:late", "zzz.last.collection");
const collections = try ci.listKnownCollections(allocator);
defer {
for (collections) |c| allocator.free(c);
allocator.free(collections);
}
try testing.expectEqual(@as(usize, names.len + 1), collections.len);
for (names) |name| {
var found = false;
for (collections) |c| found = found or std.mem.eql(u8, c, name);
try testing.expect(found);
}
try testing.expectEqualStrings("zzz.last.collection", collections[collections.len - 1]);
}
test "collection index: invalid collection names are not added and existing ones are purged" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(t.allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
const junk = [_][]const u8{ "app.bsky.feed.post&", "app.bsky.feed.post;DECLARE/**/@x", "community.lexicon.calendar.event#uri" };
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
for (junk) |name| try ci.addCollection("did:plc:alice", name);
try ci.addCollectionPage(&.{ "did:plc:bob", "did:plc:carol" }, junk[0]);
try ci.replaceCollections("did:plc:dave", &.{ "app.bsky.graph.follow", junk[1] });
{
const known = try ci.listKnownCollections(t.allocator);
defer {
for (known) |name| t.allocator.free(name);
t.allocator.free(known);
}
try t.expectEqual(@as(usize, 2), known.len);
}
// Junk written before the check existed.
var id: [32]u8 = undefined;
try ci.lock();
{
defer ci.mutex.unlock(ci.io);
for (junk) |name| for (0..2500) |i| {
const did = try std.fmt.bufPrint(&id, "did:plc:{d:0>24}", .{i});
const forward = try makeKey(t.allocator, rbc, name, did);
defer t.allocator.free(forward);
const reverse = try makeKey(t.allocator, cbr, did, name);
defer t.allocator.free(reverse);
try ci.db.put(forward, "");
try ci.db.put(reverse, "");
};
try ci.commit();
}
try ci.addCollection("did:plc:000000000000000000000007", "app.bsky.feed.post");
var stop = std.atomic.Value(bool).init(false);
var removed = std.atomic.Value(u64).init(0);
try ci.purgeInvalidCollections(t.allocator, &stop, &removed);
try t.expectEqual(@as(u64, junk.len * 2500), removed.load(.monotonic));
const known = try ci.listKnownCollections(t.allocator);
defer {
for (known) |name| t.allocator.free(name);
t.allocator.free(known);
}
try t.expectEqual(@as(usize, 2), known.len);
try t.expectEqualStrings("app.bsky.feed.post", known[0]);
try t.expectEqualStrings("app.bsky.graph.follow", known[1]);
var bytes: [4096]u8 = undefined;
var spans: [8]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", spans.len, null, &bytes, &spans);
try t.expectEqual(@as(usize, 2), page.count);
try t.expect(ci.hasCollections("did:plc:000000000000000000000007"));
try t.expect(!ci.hasCollections("did:plc:000000000000000000000008"));
}
test "collection index: idempotent add" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = std.testing.tmpDir(.{});
defer dir.cleanup();
const path = try std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{@as([]const u8, &dir.sub_path)});
defer allocator.free(path);
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
// add same entry twice — should not duplicate
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
var buf: [4096]u8 = undefined;
var offsets: [2000]Span = undefined;
const result = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &buf, &offsets);
try testing.expectEqual(@as(usize, 1), result.count);
}
test "collection index: cursor, deletion and maintenance survive reopen" {
const testing = std.testing;
const allocator = testing.allocator;
var dir = testing.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(testing.io, ".", allocator);
defer allocator.free(path);
const collection = "app.bsky.feed.post";
{
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
for (0..260) |i| {
var buf: [64]u8 = undefined;
try ci.addCollection(try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i}), collection);
}
try ci.addCollection("did:web:example.org", collection);
try ci.addCollection("did:web:example.org:alice", collection);
try ci.addCollection("did:web:example.org", "app.bsky.feed.like");
try ci.removeCollection("did:web:example.org", "app.bsky.feed.like");
try ci.removeAll("did:web:absent.example");
}
{
var ci = try CollectionIndex.open(allocator, testing.io, path);
defer ci.deinit();
var buf: [128]u8 = undefined;
var offsets: [2]Span = undefined;
const page = try ci.listReposByCollection(collection, 1, "did:web:example.org", &buf, &offsets);
try testing.expectEqual(@as(usize, 1), page.count);
try testing.expectEqualStrings("did:web:example.org:alice", page.getDid(0));
try ci.removeAll("did:web:example.org");
try testing.expect(!ci.hasCollections("did:web:example.org"));
try testing.expect(ci.hasCollections("did:web:example.org:alice"));
}
}
test "collection index: concurrent producers publish both index directions" {
const testing = std.testing;
var dir = testing.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(testing.io, ".", testing.allocator);
defer testing.allocator.free(path);
var ci = try CollectionIndex.open(testing.allocator, testing.io, path);
defer ci.deinit();
const Worker = struct {
fn run(index: *CollectionIndex, did: []const u8, ok: *bool) void {
for (0..32) |_| index.addCollection(did, "app.bsky.feed.post") catch return;
ok.* = true;
}
};
var alice = false;
var bob = false;
const first = try std.Thread.spawn(.{}, Worker.run, .{ &ci, "did:plc:alice", &alice });
const second = std.Thread.spawn(.{}, Worker.run, .{ &ci, "did:plc:bob", &bob }) catch |err| {
first.join();
return err;
};
first.join();
second.join();
try testing.expect(alice and bob);
var buf: [128]u8 = undefined;
var spans: [2]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", spans.len, null, &buf, &spans);
try testing.expectEqual(@as(usize, 2), page.count);
try testing.expectEqualStrings("did:plc:alice", page.getDid(0));
try testing.expectEqualStrings("did:plc:bob", page.getDid(1));
try testing.expect(ci.hasCollections("did:plc:alice"));
try testing.expect(ci.hasCollections("did:plc:bob"));
}
test "collection index: rejected page or replacement leaves prior state intact" {
const testing = std.testing;
var dir = testing.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(testing.io, ".", testing.allocator);
defer testing.allocator.free(path);
var ci = try CollectionIndex.open(testing.allocator, testing.io, path);
defer ci.deinit();
const post = "app.bsky.feed.post";
const like = "app.bsky.feed.like";
const alice = "did:plc:alice";
try ci.addCollection(alice, post);
try testing.expectError(error.InvalidIndexKey, ci.addCollectionPage(&.{ "did:plc:bob", "bad\x00did" }, post));
try testing.expectError(error.InvalidIndexKey, ci.replaceCollections(alice, &.{ like, "" }));
try testing.expect(ci.hasCollections(alice));
try testing.expect(!ci.hasCollections("did:plc:bob"));
var bytes: [64]u8 = undefined;
var offsets: [2]Span = undefined;
try testing.expectEqual(@as(usize, 1), (try ci.listReposByCollection(post, 2, null, &bytes, &offsets)).count);
try testing.expectEqual(@as(usize, 0), (try ci.listReposByCollection(like, 2, null, &bytes, &offsets)).count);
try ci.replaceCollections(alice, &.{like});
try testing.expectEqual(@as(usize, 0), (try ci.listReposByCollection(post, 2, null, &bytes, &offsets)).count);
try testing.expectEqual(@as(usize, 1), (try ci.listReposByCollection(like, 2, null, &bytes, &offsets)).count);
}
test "collection index: cross-frame batch is atomic and survives reopen" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.addPairs(&.{
.{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" },
.{ .did = "did:plc:bob", .collection = "app.bsky.feed.like" },
.{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" },
});
try t.expectError(error.InvalidIndexKey, ci.addPairs(&.{
.{ .did = "did:plc:carol", .collection = "app.bsky.feed.post" },
.{ .did = "invalid\x00did", .collection = "app.bsky.feed.post" },
}));
try t.expect(!ci.hasCollections("did:plc:carol"));
}
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try t.expect(ci.hasCollections("did:plc:alice"));
try t.expect(ci.hasCollections("did:plc:bob"));
try t.expect(!ci.hasCollections("did:plc:carol"));
var bytes: [128]u8 = undefined;
var spans: [4]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans);
try t.expectEqual(@as(usize, 1), page.count);
try t.expectEqualStrings("did:plc:alice", page.getDid(0));
}
}
test "collection index: maintenance failure is reported and prevents later acknowledgements" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.enableBatching(.{ .delay_ns = 0 });
const obstacle = try dir.dir.createFile(t.io, "sst", .{});
obstacle.close(t.io);
var observed_failure = false;
for (0..300) |i| {
var bytes: [64]u8 = undefined;
const id = try std.fmt.bufPrint(&bytes, "did:plc:{d:0>24}", .{i});
ci.addCollection(id, "app.bsky.feed.post") catch {
observed_failure = true;
break;
};
}
try t.expect(observed_failure);
try t.expectError(error.IndexUnavailable, ci.hasCollectionsChecked("did:plc:later"));
try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
}
test "collection index: a fresh read completes while the writer mutex is held" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
const Reader = struct {
ci: *CollectionIndex,
done: Io.Event = .unset,
outcome: anyerror!bool = false,
fn run(self: *@This()) void {
self.outcome = self.ci.hasCollectionsChecked("did:plc:alice");
self.done.set(self.ci.io);
}
};
var reader: Reader = .{ .ci = &ci };
ci.mutex.lockUncancelable(t.io);
const thread = std.Thread.spawn(.{}, Reader.run, .{&reader}) catch |err| {
ci.mutex.unlock(t.io);
return err;
};
const completed = if (reader.done.waitTimeout(t.io, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } })) |_| true else |_| false;
ci.mutex.unlock(t.io);
thread.join();
try t.expect(completed);
try t.expect(try reader.outcome);
}
test "collection index: fresh complete pages survive concurrent flush compaction and collection" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
const Writer = struct {
ci: *CollectionIndex,
acknowledged: std.atomic.Value(usize) = .init(0),
done: std.atomic.Value(bool) = .init(false),
outcome: anyerror!void = {},
fn run(self: *@This()) void {
self.outcome = self.write();
self.done.store(true, .release);
}
fn write(self: *@This()) !void {
for (0..16) |chunk| {
var bytes: [32][64]u8 = undefined;
var dids: [32][]const u8 = undefined;
for (&bytes, &dids, 0..) |*buf, *id, i| id.* = try std.fmt.bufPrint(buf, "did:plc:{d:0>24}", .{chunk * 32 + i});
try self.ci.addCollectionPage(&dids, "app.bsky.feed.post");
self.acknowledged.store((chunk + 1) * 32, .release);
self.ci.mutex.lockUncancelable(self.ci.io);
defer self.ci.mutex.unlock(self.ci.io);
try self.ci.db.flush();
while (try self.ci.db.compact()) {}
try self.ci.db.collect();
}
}
};
var writer: Writer = .{ .ci = &ci };
const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer});
var joined = false;
defer if (!joined) thread.join();
var reads: usize = 0;
while (!writer.done.load(.acquire) or reads < 100) : (reads += 1) {
const required = @min(writer.acknowledged.load(.acquire), 100);
var bytes: [4096]u8 = undefined;
var spans: [100]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
try t.expect(page.count >= required);
if (page.count < 100) try t.expect(page.count % 32 == 0);
for (0..page.count) |i| {
var expected: [64]u8 = undefined;
try t.expectEqualStrings(try std.fmt.bufPrint(&expected, "did:plc:{d:0>24}", .{i}), page.getDid(i));
}
}
thread.join();
joined = true;
try writer.outcome;
try t.expectEqual(@as(usize, 512), writer.acknowledged.load(.acquire));
try t.expect(try ci.hasCollectionsChecked("did:plc:000000000000000000000511"));
}
test "collection index: live frame indexing reports rejected writes" {
const t = std.testing;
const Value = @import("zat").cbor.Value;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
const ops: Value = .{ .array = &.{.{ .map = &.{
.{ .key = "action", .value = .{ .text = "create" } },
.{ .key = "path", .value = .{ .text = "app.bsky.feed.post/record" } },
} }} };
try ci.trackCommitOps("did:plc:alice", ops);
try t.expectError(error.InvalidIndexKey, ci.trackCommitOps("bad\x00did", ops));
try t.expect(try ci.hasCollectionsChecked("did:plc:alice"));
try t.expect(!(try ci.hasCollectionsChecked("bad\x00did")));
}
test "collection index: ordered mutations within a commit replace earlier staged membership" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.applyMutations(&.{
.{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" }, .delete = false } },
.{ .replace = .{ .did = "did:plc:alice", .collections = &.{"app.bsky.feed.like"} } },
.{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.repost" }, .delete = false } },
});
var bytes: [128]u8 = undefined;
var spans: [4]Span = undefined;
try t.expectEqual(@as(usize, 0), (try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans)).count);
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.like", 4, null, &bytes, &spans)).count);
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.repost", 4, null, &bytes, &spans)).count);
}
test "collection index: owner drains ordered live backfill and resync requests before reopen" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.enableBatching(.{ .max_batch = 4, .queue_limit = 4 });
const ops: zat.cbor.Value = .{ .array = &.{.{ .map = &.{
.{ .key = "action", .value = .{ .text = "create" } },
.{ .key = "path", .value = .{ .text = "app.bsky.feed.repost/record" } },
} }} };
const mutations: [4]Mutation = .{
.{ .pair = .{ .pair = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" }, .delete = false } },
.{ .replace = .{ .did = "did:plc:alice", .collections = &.{"app.bsky.feed.like"} } },
.{ .frame = .{ .did = "did:plc:alice", .ops = ops } },
.{ .page = .{ .dids = &.{"did:plc:bob"}, .collection = "app.bsky.feed.post" } },
};
var requests: [4]CollectionIndex.WriteOwner.Request = undefined;
ci.mutex.lockUncancelable(t.io);
var locked = true;
defer if (locked) ci.mutex.unlock(t.io);
for (&requests, mutations) |*request, mutation| {
request.* = .{ .item = mutation };
try ci.write_owner.?.submit(request);
}
ci.mutex.unlock(t.io);
locked = false;
ci.write_owner.?.close();
for (&requests) |*request| {
try t.expect(request.done.isSet());
try request.outcome;
}
try t.expectError(error.Closed, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
}
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
var bytes: [128]u8 = undefined;
var spans: [4]Span = undefined;
const post = try ci.listReposByCollection("app.bsky.feed.post", 4, null, &bytes, &spans);
try t.expectEqual(@as(usize, 1), post.count);
try t.expectEqualStrings("did:plc:bob", post.getDid(0));
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.like", 4, null, &bytes, &spans)).count);
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection("app.bsky.feed.repost", 4, null, &bytes, &spans)).count);
}
}
test "collection index: known membership does not incur the aggregation deadline" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.enableBatching(.{ .delay_ns = 2_000_000_000 });
const before = Io.Clock.awake.now(t.io);
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
const elapsed = before.durationTo(Io.Clock.awake.now(t.io)).toNanoseconds();
try t.expect(elapsed < 1_000_000_000);
try t.expect(try ci.hasCollectionsChecked("did:plc:alice"));
}
test "collection index: resync merges concurrent additions and cannot undo destructive updates" {
const t = std.testing;
for ([_]bool{ false, true }) |batched| {
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
if (batched) try ci.enableBatching(.{ .delay_ns = 0 });
const alice = "did:plc:alice";
const post = "app.bsky.feed.post";
const like = "app.bsky.feed.like";
const follow = "app.bsky.graph.follow";
try ci.addCollection(alice, post);
const quiet = try ci.beginResync(alice);
try ci.addCollection("did:plc:bob", like);
try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, quiet, &.{like}));
const racing = try ci.beginResync(alice);
try ci.addCollection(alice, follow);
try t.expectEqual(CollectionIndex.ResyncResult.merged, try ci.finishResync(alice, racing, &.{post}));
var bytes: [256]u8 = undefined;
var spans: [4]Span = undefined;
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection(follow, 4, null, &bytes, &spans)).count);
try t.expectEqual(@as(usize, 1), (try ci.listReposByCollection(post, 4, null, &bytes, &spans)).count);
try t.expectEqual(@as(usize, 2), (try ci.listReposByCollection(like, 4, null, &bytes, &spans)).count);
const converge = try ci.beginResync(alice);
try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, converge, &.{follow}));
try t.expectEqual(@as(usize, 0), (try ci.listReposByCollection(post, 4, null, &bytes, &spans)).count);
const duplicate = try ci.beginResync(alice);
try ci.addCollection(alice, follow);
try t.expectEqual(CollectionIndex.ResyncResult.merged, try ci.finishResync(alice, duplicate, &.{}));
try t.expect(try ci.hasCollectionsChecked(alice));
const deleted = try ci.beginResync(alice);
try ci.removeAll(alice);
try t.expectEqual(CollectionIndex.ResyncResult.superseded, try ci.finishResync(alice, deleted, &.{post}));
try t.expect(!(try ci.hasCollectionsChecked(alice)));
const canceled = try ci.beginResync(alice);
try t.expectError(error.ResyncBusy, ci.beginResync("did:plc:bob"));
ci.cancelResync(canceled);
const current = try ci.beginResync(alice);
ci.cancelResync(canceled);
try t.expectEqual(CollectionIndex.ResyncResult.superseded, try ci.finishResync(alice, canceled, &.{like}));
try t.expectEqual(CollectionIndex.ResyncResult.replaced, try ci.finishResync(alice, current, &.{post}));
try t.expect(try ci.hasCollectionsChecked(alice));
}
}
test "collection index: bounded log policy flushes and recovers acknowledged pairs" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 8, .max_memtable_bytes = 1 << 20 };
for (0..9) |i| {
var bytes: [64]u8 = undefined;
const id = try std.fmt.bufPrint(&bytes, "did:plc:{d}", .{i});
try ci.addCollection(id, "app.bsky.feed.post");
}
try t.expectEqual(@as(usize, 1), ci.maintenance_runs);
try t.expectEqual(@as(u64, 8), ci.maintenance_detail.flushed_segments);
try t.expectEqual(@as(u64, 2), ci.db.unflushedSegments());
}
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
for (0..9) |i| {
var bytes: [64]u8 = undefined;
const id = try std.fmt.bufPrint(&bytes, "did:plc:{d}", .{i});
try t.expect(try ci.hasCollectionsChecked(id));
}
ci.maintenance_policy = .{ .max_segments = 4096, .max_memtable_bytes = 1 };
try ci.addCollection("did:plc:byte-limit", "app.bsky.feed.post");
try t.expectEqual(@as(usize, 1), ci.maintenance_runs);
try t.expectEqual(@as(u64, 0), ci.db.unflushedSegments());
}
test "stepped maintenance returns with pending work and preserves acknowledged pairs" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 1, .step_bytes = 1 };
ci.db.options.l0_tables = 1;
ci.db.options.table_bytes = 1;
ci.db.options.block_bytes = 1;
const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
try ci.addCollectionPage(&ids, "app.bsky.feed.post");
try t.expect(ci.db.compaction != null);
try t.expect(ci.maintenance_detail.compaction_steps > 0);
var bytes: [4096]u8 = undefined;
var spans: [100]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
try t.expectEqual(@as(usize, 3), page.count);
for (ids, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
while (try ci.db.compact()) {}
try ci.db.collect();
}
test "deferred maintenance drains while idle and fresh readers see acknowledged pairs" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
ci.db.options.l0_tables = 1;
ci.db.options.table_bytes = 1;
ci.db.options.block_bytes = 1;
try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true });
const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
try ci.addCollectionPage(&ids, "app.bsky.feed.post");
var bytes: [4096]u8 = undefined;
var spans: [100]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
try t.expectEqual(@as(usize, 3), page.count);
for (ids, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
ci.write_owner.?.close();
try t.expect(ci.db.compaction == null);
try t.expectEqual(@as(usize, 0), ci.db.version.tables[0].len);
try t.expectEqual(@as(u64, 0), ci.db.unflushedSegments());
try t.expect(ci.maintenance_detail.compaction_steps > 1);
}
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
for ([_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" }) |id| try t.expect(try ci.hasCollectionsChecked(id));
}
test "deferred maintenance failure preserves an acknowledgement and rejects later writes" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
const obstacle = try dir.dir.createFile(t.io, "sst", .{});
obstacle.close(t.io);
try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true });
try ci.addCollection("did:plc:acknowledged", "app.bsky.feed.post");
try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
try t.expectError(error.IndexUnavailable, ci.hasCollectionsChecked("did:plc:acknowledged"));
ci.write_owner.?.close();
try t.expectEqual(@as(usize, 1), ci.maintenance_detail.changed_commits);
}
try dir.dir.deleteFile(t.io, "sst");
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try t.expect(try ci.hasCollectionsChecked("did:plc:acknowledged"));
try t.expect(!try ci.hasCollectionsChecked("did:plc:later"));
var bytes: [4096]u8 = undefined;
var spans: [100]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
try t.expectEqual(@as(usize, 1), page.count);
try t.expectEqualStrings("did:plc:acknowledged", page.getDid(0));
}
test "page worker bounds admission and drains borrowed output buffers" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try t.expectError(error.InvalidBatchPolicy, ci.enablePageWorker(0));
try ci.enablePageWorker(1);
try t.expectError(error.AlreadyStarted, ci.enablePageWorker(1));
var bytes: [256]u8 = undefined;
var offsets: [2]Span = undefined;
var result: ListResult = undefined;
var request: CollectionIndex.PageOwner.Request = .{ .item = .{ .collection = "app.bsky.feed.post", .limit = 2, .cursor = null, .bytes = &bytes, .offsets = &offsets, .result = &result } };
ci.read_mutex.lockUncancelable(t.io);
var locked = true;
defer if (locked) ci.read_mutex.unlock(t.io);
try ci.page_owner.?.submit(&request);
var rejected: CollectionIndex.PageOwner.Request = .{ .item = request.item };
try t.expectError(error.QueueFull, ci.page_owner.?.submit(&rejected));
try t.expect(!request.done.isSet());
ci.read_mutex.unlock(t.io);
locked = false;
ci.page_owner.?.close();
try t.expect(ci.page_owner.?.thread == null);
try t.expectEqual(@as(usize, 0), ci.page_owner.?.outstanding);
try t.expect(request.done.isSet());
try request.outcome;
try t.expectEqual(@as(usize, 1), result.count);
try t.expect(result.buf.ptr == bytes[0..].ptr);
try t.expectEqualStrings("did:plc:alice", result.getDid(0));
try t.expectError(error.Closed, ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets));
}
test "page worker propagates a missing manifest and serves later recovered reads" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.addCollection("did:plc:alice", "app.bsky.feed.post");
try ci.enablePageWorker(2);
try dir.dir.rename("manifest", dir.dir, "manifest.saved", t.io);
var bytes: [256]u8 = undefined;
var offsets: [2]Span = undefined;
try t.expectError(error.ReaderRetryExhausted, ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets));
try dir.dir.rename("manifest.saved", dir.dir, "manifest", t.io);
const page = try ci.listReposByCollection("app.bsky.feed.post", 2, null, &bytes, &offsets);
try t.expectEqual(@as(usize, 1), page.count);
try t.expectEqualStrings("did:plc:alice", page.getDid(0));
}
test "log collection schedules a second sweep after an interleaved flush" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_after_ack = true;
ci.maintenance_policy = .{ .max_segments = 1, .log_gc_names = 1 };
try ci.addCollection("did:plc:a", "app.bsky.feed.post");
_ = try ci.maintain();
try t.expect(ci.log_gc_pending);
try t.expect(ci.log_collector.names != null);
try ci.addCollection("did:plc:b", "app.bsky.feed.post");
_ = try ci.maintain();
try t.expect(ci.log_gc_pending);
var steps: usize = 0;
while (try ci.maintain() != .idle) {
steps += 1;
try t.expect(steps < 32);
}
try t.expect(!ci.log_gc_pending);
try t.expect(ci.log_collector.names == null);
const names = try ci.store.list(t.allocator, "log/");
defer zkv.freeNames(t.allocator, names);
try t.expectEqual(@as(usize, 1), names.len);
try t.expect(try ci.hasCollectionsChecked("did:plc:a"));
try t.expect(try ci.hasCollectionsChecked("did:plc:b"));
}
test "bounded log maintenance drains with idle pending writes and reopens" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.db.options.l0_tables = 1;
ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 64, .log_gc_names = 1 };
try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
for (0..32) |i| {
var buffer: [32]u8 = undefined;
const id = try std.fmt.bufPrint(&buffer, "did:plc:{d}", .{i});
try ci.addCollection(id, "app.bsky.feed.post");
}
ci.write_owner.?.close();
try t.expect(!ci.log_gc_pending);
try t.expect(ci.log_collector.names == null);
try t.expect(ci.db.compaction == null);
try t.expect(ci.maintenance_detail.log_gc_steps > 0);
try t.expect(ci.maintenance_store.writes > 0);
}
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
for (0..32) |i| {
var buffer: [32]u8 = undefined;
const id = try std.fmt.bufPrint(&buffer, "did:plc:{d}", .{i});
try t.expect(try ci.hasCollectionsChecked(id));
}
}
test "pending SST writes wake the idle owner and survive shutdown and reopen" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
{
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
ci.db.options.l0_tables = 1;
ci.db.options.table_bytes = 1;
ci.db.options.block_bytes = 1;
try t.expectError(error.InvalidBatchPolicy, ci.enableBatching(.{ .background_writes = true }));
try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
const ids = [_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" };
try ci.addCollectionPage(&ids, "app.bsky.feed.post");
for (ids) |id| try t.expect(try ci.hasCollectionsChecked(id));
ci.write_owner.?.close();
try t.expect(ci.db.compaction == null);
try t.expect(ci.async_store.pending == null);
try t.expect(ci.maintenance_detail.pending_polls > 0);
try t.expectEqual(@as(usize, 0), ci.db.version.tables[0].len);
}
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
var bytes: [4096]u8 = undefined;
var spans: [100]Span = undefined;
const page = try ci.listReposByCollection("app.bsky.feed.post", 100, null, &bytes, &spans);
try t.expectEqual(@as(usize, 3), page.count);
for ([_][]const u8{ "did:plc:a", "did:plc:b", "did:plc:c" }, 0..) |id, i| try t.expectEqualStrings(id, page.getDid(i));
}
test "background concurrency failure preserves acknowledged pairs and stops later writes" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var acknowledged: usize = 0;
{
var limited = Io.Threaded.init(t.allocator, .{ .concurrent_limit = .nothing });
defer limited.deinit();
var ci = try CollectionIndex.openWithReaderIo(t.allocator, limited.io(), t.io, path);
defer ci.deinit();
ci.maintenance_policy = .{ .max_segments = 2, .step_bytes = 1 };
ci.db.options.l0_tables = 1;
ci.db.options.table_bytes = 1;
ci.db.options.block_bytes = 1;
try ci.enableBatching(.{ .delay_ns = 0, .maintenance_after_ack = true, .background_writes = true });
var failed = false;
for (0..16) |i| {
var buf: [64]u8 = undefined;
const did = try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i});
ci.addCollection(did, "app.bsky.feed.post") catch |err| {
try t.expectEqual(error.IndexUnavailable, err);
failed = true;
break;
};
acknowledged += 1;
}
try t.expect(failed);
try t.expect(acknowledged > 0);
try t.expectError(error.IndexUnavailable, ci.addCollection("did:plc:later", "app.bsky.feed.post"));
ci.write_owner.?.close();
try t.expect(ci.async_store.pending == null);
}
var ci = try CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
for (0..16) |i| {
var buf: [64]u8 = undefined;
const did = try std.fmt.bufPrint(&buf, "did:plc:{d:0>24}", .{i});
try t.expectEqual(i < acknowledged, try ci.hasCollectionsChecked(did));
}
try t.expect(!try ci.hasCollectionsChecked("did:plc:later"));
}