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
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
//! relay broadcaster — fan-out firehose frames to downstream consumers
//!
//! features:
//! - ref-counted shared frames (one copy per broadcast, not per consumer)
//! - ConsumerTooSlow CBOR error frame before disconnect
//! - ping/pong keepalive (30s idle, 5s deadline)
//! - non-blocking broadcast via per-consumer ring buffers + write threads
//! - health/stats HTTP endpoints via websocket handshake routing
const std = @import("std");
const Io = std.Io;
const websocket = @import("websocket");
const zat = @import("zat");
const ring_buffer = @import("util/ring_buffer.zig");
const event_log_mod = @import("event_log.zig");
const builtin = @import("builtin");
const build_options = @import("build_options");
const util = @import("util/util.zig");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.relay);
const timestamp = util.timestamp;
// --- stats ---
pub const Stats = struct {
replay_frame: @import("util/duration_profile.zig").DurationProfile = .{},
replay_validate: @import("util/duration_profile.zig").DurationProfile = .{},
replay_index: @import("util/duration_profile.zig").DurationProfile = .{},
replay_post_index: @import("util/duration_profile.zig").DurationProfile = .{},
seq: std.atomic.Value(u64) = .{ .raw = 0 },
relay_seq: std.atomic.Value(u64) = .{ .raw = 0 },
consumer_count: std.atomic.Value(u64) = .{ .raw = 0 },
frames_in: std.atomic.Value(u64) = .{ .raw = 0 },
frames_out: std.atomic.Value(u64) = .{ .raw = 0 },
validated: std.atomic.Value(u64) = .{ .raw = 0 },
failed: std.atomic.Value(u64) = .{ .raw = 0 },
// per-reason failure breakdown (subsets of `failed`)
failed_bad_did: std.atomic.Value(u64) = .{ .raw = 0 },
failed_bad_rev: std.atomic.Value(u64) = .{ .raw = 0 },
failed_missing_blocks: std.atomic.Value(u64) = .{ .raw = 0 },
failed_oversized_blocks: std.atomic.Value(u64) = .{ .raw = 0 },
failed_bad_structure: std.atomic.Value(u64) = .{ .raw = 0 },
failed_signature: std.atomic.Value(u64) = .{ .raw = 0 },
failed_commit_integrity: std.atomic.Value(u64) = .{ .raw = 0 },
// Proof failures split by cause, because they mean opposite things: a
// sender that omitted prevData is behaving as expected for a pre-Sync-1.1
// PDS, while a proof that fails to invert means the commit or our
// verification is wrong. Counting both as sync_1_1 hid a zat MST bug that
// was dropping valid commits at 5% of validated traffic.
failed_sync_1_1: std.atomic.Value(u64) = .{ .raw = 0 },
failed_prev_data_missing: std.atomic.Value(u64) = .{ .raw = 0 },
failed_host_authority: std.atomic.Value(u64) = .{ .raw = 0 },
failed_future_rev: std.atomic.Value(u64) = .{ .raw = 0 },
skipped: std.atomic.Value(u64) = .{ .raw = 0 },
rate_limited: std.atomic.Value(u64) = .{ .raw = 0 },
rate_limited_sec: std.atomic.Value(u64) = .{ .raw = 0 },
rate_limited_hour: std.atomic.Value(u64) = .{ .raw = 0 },
rate_limited_day: std.atomic.Value(u64) = .{ .raw = 0 },
decode_errors: std.atomic.Value(u64) = .{ .raw = 0 },
cache_hits: std.atomic.Value(u64) = .{ .raw = 0 },
cache_misses: std.atomic.Value(u64) = .{ .raw = 0 },
slow_consumers: std.atomic.Value(u64) = .{ .raw = 0 },
connected_inbound: std.atomic.Value(u64) = .{ .raw = 0 },
cache_evictions: std.atomic.Value(u64) = .{ .raw = 0 },
// chain continuity failures by reason (since vs stored rev, prevData vs stored data CID)
chain_breaks_since: std.atomic.Value(u64) = .{ .raw = 0 },
chain_breaks_prev_data: std.atomic.Value(u64) = .{ .raw = 0 },
pool_backpressure: std.atomic.Value(u64) = .{ .raw = 0 },
// keepalive pinger (ws_ping.zig) — pings sent, connections torn down for
// unanswered pings, and ping writes that themselves failed
ws_pings_sent: std.atomic.Value(u64) = .{ .raw = 0 },
ws_ping_timeout_closes: std.atomic.Value(u64) = .{ .raw = 0 },
ws_ping_write_failures: std.atomic.Value(u64) = .{ .raw = 0 },
// host authority resolution metrics
host_authority_checks: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_is_new: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_host_changed: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_time_us: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_cache_hits: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_network_checks: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_network_time_us: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_pool_wait_us: std.atomic.Value(u64) = .{ .raw = 0 },
// per-branch reject breakdown (subsets of failed_host_authority).
// lets us tell whether rejects come from stale cached forgeries
// (host_mismatch), genuinely forged DIDs (resolve/no_endpoint),
// or a mismatch between DID doc endpoint and our host table.
host_authority_reject_parse_did: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_reject_resolve: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_reject_no_endpoint: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_reject_bad_url: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_reject_unknown_host: std.atomic.Value(u64) = .{ .raw = 0 },
host_authority_reject_host_mismatch: std.atomic.Value(u64) = .{ .raw = 0 },
// subscriber reconnect-cycle disconnect breakdown. only handshake-or-earlier
// failures accumulate to failed_attempts (reset_failures fires after
// ws_handshake succeeds, before read_loop). 15 consecutive of these →
// host moves to 'exhausted'. read_loop disconnects do not directly
// exhaust unless the next handshake also fails.
subscriber_disconnect_dns_connect: std.atomic.Value(u64) = .{ .raw = 0 },
subscriber_disconnect_tls_init: std.atomic.Value(u64) = .{ .raw = 0 },
subscriber_disconnect_ws_handshake: std.atomic.Value(u64) = .{ .raw = 0 },
subscriber_disconnect_read_loop: std.atomic.Value(u64) = .{ .raw = 0 },
// frame pool memory pressure
pool_queued_bytes: std.atomic.Value(u64) = .{ .raw = 0 },
// persist/broadcast pipeline contention
persist_order_spins: std.atomic.Value(u64) = .{ .raw = 0 },
broadcast_queue_push_lock_spins: std.atomic.Value(u64) = .{ .raw = 0 },
broadcast_queue_full: std.atomic.Value(u64) = .{ .raw = 0 },
broadcast_queue_depth_hwm: std.atomic.Value(u32) = .{ .raw = 0 },
broadcast_no_consumers: std.atomic.Value(u64) = .{ .raw = 0 },
// backoff sleeps taken while the ring was full, the ordering lock was
// held, or a replay waited for consumer buffer space. these advance while
// the wait is in progress, so a stall is visible on /metrics as it happens.
broadcast_queue_full_waits: std.atomic.Value(u64) = .{ .raw = 0 },
persist_order_waits: std.atomic.Value(u64) = .{ .raw = 0 },
replay_buffer_waits: std.atomic.Value(u64) = .{ .raw = 0 },
start_time: i64 = 0,
};
/// spin briefly, then sleep between retries. `attempt` is the caller's retry
/// count: the first `backoff_spin_budget` retries only hint the CPU, every
/// later one sleeps so the waiter stops competing for CPU with whatever it is
/// waiting for. under zio the sleep also yields the scheduler to other fibers.
const backoff_spin_budget: u32 = 64;
const backoff_sleep = Io.Duration.fromMilliseconds(1);
fn backoff(attempt: u32, waits: *std.atomic.Value(u64), io: Io) void {
if (attempt <= backoff_spin_budget) {
std.atomic.spinLoopHint();
return;
}
_ = waits.fetchAdd(1, .monotonic);
io.sleep(backoff_sleep, .awake) catch std.atomic.spinLoopHint();
}
// --- shared frame (ref-counted) ---
pub const SharedFrame = struct {
data: []const u8,
ref_count: std.atomic.Value(u32),
allocator: Allocator,
pub fn create(allocator: Allocator, data: []const u8) !*SharedFrame {
const frame = try allocator.create(SharedFrame);
const duped = try allocator.dupe(u8, data);
frame.* = .{
.data = duped,
.ref_count = .{ .raw = 1 },
.allocator = allocator,
};
return frame;
}
pub fn acquire(self: *SharedFrame) void {
_ = self.ref_count.fetchAdd(1, .monotonic);
}
pub fn release(self: *SharedFrame) void {
if (self.ref_count.fetchSub(1, .acq_rel) == 1) {
self.allocator.free(self.data);
self.allocator.destroy(self);
}
}
};
// --- ConsumerTooSlow error frame ---
/// build the ConsumerTooSlow CBOR error frame using the SDK encoder.
/// header: {op: -1}, payload: {error: "ConsumerTooSlow", message: "..."}
fn buildErrorFrame(allocator: Allocator) ?[]const u8 {
const cbor = zat.cbor;
// header: {op: -1} — spec says no `t` field on error frames
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .negative = -1 } },
} };
// payload: {error: "ConsumerTooSlow", message: "consumer buffer full"}
const payload: cbor.Value = .{ .map = &.{
.{ .key = "error", .value = .{ .text = "ConsumerTooSlow" } },
.{ .key = "message", .value = .{ .text = "consumer buffer full" } },
} };
const header_bytes = cbor.encodeAlloc(allocator, header) catch return null;
const payload_bytes = cbor.encodeAlloc(allocator, payload) catch {
allocator.free(header_bytes);
return null;
};
var frame = allocator.alloc(u8, header_bytes.len + payload_bytes.len) catch {
allocator.free(header_bytes);
allocator.free(payload_bytes);
return null;
};
@memcpy(frame[0..header_bytes.len], header_bytes);
@memcpy(frame[header_bytes.len..], payload_bytes);
allocator.free(header_bytes);
allocator.free(payload_bytes);
return frame;
}
/// encode an error frame into caller-provided buffer.
/// used for InvalidCursor / FutureCursor error frames.
/// header: {op: -1}, payload: {error: <name>, message: <msg>}
fn encodeErrorFrame(error_name: []const u8, message: []const u8, out: []u8) ?[]const u8 {
const cbor = zat.cbor;
const alloc = std.heap.c_allocator;
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .negative = -1 } },
} };
const payload: cbor.Value = .{ .map = &.{
.{ .key = "error", .value = .{ .text = error_name } },
.{ .key = "message", .value = .{ .text = message } },
} };
const header_bytes = cbor.encodeAlloc(alloc, header) catch return null;
defer alloc.free(header_bytes);
const payload_bytes = cbor.encodeAlloc(alloc, payload) catch return null;
defer alloc.free(payload_bytes);
const total = header_bytes.len + payload_bytes.len;
if (total > out.len) return null;
@memcpy(out[0..header_bytes.len], header_bytes);
@memcpy(out[header_bytes.len..][0..payload_bytes.len], payload_bytes);
return out[0..total];
}
/// encode an #info message frame into caller-provided buffer.
/// used for OutdatedCursor. this is a message frame (op: 1), not an error frame.
/// header: {op: 1, t: "#info"}, payload: {name: <name>, message: <msg>}
fn encodeInfoMessage(name: []const u8, message: []const u8, out: []u8) ?[]const u8 {
const cbor = zat.cbor;
const alloc = std.heap.c_allocator;
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = "#info" } },
} };
const payload: cbor.Value = .{ .map = &.{
.{ .key = "name", .value = .{ .text = name } },
.{ .key = "message", .value = .{ .text = message } },
} };
const header_bytes = cbor.encodeAlloc(alloc, header) catch return null;
defer alloc.free(header_bytes);
const payload_bytes = cbor.encodeAlloc(alloc, payload) catch return null;
defer alloc.free(payload_bytes);
const total = header_bytes.len + payload_bytes.len;
if (total > out.len) return null;
@memcpy(out[0..header_bytes.len], header_bytes);
@memcpy(out[header_bytes.len..][0..payload_bytes.len], payload_bytes);
return out[0..total];
}
// --- frame re-sequencing ---
/// resequence a firehose frame: replace the payload's "seq" with relay_seq.
/// header bytes are preserved as-is, only the payload is re-encoded.
/// returns null on decode failure; caller owns returned memory via allocator.
pub fn resequenceFrame(allocator: Allocator, data: []const u8, relay_seq: u64) ?[]u8 {
const cbor = zat.cbor;
// split frame: [header CBOR] [payload CBOR]
const header_result = cbor.decode(allocator, data) catch return null;
const header_end = header_result.consumed;
const payload_data = data[header_end..];
// check header type — commit frames need tooBig normalization
const is_commit = blk: {
const header_val = switch (header_result.value) {
.map => |entries| entries,
else => break :blk false,
};
for (header_val) |entry| {
if (std.mem.eql(u8, entry.key, "t")) {
const t = switch (entry.value) {
.text => |s| s,
else => break :blk false,
};
break :blk std.mem.eql(u8, t, "#commit");
}
}
break :blk false;
};
// decode payload map
const payload = cbor.decodeAll(allocator, payload_data) catch return null;
const old_entries = switch (payload) {
.map => |entries| entries,
else => return null,
};
// rebuild map entries with seq replaced
var new_entries: std.ArrayListUnmanaged(cbor.Value.MapEntry) = .empty;
var found_seq = false;
var found_too_big = false;
var found_rebase = false;
for (old_entries) |entry| {
if (std.mem.eql(u8, entry.key, "seq")) {
new_entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = relay_seq } }) catch return null;
found_seq = true;
} else {
if (std.mem.eql(u8, entry.key, "tooBig")) found_too_big = true;
if (std.mem.eql(u8, entry.key, "rebase")) found_rebase = true;
new_entries.append(allocator, entry) catch return null;
}
}
if (!found_seq) {
new_entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = relay_seq } }) catch return null;
}
// lexicon requires tooBig on #commit — some PDSes omit it, hydrant et al. reject the frame
if (is_commit and !found_too_big) {
new_entries.append(allocator, .{ .key = "tooBig", .value = .{ .boolean = false } }) catch return null;
}
if (is_commit and !found_rebase) {
new_entries.append(allocator, .{ .key = "rebase", .value = .{ .boolean = false } }) catch return null;
}
const new_payload: cbor.Value = .{ .map = new_entries.items };
const new_payload_bytes = cbor.encodeAlloc(allocator, new_payload) catch return null;
// combine: original header bytes + resequenced payload
var result = allocator.alloc(u8, header_end + new_payload_bytes.len) catch return null;
@memcpy(result[0..header_end], data[0..header_end]);
@memcpy(result[header_end..], new_payload_bytes);
return result;
}
// --- broadcast queue (worker → fiber handoff) ---
/// item produced by frame workers, consumed by the broadcaster fiber.
/// data is heap-allocated by the worker; the broadcaster fiber frees it after broadcast.
pub const BroadcastItem = struct {
seq: u64,
data: []const u8,
};
/// MPSC ring buffer: multiple frame worker threads push, one broadcaster fiber pops.
/// uses an atomic spinlock for push (no Io.Mutex — works from any execution context).
/// pop is single-consumer (broadcaster fiber only), no locking needed.
pub const BroadcastQueue = struct {
const CAPACITY = 8192;
items: [CAPACITY]BroadcastItem = undefined,
head: std.atomic.Value(u32) = .{ .raw = 0 },
tail: std.atomic.Value(u32) = .{ .raw = 0 },
push_lock: std.atomic.Value(u32) = .{ .raw = 0 },
allocator: Allocator,
pub fn init(allocator: Allocator) BroadcastQueue {
return .{ .allocator = allocator };
}
/// approximate queue depth (may be slightly stale — for metrics only)
pub fn depth(self: *const BroadcastQueue) u32 {
const tail = self.tail.load(.monotonic);
const head = self.head.load(.monotonic);
return if (tail >= head) tail - head else CAPACITY - head + tail;
}
/// push an item (called by worker threads). waits until space is available.
/// matches Indigo semantics: every persisted event reaches live broadcast.
/// a full ring means the broadcaster is not draining, and a producer that
/// spins competes with it for the CPU it needs to drain (2026-10-18: 16
/// producers spun on 8 vCPUs for an hour). after a short spin budget the
/// producer sleeps between retries instead.
pub fn push(self: *BroadcastQueue, seq: u64, data: []const u8, stats: *Stats, io: Io) void {
var full_spins: u32 = 0;
while (true) {
// acquire spinlock
var lock_spins: u32 = 0;
while (self.push_lock.cmpxchgWeak(0, 1, .acquire, .monotonic) != null) {
lock_spins += 1;
std.atomic.spinLoopHint();
}
if (lock_spins > 0) {
_ = stats.broadcast_queue_push_lock_spins.fetchAdd(lock_spins, .monotonic);
}
const tail = self.tail.load(.monotonic);
const next_tail = (tail + 1) % CAPACITY;
if (next_tail == self.head.load(.acquire)) {
// full — release lock, back off, retry. the counter advances
// per retry so the stall is visible while it lasts; saturating
// add so a long stall can never panic the worker.
self.push_lock.store(0, .release);
_ = stats.broadcast_queue_full.fetchAdd(1, .monotonic);
full_spins +|= 1;
backoff(full_spins, &stats.broadcast_queue_full_waits, io);
continue;
}
self.items[tail] = .{ .seq = seq, .data = data };
self.tail.store(next_tail, .release);
self.push_lock.store(0, .release);
// update high-water mark (racy but directionally correct)
const d = self.depth();
const hwm = stats.broadcast_queue_depth_hwm.load(.monotonic);
if (d > hwm) {
_ = stats.broadcast_queue_depth_hwm.cmpxchgWeak(hwm, d, .monotonic, .monotonic);
}
return;
}
}
/// peek the seq at the head without removing it (broadcaster fiber only).
/// used to gate emission on the durable watermark. null if empty.
pub fn peekSeq(self: *BroadcastQueue) ?u64 {
const head = self.head.load(.monotonic);
if (head == self.tail.load(.acquire)) return null; // empty
return self.items[head].seq;
}
/// pop an item (called by broadcaster fiber only). returns null if empty.
pub fn pop(self: *BroadcastQueue) ?BroadcastItem {
const head = self.head.load(.monotonic);
if (head == self.tail.load(.acquire)) return null; // empty
const item = self.items[head];
self.head.store((head + 1) % CAPACITY, .release);
return item;
}
};
// --- consumer ---
const ping_interval_ns: u64 = 30 * std.time.ns_per_s;
const ping_timeout_ns: u64 = 5 * std.time.ns_per_s;
/// how long a replay waits for the consumer to drain before retrying an enqueue
const replay_wait_sleep = Io.Duration.fromMilliseconds(10);
pub const Consumer = struct {
const BUFFER_CAP = 65536;
conn: *websocket.Conn,
allocator: Allocator,
buf: [BUFFER_CAP]*SharedFrame = undefined,
write_pos: usize = 0,
read_pos: usize = 0,
buf_len: usize = 0,
alive: std.atomic.Value(bool) = .{ .raw = true },
mutex: Io.Mutex = Io.Mutex.init,
cond: Io.Condition = Io.Condition.init,
future: ?Io.Future(void) = null,
last_send_time: i128 = 0,
io: Io,
/// set while a cursor replay is in progress. broadcast() skips a replaying
/// consumer entirely (no live enqueue, no slow-consumer kick): the replay
/// delivers from disk at the consumer's own pace and hands off to live
/// once it has caught up. see Broadcaster.replayTo.
replaying: std.atomic.Value(bool) = .{ .raw = false },
/// replay → live handoff window: live frames are parked in `pending` with
/// their seq until the final catch-up chunk is in `buf`, then moved over in
/// order (dropping any the catch-up already delivered). guarded by `mutex`.
staging: bool = false,
pending: std.ArrayListUnmanaged(PendingFrame) = .empty,
/// set by dropSlowConsumer. writeLoop sends ConsumerTooSlow on its way
/// out (best effort) so the broadcaster never writes to a consumer socket.
kicked: std.atomic.Value(bool) = .{ .raw = false },
error_frame: ?[]const u8 = null,
const PendingFrame = struct { seq: u64, frame: *SharedFrame };
/// push a shared frame to this consumer's send buffer.
/// acquires a reference. returns false if full (consumer too slow) or
/// dead — a disconnected consumer must not keep accumulating frames
/// (replay for a flapping consumer compounded into an OOM otherwise).
pub fn enqueue(self: *Consumer, frame: *SharedFrame) bool {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (!self.alive.load(.acquire)) return false;
return self.enqueueLocked(frame);
}
fn enqueueLocked(self: *Consumer, frame: *SharedFrame) bool {
if (self.buf_len == BUFFER_CAP) return false;
frame.acquire();
self.buf[self.write_pos] = frame;
self.write_pos = (self.write_pos + 1) % BUFFER_CAP;
self.buf_len += 1;
self.cond.signal(self.io);
return true;
}
/// live-path enqueue from broadcast(). during the replay → live handoff
/// the frame is parked in `pending` instead of `buf`.
pub fn enqueueLive(self: *Consumer, seq: u64, frame: *SharedFrame) bool {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (!self.alive.load(.acquire)) return false;
if (self.staging) {
if (self.pending.items.len >= BUFFER_CAP) return false;
self.pending.append(self.allocator, .{ .seq = seq, .frame = frame }) catch return false;
frame.acquire();
return true;
}
return self.enqueueLocked(frame);
}
/// replay enqueue: waits for buffer space instead of failing, so a
/// consumer slower than disk playback gets a slower replay rather than a
/// kick. returns false only when the consumer is dead or the relay is
/// shutting down.
pub fn enqueueRawWait(self: *Consumer, data: []const u8, shutdown_flag: *const std.atomic.Value(bool), waits: *std.atomic.Value(u64)) bool {
const frame = SharedFrame.create(self.allocator, data) catch return false;
defer frame.release();
while (self.alive.load(.acquire) and !shutdown_flag.load(.acquire)) {
if (self.enqueue(frame)) return true;
_ = waits.fetchAdd(1, .monotonic);
self.io.sleep(replay_wait_sleep, .awake) catch return false;
}
return false;
}
/// disk is drained: park live frames in `pending` while the final
/// catch-up chunk is enqueued.
fn beginStaging(self: *Consumer) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
self.staging = true;
self.replaying.store(false, .release);
}
/// move parked live frames newer than `since` (the last replayed seq) into
/// `buf`, in order, and resume direct live delivery. returns false if `buf`
/// cannot take them: the consumer is too slow for live and the caller kicks it.
fn finishStaging(self: *Consumer, since: u64) bool {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
var ok = true;
for (self.pending.items) |p| {
defer p.frame.release();
if (p.seq <= since) continue;
if (ok and !self.enqueueLocked(p.frame)) ok = false;
}
self.pending.clearAndFree(self.allocator);
self.staging = false;
return ok;
}
/// drop parked frames (replay aborted, or the consumer is going away).
fn abortStaging(self: *Consumer) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
self.releasePendingLocked();
}
fn releasePendingLocked(self: *Consumer) void {
for (self.pending.items) |p| p.frame.release();
self.pending.clearAndFree(self.allocator);
self.staging = false;
}
pub fn deinit(self: *Consumer) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
self.releasePendingLocked();
}
/// push raw bytes (for replay, error frames). allocates a new SharedFrame.
pub fn enqueueRaw(self: *Consumer, data: []const u8) bool {
const frame = SharedFrame.create(self.allocator, data) catch return false;
// enqueue will acquire, so we start with refcount 1 (for our ownership)
// then release our ownership after enqueue
if (self.enqueue(frame)) {
frame.release(); // drop our ref, consumer write loop holds one
return true;
}
frame.release();
return false;
}
fn dequeue(self: *Consumer) ?*SharedFrame {
// caller must hold mutex
if (self.buf_len == 0) return null;
const frame = self.buf[self.read_pos];
self.read_pos = (self.read_pos + 1) % BUFFER_CAP;
self.buf_len -= 1;
return frame;
}
fn writeLoop(self: *Consumer) void {
self.last_send_time = Io.Timestamp.now(self.io, .real).nanoseconds;
while (self.alive.load(.acquire)) {
var frame: ?*SharedFrame = null;
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (self.buf_len == 0) {
// no data: poll briefly instead of blocking on cond
// (Io.Condition has no timedWait, so we poll to allow periodic ping checks)
self.mutex.unlock(self.io);
self.io.sleep(Io.Duration.fromMilliseconds(100), .awake) catch {};
self.mutex.lockUncancelable(self.io);
}
frame = self.dequeue();
}
if (frame) |f| {
defer f.release();
self.conn.writeBin(f.data) catch {
self.alive.store(false, .release);
break;
};
self.last_send_time = Io.Timestamp.now(self.io, .real).nanoseconds;
} else {
// no data — check if we should send a ping
self.maybePing();
}
}
// drain remaining buffered frames
while (true) {
self.mutex.lockUncancelable(self.io);
const frame = self.dequeue();
self.mutex.unlock(self.io);
if (frame) |f| {
f.release();
} else break;
}
self.abortStaging();
// a kicked consumer gets ConsumerTooSlow before the close, from this
// fiber only: its socket is full by definition, and the broadcaster
// must never park on it (2026-10-18).
if (self.kicked.load(.acquire)) {
if (self.error_frame) |ef| self.conn.writeBin(ef) catch {};
}
// unblock readLoop, which is parked on this socket and owns its close.
// this MUST happen here, not from the broadcast thread, which would
// race readLoop's setsockopt/read calls on the socket.
if (!self.conn.isClosed()) {
self.conn.writeClose(.{}) catch {};
util.net.interrupt(self.io, self.conn.stream);
}
}
fn maybePing(self: *Consumer) void {
const now = Io.Timestamp.now(self.io, .real).nanoseconds;
const elapsed: u64 = @intCast(@max(0, now - self.last_send_time));
if (elapsed >= ping_interval_ns) {
// send ping
self.conn.writePing(&.{}) catch {
self.alive.store(false, .release);
return;
};
self.last_send_time = now;
}
}
pub fn shutdown(self: *Consumer) void {
self.alive.store(false, .release);
self.cond.signal(self.io);
if (self.future) |*f| f.cancel(self.io);
self.future = null;
}
};
// --- broadcaster ---
/// per-chunk bound for disk replay: caps the transient allocation of one
/// consumer connect at ~16 MiB regardless of how much backlog its cursor
/// spans. worst-case per-frame size (5 MiB max_message_size) is still
/// covered: max_bytes is checked before each read, so a chunk holds at most
/// max_bytes + one frame.
const replay_chunk_limits: event_log_mod.PlaybackLimits = .{
.max_entries = 4096,
.max_bytes = 16 * 1024 * 1024,
};
const history_capacity = 50_000;
const FrameHistory = ring_buffer.RingBuffer(history_capacity);
/// function pointer for HTTP fallback handler (set by main.zig)
pub const HttpFallbackFn = *const fn (
*websocket.Conn,
[]const u8,
[]const u8,
[]const u8,
*const websocket.Handshake.KeyValue,
?*anyopaque,
) void;
pub const Broadcaster = struct {
allocator: Allocator,
consumers: std.ArrayListUnmanaged(*Consumer) = .empty,
consumers_mutex: Io.Mutex = Io.Mutex.init,
/// ordering spinlock for persist → queue push atomicity.
/// atomic spinlock (not Io.Mutex) so both Threaded workers and Evented admin
/// can participate in the same ordered publication path.
persist_order: std.atomic.Value(u32) = .{ .raw = 0 },
/// worker → fiber handoff: frame workers push here, broadcaster fiber pops.
broadcast_queue: BroadcastQueue,
history: FrameHistory,
retain_ram_history: bool = true,
persist: ?*event_log_mod.DiskPersist = null,
db_queue: ?*event_log_mod.DbRequestQueue = null,
stats: Stats = .{},
error_frame: ?[]const u8 = null,
http_fallback: ?HttpFallbackFn = null,
http_fallback_ctx: ?*anyopaque = null,
io: Io,
shutdown: *std.atomic.Value(bool),
producers_done: std.atomic.Value(bool) = .{ .raw = false },
pub fn init(allocator: Allocator, io: Io, shutdown: *std.atomic.Value(bool)) Broadcaster {
return .{
.allocator = allocator,
.broadcast_queue = BroadcastQueue.init(allocator),
.history = FrameHistory.init(allocator, io),
.stats = .{ .start_time = timestamp(io) },
.error_frame = buildErrorFrame(allocator),
.io = io,
.shutdown = shutdown,
};
}
pub fn deinit(self: *Broadcaster) void {
self.consumers_mutex.lockUncancelable(self.io);
defer self.consumers_mutex.unlock(self.io);
for (self.consumers.items) |consumer| {
consumer.shutdown();
consumer.deinit();
self.allocator.destroy(consumer);
}
self.consumers.deinit(self.allocator);
self.history.deinit();
if (self.error_frame) |ef| self.allocator.free(ef);
while (self.broadcast_queue.pop()) |item| self.allocator.free(@constCast(item.data));
}
/// `replaying` marks a consumer that connected with a cursor: it is skipped
/// by broadcast() until replayTo hands it off to live.
pub fn addConsumer(self: *Broadcaster, conn: *websocket.Conn, replaying: bool) !*Consumer {
const consumer = try self.allocator.create(Consumer);
consumer.* = .{
.conn = conn,
.allocator = self.allocator,
.io = self.io,
.replaying = .{ .raw = replaying },
.error_frame = self.error_frame,
};
consumer.future = self.io.concurrent(Consumer.writeLoop, .{consumer}) catch {
self.allocator.destroy(consumer);
return error.ThreadSpawnFailed;
};
self.consumers_mutex.lockUncancelable(self.io);
defer self.consumers_mutex.unlock(self.io);
self.consumers.append(self.allocator, consumer) catch {
consumer.shutdown();
self.allocator.destroy(consumer);
return error.OutOfMemory;
};
_ = self.stats.consumer_count.fetchAdd(1, .monotonic);
log.info("consumer connected ({d} total)", .{self.consumers.items.len});
return consumer;
}
pub fn removeConsumer(self: *Broadcaster, consumer: *Consumer) void {
{
self.consumers_mutex.lockUncancelable(self.io);
defer self.consumers_mutex.unlock(self.io);
for (self.consumers.items, 0..) |c, i| {
if (c == consumer) {
_ = self.consumers.swapRemove(i);
// only decrement if we found it — dropSlowConsumer already
// decremented for slow consumers removed during broadcast()
_ = self.stats.consumer_count.fetchSub(1, .monotonic);
break;
}
}
}
consumer.shutdown();
consumer.deinit();
log.info("consumer disconnected ({d} remaining)", .{self.consumers.items.len});
self.allocator.destroy(consumer);
}
/// broadcast a frame to all consumers. non-blocking — just enqueues.
/// drops slow consumers whose buffers are full after sending ConsumerTooSlow.
pub fn broadcast(self: *Broadcaster, seq: u64, data: []const u8) void {
self.stats.seq.store(seq, .release);
// add to history for cursor replay
if (self.retain_ram_history and (self.persist == null or self.persist.?.history_enabled)) _ = self.history.push(seq, data);
// fast path: skip SharedFrame allocation when nobody is listening
if (self.stats.consumer_count.load(.acquire) == 0) {
_ = self.stats.broadcast_no_consumers.fetchAdd(1, .monotonic);
return;
}
// create one shared frame for all consumers
const frame = SharedFrame.create(self.allocator, data) catch return;
defer frame.release(); // release broadcaster's reference
self.consumers_mutex.lockUncancelable(self.io);
defer self.consumers_mutex.unlock(self.io);
var frames_sent: u64 = 0;
var i: usize = 0;
while (i < self.consumers.items.len) {
const consumer = self.consumers.items[i];
if (!consumer.alive.load(.acquire)) {
// remove from broadcast list but don't destroy —
// Handler.close() → removeConsumer() owns cleanup
_ = self.consumers.swapRemove(i);
_ = self.stats.consumer_count.fetchSub(1, .monotonic);
continue;
}
if (consumer.replaying.load(.acquire)) {
// catching up from disk; replayTo delivers and hands off to live
i += 1;
continue;
}
if (consumer.enqueueLive(seq, frame)) {
frames_sent += 1;
} else {
// buffer full — send ConsumerTooSlow error, then drop
self.dropSlowConsumer(consumer);
_ = self.consumers.swapRemove(i);
_ = self.stats.consumer_count.fetchSub(1, .monotonic);
_ = self.stats.slow_consumers.fetchAdd(1, .monotonic);
continue;
}
i += 1;
}
_ = self.stats.frames_out.fetchAdd(frames_sent, .monotonic);
}
fn dropSlowConsumer(self: *Broadcaster, consumer: *Consumer) void {
_ = self;
log.warn("dropping slow consumer (ConsumerTooSlow)", .{});
// never touch the consumer's socket from here. its buffer is full, so
// its socket is full too, and a synchronous error-frame write parked
// the broadcaster (holding consumers_mutex) until that peer read
// (2026-10-18 wedge). writeLoop sends ConsumerTooSlow best effort on
// its way out, then closes — closing from a third thread races
// readLoop's setsockopt/read (EBADF → unreachable under ReleaseSafe).
consumer.kicked.store(true, .release);
consumer.alive.store(false, .release);
consumer.cond.signal(consumer.io);
// consumer is removed from list by broadcast() caller (swapRemove).
// cleanup deferred to removeConsumer to avoid double-destroy.
}
/// cursor replay. the consumer is in the live list but flagged `replaying`,
/// so broadcast() leaves it alone while disk playback runs at the consumer's
/// own pace (a slow reader gets a slow replay, not a kick). once a chunk
/// comes back empty, live frames are parked (`staging`), one more disk pass
/// collects anything broadcast meanwhile (every broadcast frame is on disk
/// first, see runBroadcastLoop), and the parked frames newer than the last
/// replayed seq follow in order. no gap, no reordering, duplicates only at
/// the boundary.
///
/// disk playback runs on pool_io (Threaded) via request/reply, in bounded
/// chunks: materializing the whole backlog per connect is an O(retention)
/// allocation, and a flapping consumer stacking those OOMed the canary
/// (2026-08-06).
pub fn replayTo(self: *Broadcaster, consumer: *Consumer, cursor: u64) void {
if (self.persist) |dp| {
var since = cursor;
var replayed: usize = 0;
if (!self.replayChunks(dp, consumer, &since, &replayed)) {
self.abortReplay(consumer, cursor, replayed);
return;
}
consumer.beginStaging();
if (!self.replayChunks(dp, consumer, &since, &replayed)) {
self.abortReplay(consumer, cursor, replayed);
return;
}
if (!consumer.finishStaging(since)) {
log.warn("replay handoff: consumer too slow for live after {d} frames (cursor={d})", .{ replayed, cursor });
self.dropSlowConsumer(consumer);
return;
}
if (replayed > 0) {
log.info("replayed {d} frames from disk (cursor={d})", .{ replayed, cursor });
}
return;
}
// fallback: in-memory ring buffer (no persist configured). short and
// synchronous, so live frames simply follow it.
self.replayFromMemory(consumer, cursor);
consumer.replaying.store(false, .release);
}
fn abortReplay(self: *Broadcaster, consumer: *Consumer, cursor: u64, replayed: usize) void {
_ = self;
log.warn("replay aborted after {d} frames (consumer dead or shutting down, cursor={d})", .{ replayed, cursor });
consumer.abortStaging();
consumer.replaying.store(false, .release);
}
/// play disk chunks after `since` to the consumer until one comes back
/// empty. advances `since` and `replayed`. returns false when the consumer
/// died or the relay is shutting down.
fn replayChunks(self: *Broadcaster, dp: *event_log_mod.DiskPersist, consumer: *Consumer, since: *u64, replayed: *usize) bool {
while (consumer.alive.load(.acquire) and !self.shutdown.load(.acquire)) {
var req: event_log_mod.PlaybackRequest = .{
.since = since.*,
.allocator = self.allocator,
.limits = replay_chunk_limits,
};
dp.enqueuePlayback(&req);
// poll until pool_io worker completes the request.
// SAFETY: req is stack-local — we MUST wait for the worker to finish before
// returning, otherwise the stack frame unwinds while the worker still holds &req.
// if sleep fails (shutdown/io error), fall back to spin-wait. the host_ops worker
// drains all pending playback requests before exiting, so this is bounded.
while (!req.done.load(.acquire)) {
self.io.sleep(Io.Duration.fromMicroseconds(100), .awake) catch {
while (!req.done.load(.acquire)) std.atomic.spinLoopHint();
break;
};
}
defer {
for (req.entries.items) |e| self.allocator.free(e.data);
req.entries.deinit(self.allocator);
}
if (req.err) |err| {
log.warn("disk replay failed: {s}, falling back to memory", .{@errorName(err)});
self.replayFromMemory(consumer, since.*);
return true;
}
if (req.entries.items.len == 0) return true; // caught up
var reseq_arena = std.heap.ArenaAllocator.init(self.allocator);
defer reseq_arena.deinit();
for (req.entries.items) |entry| {
// resequence: replace upstream seq in CBOR with relay-assigned seq
const frame_data = resequenceFrame(reseq_arena.allocator(), entry.data, entry.seq) orelse entry.data;
if (!consumer.enqueueRawWait(frame_data, self.shutdown, &self.stats.replay_buffer_waits)) {
return false;
}
replayed.* += 1;
since.* = entry.seq;
}
}
return false;
}
fn replayFromMemory(self: *Broadcaster, consumer: *Consumer, cursor: u64) void {
self.history.mutex.lockUncancelable(self.io);
defer self.history.mutex.unlock(self.io);
var i: usize = 0;
while (i < self.history.len) : (i += 1) {
const idx = (self.history.read_pos + i) % history_capacity;
const entry = self.history.entries[idx];
if (entry.seq > cursor) {
if (!consumer.enqueueRaw(entry.data)) break;
}
}
}
pub fn consumerCount(self: *Broadcaster) usize {
self.consumers_mutex.lockUncancelable(self.io);
defer self.consumers_mutex.unlock(self.io);
return self.consumers.items.len;
}
/// take the persist → push ordering lock. spins briefly, then sleeps
/// between retries: the holder may be blocked inside persist (disk mutex)
/// or push (full ring), and spinning producers starve exactly the threads
/// that would release it (2026-10-18: 15 workers spun on the lock while
/// the 16th waited on a full ring, on an 8-vCPU node).
pub fn lockPersistOrder(self: *Broadcaster, io: Io) void {
var attempt: u32 = 0;
while (self.persist_order.cmpxchgWeak(0, 1, .acquire, .monotonic) != null) {
attempt +|= 1;
_ = self.stats.persist_order_spins.fetchAdd(1, .monotonic);
backoff(attempt, &self.stats.persist_order_waits, io);
}
}
pub fn unlockPersistOrder(self: *Broadcaster) void {
self.persist_order.store(0, .release);
}
/// broadcast loop — drains the broadcast queue, fans out to consumers
/// and calls broadcast() for each item. this is the only path that touches
/// consumers_mutex / consumer.mutex / consumer.cond.
pub fn runBroadcastLoop(self: *Broadcaster) void {
log.info("broadcaster fiber started", .{});
while (true) {
const finished = self.producers_done.load(.acquire);
// only emit frames that are durably on disk: hold any whose seq is
// past the persister's committed watermark until the next flush
// advances it. without a persister (degenerate no-persist mode),
// nothing is gated. see docs/incident-2026-05-31-seq-rewind.md.
const committed: u64 = if (self.persist) |dp|
dp.committed_seq.load(.acquire)
else
std.math.maxInt(u64);
var drained: usize = 0;
while (self.broadcast_queue.peekSeq()) |seq| {
if (seq > committed) break; // not durable yet — hold
const item = self.broadcast_queue.pop() orelse break;
self.broadcast(item.seq, item.data);
self.allocator.free(@constCast(item.data));
drained += 1;
}
if (finished) break;
if (drained == 0) {
// nothing emittable — yield briefly so other fibers run
self.io.sleep(Io.Duration.fromMilliseconds(1), .awake) catch return;
}
}
while (self.broadcast_queue.pop()) |item| {
self.allocator.free(@constCast(item.data));
}
log.info("broadcaster fiber stopped", .{});
}
};
// --- websocket handler ---
pub const Handler = struct {
consumer: ?*Consumer,
broadcaster: *Broadcaster,
conn: *websocket.Conn,
cursor: ?u64,
invalid_cursor: bool = false,
/// called during handshake — validate path, parse cursor.
/// do NOT start the write thread here (handshake reply hasn't been sent yet).
pub fn init(handshake: *const websocket.Handshake, conn: *websocket.Conn, ctx: *Broadcaster) !Handler {
const url = handshake.url;
const path = if (std.mem.indexOfScalar(u8, url, '?')) |qi| url[0..qi] else url;
if (!std.mem.eql(u8, path, "/xrpc/com.atproto.sync.subscribeRepos")) {
return error.NotFound;
}
// parse cursor (deferred until afterInit when connection is fully upgraded)
var cursor: ?u64 = null;
var invalid_cursor = false;
if (std.mem.indexOf(u8, url, "cursor=")) |cursor_start| {
const value_start = cursor_start + "cursor=".len;
const value_end = std.mem.indexOfScalarPos(u8, url, value_start, '&') orelse url.len;
const cursor_str = url[value_start..value_end];
cursor = std.fmt.parseInt(u64, cursor_str, 10) catch blk: {
invalid_cursor = true;
break :blk null;
};
}
return .{ .consumer = null, .broadcaster = ctx, .conn = conn, .cursor = cursor, .invalid_cursor = invalid_cursor };
}
/// called AFTER the websocket handshake reply has been sent to the client.
/// safe to start the consumer write thread and begin sending frames.
pub fn afterInit(self: *Handler, ctx: *Broadcaster) !void {
const replaying = self.cursor != null and !self.invalid_cursor;
const consumer = ctx.addConsumer(self.conn, replaying) catch return error.Unexpected;
self.consumer = consumer;
if (self.invalid_cursor) {
// spec: send error frame with InvalidCursor, then close
var buf: [256]u8 = undefined;
if (encodeErrorFrame("InvalidCursor", "cursor parameter is not a valid integer", &buf)) |frame| {
consumer.conn.writeBin(frame) catch {};
}
consumer.conn.close(.{}) catch {};
return;
}
if (self.cursor) |cursor| {
if (ctx.persist) |dp| if (!dp.history_enabled) {
var buf: [256]u8 = undefined;
if (encodeErrorFrame("ReplayDisabled", "This relay serves live events only", &buf)) |frame| {
consumer.conn.writeBin(frame) catch {};
}
consumer.conn.close(.{}) catch {};
return;
};
const latest = ctx.stats.relay_seq.load(.acquire);
// FutureCursor: cursor ahead of current seq — error, close
if (latest > 0 and cursor > latest) {
var buf: [256]u8 = undefined;
if (encodeErrorFrame("FutureCursor", "Cursor in the future.", &buf)) |frame| {
consumer.conn.writeBin(frame) catch {};
}
consumer.conn.close(.{}) catch {};
return;
}
// OutdatedCursor: cursor older than oldest available — info, continue
const oldest = blk: {
if (ctx.persist != null and ctx.db_queue != null) {
const FirstSeqReq = struct {
base: event_log_mod.DbRequest = .{ .callback = &execute },
result: ?u64 = null,
fn execute(b: *event_log_mod.DbRequest, dp: *event_log_mod.DiskPersist) void {
const s: *@This() = @fieldParentPtr("base", b);
s.result = dp.firstSeq();
}
};
var first_req: FirstSeqReq = .{};
ctx.db_queue.?.push(&first_req.base);
first_req.base.wait(ctx.io, ctx.shutdown);
if (first_req.result) |s| break :blk s;
}
break :blk ctx.history.oldestSeq() orelse 0;
};
if (oldest > 0 and cursor < oldest) {
var buf: [256]u8 = undefined;
if (encodeInfoMessage("OutdatedCursor", "Requested cursor exceeded limit. Possibly missing events", &buf)) |frame| {
consumer.conn.writeBin(frame) catch {};
}
// don't close — fall through to replayTo which replays from oldest available
}
ctx.replayTo(consumer, cursor);
}
}
pub fn clientMessage(_: *Handler, _: []const u8) !void {
// relay consumers are read-only
}
/// handle client-initiated close frame. without this, the websocket
/// library tries to write a close reply which can panic if the socket
/// is already dead (unreachable in std/net.zig drain).
pub fn clientClose(self: *Handler, _: []const u8) !void {
if (self.consumer) |c| {
c.alive.store(false, .release);
c.cond.signal(c.io);
}
self.conn.close(.{}) catch {};
}
pub fn close(self: *Handler) void {
if (self.consumer) |c| self.broadcaster.removeConsumer(c);
}
/// called by websocket server for non-WebSocket HTTP requests
pub fn httpFallback(
conn: *websocket.Conn,
method: []const u8,
url: []const u8,
body: []const u8,
headers: *const websocket.Handshake.KeyValue,
ctx: *Broadcaster,
) void {
if (ctx.http_fallback) |f| {
f(conn, method, url, body, headers, ctx.http_fallback_ctx);
}
}
};
pub const AttributionMetrics = struct {
history_entries: usize = 0,
evtbuf_entries: usize = 0,
did_cache_entries: usize = 0,
host_authority_cache_entries: usize = 0,
resolve_queue_len: usize = 0,
resolve_queued_set_count: usize = 0,
// memory attribution — internal capacities of key data structures
validator_cache_map_cap: usize = 0,
did_cache_map_cap: usize = 0,
queued_set_map_cap: usize = 0,
evtbuf_cap: usize = 0,
outbuf_cap: usize = 0,
workers_count: usize = 0,
// db_queue liveness — handled stops advancing while depth > 0 = workers wedged
db_queue_depth: u32 = 0,
db_queue_handled_total: u64 = 0,
};
pub fn formatPrometheusMetrics(stats: *const Stats, cache_entries: usize, attribution: AttributionMetrics, data_dir: []const u8, buf: []u8, io: Io) []const u8 {
const uptime: i64 = timestamp(io) - stats.start_time;
var w: Io.Writer = .fixed(buf);
// canary metric — proves what binary is running
w.print(
\\# TYPE relay_build_info gauge
\\# HELP relay_build_info build provenance
\\relay_build_info{{git_sha="{s}",optimize="{s}"}} 1
\\
, .{ build_options.git_sha, build_options.optimize }) catch {};
w.print(
\\# TYPE relay_frames_received_total counter
\\relay_frames_received_total {d}
\\
\\# TYPE relay_frames_broadcast_total counter
\\relay_frames_broadcast_total {d}
\\
\\# TYPE relay_consumers_active gauge
\\relay_consumers_active {d}
\\
\\# TYPE relay_validation_total counter
\\relay_validation_total{{result="validated"}} {d}
\\relay_validation_total{{result="failed"}} {d}
\\relay_validation_total{{result="skipped"}} {d}
\\
\\# TYPE relay_rate_limited_total counter
\\relay_rate_limited_total {d}
\\
\\# TYPE relay_rate_limited_by_tier counter
\\relay_rate_limited_by_tier{{tier="sec"}} {d}
\\relay_rate_limited_by_tier{{tier="hour"}} {d}
\\relay_rate_limited_by_tier{{tier="day"}} {d}
\\
\\# TYPE relay_pool_backpressure_total counter
\\# HELP relay_pool_backpressure_total times pool submit blocked on full queue
\\relay_pool_backpressure_total {d}
\\
\\# TYPE relay_decode_errors_total counter
\\relay_decode_errors_total {d}
\\
\\# TYPE relay_cache_total counter
\\relay_cache_total{{result="hit"}} {d}
\\relay_cache_total{{result="miss"}} {d}
\\
\\# TYPE relay_slow_consumers_total counter
\\relay_slow_consumers_total {d}
\\
\\# TYPE relay_connected_inbound gauge
\\relay_connected_inbound {d}
\\
\\# TYPE relay_upstream_seq gauge
\\relay_upstream_seq {d}
\\
\\# TYPE relay_seq gauge
\\relay_seq {d}
\\
\\# TYPE relay_uptime_seconds gauge
\\relay_uptime_seconds {d}
\\
\\# TYPE relay_validator_cache_entries gauge
\\relay_validator_cache_entries {d}
\\
\\# TYPE relay_validator_cache_evictions_total counter
\\relay_validator_cache_evictions_total {d}
\\
\\# TYPE relay_history_entries gauge
\\# HELP relay_history_entries in-memory frame history ring buffer entries
\\relay_history_entries {d}
\\
\\# TYPE relay_evtbuf_entries gauge
\\# HELP relay_evtbuf_entries pending flush buffer entries
\\relay_evtbuf_entries {d}
\\
\\# TYPE relay_did_cache_entries gauge
\\# HELP relay_did_cache_entries DID-to-UID cache entries
\\relay_did_cache_entries {d}
\\
\\# TYPE relay_resolve_queue_len gauge
\\# HELP relay_resolve_queue_len DID resolve queue length
\\relay_resolve_queue_len {d}
\\
\\# TYPE relay_resolve_queued_set_count gauge
\\# HELP relay_resolve_queued_set_count DID resolve dedup set size
\\relay_resolve_queued_set_count {d}
\\
\\# TYPE relay_host_authority_checks_total counter
\\# HELP relay_host_authority_checks_total resolveHostAuthority calls on frame workers
\\relay_host_authority_checks_total {d}
\\
\\# TYPE relay_host_authority_trigger counter
\\# HELP relay_host_authority_trigger host authority check triggers by reason
\\relay_host_authority_trigger{{reason="is_new"}} {d}
\\relay_host_authority_trigger{{reason="host_changed"}} {d}
\\
\\# TYPE relay_host_authority_time_us_total counter
\\# HELP relay_host_authority_time_us_total cumulative microseconds in resolveHostAuthority
\\relay_host_authority_time_us_total {d}
\\
\\# TYPE relay_pool_queued_bytes gauge
\\# HELP relay_pool_queued_bytes estimated bytes of frame data queued in worker pool
\\relay_pool_queued_bytes {d}
\\
, .{
stats.frames_in.load(.acquire),
stats.frames_out.load(.acquire),
stats.consumer_count.load(.acquire),
stats.validated.load(.acquire),
stats.failed.load(.acquire),
stats.skipped.load(.acquire),
stats.rate_limited.load(.acquire),
stats.rate_limited_sec.load(.acquire),
stats.rate_limited_hour.load(.acquire),
stats.rate_limited_day.load(.acquire),
stats.pool_backpressure.load(.acquire),
stats.decode_errors.load(.acquire),
stats.cache_hits.load(.acquire),
stats.cache_misses.load(.acquire),
stats.slow_consumers.load(.acquire),
stats.connected_inbound.load(.acquire),
stats.seq.load(.acquire),
stats.relay_seq.load(.acquire),
uptime,
cache_entries,
stats.cache_evictions.load(.acquire),
attribution.history_entries,
attribution.evtbuf_entries,
attribution.did_cache_entries,
attribution.resolve_queue_len,
attribution.resolve_queued_set_count,
stats.host_authority_checks.load(.acquire),
stats.host_authority_is_new.load(.acquire),
stats.host_authority_host_changed.load(.acquire),
stats.host_authority_time_us.load(.acquire),
stats.pool_queued_bytes.load(.acquire),
}) catch return w.buffered();
// keepalive pinger metrics (separate print to stay under 32-arg limit)
w.print(
\\# TYPE relay_ws_pings_sent_total counter
\\# HELP relay_ws_pings_sent_total keepalive pings sent to silent upstream connections
\\relay_ws_pings_sent_total {d}
\\
\\# TYPE relay_ws_ping_timeout_closes_total counter
\\# HELP relay_ws_ping_timeout_closes_total connections closed as half-open after max unanswered keepalive pings
\\relay_ws_ping_timeout_closes_total {d}
\\
\\# TYPE relay_ws_ping_write_failures_total counter
\\# HELP relay_ws_ping_write_failures_total keepalive ping writes that failed (connection torn down)
\\relay_ws_ping_write_failures_total {d}
\\
, .{
stats.ws_pings_sent.load(.acquire),
stats.ws_ping_timeout_closes.load(.acquire),
stats.ws_ping_write_failures.load(.acquire),
}) catch return w.buffered();
w.print(
\\# TYPE relay_host_authority_cache_hits_total counter
\\# HELP relay_host_authority_cache_hits_total confirmed host mismatches rejected without network resolution
\\relay_host_authority_cache_hits_total {d}
\\
\\# TYPE relay_host_authority_network_checks_total counter
\\# HELP relay_host_authority_network_checks_total host authority decisions that performed network resolution
\\relay_host_authority_network_checks_total {d}
\\
\\# TYPE relay_host_authority_network_time_us_total counter
\\# HELP relay_host_authority_network_time_us_total worker microseconds spent waiting on host authority network decisions
\\relay_host_authority_network_time_us_total {d}
\\
\\# TYPE relay_host_authority_pool_wait_us_total counter
\\# HELP relay_host_authority_pool_wait_us_total worker microseconds spent waiting for a host resolver pool slot
\\relay_host_authority_pool_wait_us_total {d}
\\
\\# TYPE relay_host_authority_cache_entries gauge
\\# HELP relay_host_authority_cache_entries confirmed DID and incoming host mismatches cached
\\relay_host_authority_cache_entries {d}
\\
, .{
stats.host_authority_cache_hits.load(.acquire),
stats.host_authority_network_checks.load(.acquire),
stats.host_authority_network_time_us.load(.acquire),
stats.host_authority_pool_wait_us.load(.acquire),
attribution.host_authority_cache_entries,
}) catch return w.buffered();
// pipeline contention metrics (separate print to stay under 32-arg limit)
w.print(
\\# TYPE relay_chain_breaks_total counter
\\# HELP relay_chain_breaks_total chain continuity failures by reason
\\relay_chain_breaks_total{{reason="since"}} {d}
\\relay_chain_breaks_total{{reason="prev_data"}} {d}
\\
\\# TYPE relay_persist_order_spins_total counter
\\# HELP relay_persist_order_spins_total retries waiting for the persist ordering lock
\\relay_persist_order_spins_total {d}
\\
\\# TYPE relay_persist_order_waits_total counter
\\# HELP relay_persist_order_waits_total backoff sleeps waiting for the persist ordering lock (advances during a stall)
\\relay_persist_order_waits_total {d}
\\
\\# TYPE relay_broadcast_queue_full_waits_total counter
\\# HELP relay_broadcast_queue_full_waits_total backoff sleeps on a full broadcast ring (advances during a stall)
\\relay_broadcast_queue_full_waits_total {d}
\\
\\# TYPE relay_replay_buffer_waits_total counter
\\# HELP relay_replay_buffer_waits_total replay pauses waiting for a consumer to drain its buffer
\\relay_replay_buffer_waits_total {d}
\\
\\# TYPE relay_broadcast_queue_push_lock_spins_total counter
\\# HELP relay_broadcast_queue_push_lock_spins_total spin iterations waiting for broadcast queue push lock
\\relay_broadcast_queue_push_lock_spins_total {d}
\\
\\# TYPE relay_broadcast_queue_full_total counter
\\# HELP relay_broadcast_queue_full_total retries on a full broadcast queue (ring capacity)
\\relay_broadcast_queue_full_total {d}
\\
\\# TYPE relay_broadcast_queue_depth_hwm gauge
\\# HELP relay_broadcast_queue_depth_hwm high-water mark of broadcast queue depth
\\relay_broadcast_queue_depth_hwm {d}
\\
\\# TYPE relay_broadcast_no_consumers_total counter
\\# HELP relay_broadcast_no_consumers_total frames skipped broadcast (no consumers)
\\relay_broadcast_no_consumers_total {d}
\\
, .{
stats.chain_breaks_since.load(.acquire),
stats.chain_breaks_prev_data.load(.acquire),
stats.persist_order_spins.load(.acquire),
stats.persist_order_waits.load(.acquire),
stats.broadcast_queue_full_waits.load(.acquire),
stats.replay_buffer_waits.load(.acquire),
stats.broadcast_queue_push_lock_spins.load(.acquire),
stats.broadcast_queue_full.load(.acquire),
stats.broadcast_queue_depth_hwm.load(.acquire),
stats.broadcast_no_consumers.load(.acquire),
}) catch {};
// validation failure breakdown by reason
w.print(
\\# TYPE relay_validation_failed counter
\\# HELP relay_validation_failed validation failures by reason
\\relay_validation_failed{{reason="bad_did"}} {d}
\\relay_validation_failed{{reason="bad_rev"}} {d}
\\relay_validation_failed{{reason="missing_blocks"}} {d}
\\relay_validation_failed{{reason="oversized_blocks"}} {d}
\\relay_validation_failed{{reason="bad_structure"}} {d}
\\relay_validation_failed{{reason="signature"}} {d}
\\relay_validation_failed{{reason="commit_integrity"}} {d}
\\relay_validation_failed{{reason="sync_1_1"}} {d}
\\relay_validation_failed{{reason="prev_data_missing"}} {d}
\\relay_validation_failed{{reason="host_authority"}} {d}
\\relay_validation_failed{{reason="future_rev"}} {d}
\\
\\# TYPE relay_host_authority_reject counter
\\# HELP relay_host_authority_reject host authority reject breakdown by branch
\\relay_host_authority_reject{{branch="parse_did"}} {d}
\\relay_host_authority_reject{{branch="resolve"}} {d}
\\relay_host_authority_reject{{branch="no_endpoint"}} {d}
\\relay_host_authority_reject{{branch="bad_url"}} {d}
\\relay_host_authority_reject{{branch="unknown_host"}} {d}
\\relay_host_authority_reject{{branch="host_mismatch"}} {d}
\\
\\# TYPE relay_subscriber_disconnect_total counter
\\# HELP relay_subscriber_disconnect_total subscriber reconnect-cycle disconnects by phase
\\relay_subscriber_disconnect_total{{phase="dns_connect"}} {d}
\\relay_subscriber_disconnect_total{{phase="tls_init"}} {d}
\\relay_subscriber_disconnect_total{{phase="ws_handshake"}} {d}
\\relay_subscriber_disconnect_total{{phase="read_loop"}} {d}
\\
, .{
stats.failed_bad_did.load(.acquire),
stats.failed_bad_rev.load(.acquire),
stats.failed_missing_blocks.load(.acquire),
stats.failed_oversized_blocks.load(.acquire),
stats.failed_bad_structure.load(.acquire),
stats.failed_signature.load(.acquire),
stats.failed_commit_integrity.load(.acquire),
stats.failed_sync_1_1.load(.acquire),
stats.failed_prev_data_missing.load(.acquire),
stats.failed_host_authority.load(.acquire),
stats.failed_future_rev.load(.acquire),
stats.host_authority_reject_parse_did.load(.acquire),
stats.host_authority_reject_resolve.load(.acquire),
stats.host_authority_reject_no_endpoint.load(.acquire),
stats.host_authority_reject_bad_url.load(.acquire),
stats.host_authority_reject_unknown_host.load(.acquire),
stats.host_authority_reject_host_mismatch.load(.acquire),
stats.subscriber_disconnect_dns_connect.load(.acquire),
stats.subscriber_disconnect_tls_init.load(.acquire),
stats.subscriber_disconnect_ws_handshake.load(.acquire),
stats.subscriber_disconnect_read_loop.load(.acquire),
}) catch return w.buffered();
// memory attribution — internal capacities help identify what's consuming RSS
w.print(
\\# TYPE relay_validator_cache_map_cap gauge
\\# HELP relay_validator_cache_map_cap hashmap backing capacity of signing key LRU
\\relay_validator_cache_map_cap {d}
\\
\\# TYPE relay_did_cache_map_cap gauge
\\# HELP relay_did_cache_map_cap hashmap backing capacity of DID-to-UID LRU
\\relay_did_cache_map_cap {d}
\\
\\# TYPE relay_queued_set_map_cap gauge
\\# HELP relay_queued_set_map_cap hashmap backing capacity of resolver dedup set
\\relay_queued_set_map_cap {d}
\\
\\# TYPE relay_evtbuf_cap gauge
\\# HELP relay_evtbuf_cap allocated capacity of event flush buffer (jobs)
\\relay_evtbuf_cap {d}
\\
\\# TYPE relay_outbuf_cap gauge
\\# HELP relay_outbuf_cap allocated capacity of output byte buffer
\\relay_outbuf_cap {d}
\\
\\# TYPE relay_workers_count gauge
\\# HELP relay_workers_count active subscriber worker threads
\\relay_workers_count {d}
\\
\\# TYPE relay_db_queue_depth gauge
\\# HELP relay_db_queue_depth current depth of the DbRequestQueue (tail - head). non-zero with stagnant relay_db_queue_handled_total = workers wedged
\\relay_db_queue_depth {d}
\\
\\# TYPE relay_db_queue_handled_total counter
\\# HELP relay_db_queue_handled_total total DbRequest callbacks executed across worker threads
\\relay_db_queue_handled_total {d}
\\
, .{
attribution.validator_cache_map_cap,
attribution.did_cache_map_cap,
attribution.queued_set_map_cap,
attribution.evtbuf_cap,
attribution.outbuf_cap,
attribution.workers_count,
attribution.db_queue_depth,
attribution.db_queue_handled_total,
}) catch {};
if (comptime @import("build_options").profile_stages) {
inline for (.{ "frame", "validate", "index", "post_index" }) |stage| {
const profile = &@field(stats, "replay_" ++ stage);
w.print("relay_stage_count{{stage=\"{s}\"}} {d}\nrelay_stage_ns_total{{stage=\"{s}\"}} {d}\nrelay_stage_ns_max{{stage=\"{s}\"}} {d}\n", .{
stage, profile.count.load(.monotonic),
stage, profile.total_ns.load(.monotonic),
stage, profile.max_ns.load(.monotonic),
}) catch {};
}
}
// linux-only process metrics from /proc
if (comptime builtin.os.tag == .linux) {
appendProcMetrics(&w, io);
appendDiskMetrics(&w, data_dir);
}
return w.buffered();
}
fn appendProcMetrics(w: *Io.Writer, io: Io) void {
// RSS from /proc/self/statm (field[1] * page_size)
if (Io.Dir.openFileAbsolute(io, "/proc/self/statm", .{})) |f| {
defer f.close(io);
var statm_buf: [256]u8 = undefined;
const n = f.readPositionalAll(io, &statm_buf, 0) catch 0;
if (n > 0) {
const line = statm_buf[0..n];
var iter = std.mem.splitScalar(u8, line, ' ');
_ = iter.next(); // skip total pages
if (iter.next()) |rss_pages| {
if (std.fmt.parseInt(u64, rss_pages, 10)) |pages| {
w.print(
\\# TYPE relay_process_rss_bytes gauge
\\relay_process_rss_bytes {d}
\\
, .{pages * 4096}) catch {};
} else |_| {}
}
}
} else |_| {}
// thread count, VmHWM, RssAnon from /proc/self/status
if (Io.Dir.openFileAbsolute(io, "/proc/self/status", .{})) |f| {
defer f.close(io);
var status_buf: [4096]u8 = undefined;
const n = f.readPositionalAll(io, &status_buf, 0) catch 0;
if (n > 0) {
const content = status_buf[0..n];
const fields = .{
.{ "Threads:", "relay_threads_total" },
.{ "VmHWM:", "relay_vm_hwm_kb" },
.{ "RssAnon:", "relay_rss_anon_kb" },
};
inline for (fields) |entry| {
if (std.mem.indexOf(u8, content, entry[0])) |pos| {
const rest = content[pos + entry[0].len ..];
const trimmed = std.mem.trimStart(u8, rest, " \t");
const end = std.mem.indexOfScalar(u8, trimmed, ' ') orelse
(std.mem.indexOfScalar(u8, trimmed, '\n') orelse trimmed.len);
if (std.fmt.parseInt(u64, trimmed[0..end], 10)) |val| {
w.print(
\\# TYPE {s} gauge
\\{s} {d}
\\
, .{ entry[1], entry[1], val }) catch {};
} else |_| {}
}
}
}
} else |_| {}
// glibc malloc stats — mallinfo fields are c_int, bitcast to u32 to extend range to 4 GiB.
// note: mallinfo only reports the main arena, not per-thread arenas.
// for accurate total heap picture, rely on RssAnon from /proc/self/status above.
const mi = mallinfo();
const arena: u64 = @as(u32, @bitCast(mi.arena));
const in_use: u64 = @as(u32, @bitCast(mi.uordblks));
const free_bytes: u64 = @as(u32, @bitCast(mi.fordblks));
const mmap_bytes: u64 = @as(u32, @bitCast(mi.hblkhd));
w.print(
\\# TYPE relay_malloc_arena_bytes gauge
\\relay_malloc_arena_bytes {d}
\\
\\# TYPE relay_malloc_in_use_bytes gauge
\\relay_malloc_in_use_bytes {d}
\\
\\# TYPE relay_malloc_free_bytes gauge
\\relay_malloc_free_bytes {d}
\\
\\# TYPE relay_malloc_mmap_bytes gauge
\\relay_malloc_mmap_bytes {d}
\\
, .{ arena, in_use, free_bytes, mmap_bytes }) catch {};
// all-arena heap picture via malloc_info() (mallinfo above is main-arena only).
// with ~2670 worker threads glibc spreads allocations across many per-thread
// arenas; post-burst fragmentation lives there, invisible to mallinfo. these
// gauges sum every arena so a rising free_total / arena_count is observable.
if (readMallocInfo()) |info| {
w.print(
\\# TYPE relay_malloc_system_bytes gauge
\\# HELP relay_malloc_system_bytes total bytes obtained from the OS across all arenas
\\relay_malloc_system_bytes {d}
\\
\\# TYPE relay_malloc_free_total_bytes gauge
\\# HELP relay_malloc_free_total_bytes free bytes held in all arenas (fast+rest), not returned to OS
\\relay_malloc_free_total_bytes {d}
\\
\\# TYPE relay_malloc_arena_count gauge
\\# HELP relay_malloc_arena_count number of glibc malloc arenas (tune via MALLOC_ARENA_MAX)
\\relay_malloc_arena_count {d}
\\
, .{ info.system_bytes, info.free_bytes, info.arena_count }) catch {};
}
}
// glibc mallinfo struct — fields are c_int (32-bit), we bitcast to u32 for range.
const MallInfo = extern struct {
arena: c_int,
ordblks: c_int,
smblks: c_int,
hblks: c_int,
hblkhd: c_int,
usmblks: c_int,
fsmblks: c_int,
uordblks: c_int,
fordblks: c_int,
keepcost: c_int,
};
const mallinfo = @extern(*const fn () callconv(.c) MallInfo, .{ .name = "mallinfo" });
// all-arena heap stats, parsed from glibc malloc_info() XML. unlike mallinfo()
// these cover every per-thread arena, not just the main one.
const MallocInfo = struct {
system_bytes: u64,
free_bytes: u64,
arena_count: u32,
};
const CFile = opaque {};
const open_memstream = @extern(*const fn (ptr: *[*c]u8, size: *usize) callconv(.c) ?*CFile, .{ .name = "open_memstream" });
const fclose = @extern(*const fn (*CFile) callconv(.c) c_int, .{ .name = "fclose" });
const c_free = @extern(*const fn (?*anyopaque) callconv(.c) void, .{ .name = "free" });
const malloc_info_fn = @extern(*const fn (options: c_int, stream: *CFile) callconv(.c) c_int, .{ .name = "malloc_info" });
fn readMallocInfo() ?MallocInfo {
// comptime if prunes the linux-only externs from analysis on other hosts,
// so `zig build test` on macOS doesn't try to link malloc_info/open_memstream.
return if (comptime builtin.os.tag == .linux) readMallocInfoLinux() else null;
}
fn readMallocInfoLinux() ?MallocInfo {
var buf_ptr: [*c]u8 = null;
var buf_size: usize = 0;
const stream = open_memstream(&buf_ptr, &buf_size) orelse return null;
_ = malloc_info_fn(0, stream);
_ = fclose(stream); // flushes and populates buf_ptr/buf_size
const p = buf_ptr orelse return null;
defer c_free(p);
const xml = p[0..buf_size];
return MallocInfo{
// top-level totals are the LAST occurrence (each <heap> emits its own).
.system_bytes = lastSizeAttr(xml, "system type=\"current\"") orelse 0,
.free_bytes = (lastSizeAttr(xml, "total type=\"fast\"") orelse 0) +
(lastSizeAttr(xml, "total type=\"rest\"") orelse 0),
.arena_count = countOccurrences(xml, "<heap nr="),
};
}
// find the last occurrence of `marker`, then parse the first `size="N"` after it.
fn lastSizeAttr(xml: []const u8, marker: []const u8) ?u64 {
const at = std.mem.lastIndexOf(u8, xml, marker) orelse return null;
const rest = xml[at + marker.len ..];
const key = "size=\"";
const kpos = std.mem.indexOf(u8, rest, key) orelse return null;
const num = rest[kpos + key.len ..];
const end = std.mem.indexOfScalar(u8, num, '"') orelse return null;
return std.fmt.parseInt(u64, num[0..end], 10) catch null;
}
fn countOccurrences(haystack: []const u8, needle: []const u8) u32 {
var n: u32 = 0;
var i: usize = 0;
while (std.mem.indexOfPos(u8, haystack, i, needle)) |pos| {
n += 1;
i = pos + needle.len;
}
return n;
}
test "readMallocInfo parses all-arena totals" {
if (comptime builtin.os.tag != .linux) return error.SkipZigTest;
// force some allocation so the arena is non-trivial
const a = std.heap.c_allocator;
var kept: [64][]u8 = undefined;
for (&kept) |*slot| slot.* = try a.alloc(u8, 4096);
defer for (kept) |s| a.free(s);
const info = readMallocInfo() orelse return error.MallocInfoUnavailable;
try std.testing.expect(info.system_bytes > 0);
try std.testing.expect(info.arena_count >= 1);
}
test "lastSizeAttr / countOccurrences against sample XML" {
const xml =
\\<malloc version="1">
\\<heap nr="0">
\\<total type="fast" count="1" size="100"/>
\\<total type="rest" count="2" size="200"/>
\\<system type="current" size="9999"/>
\\</heap>
\\<heap nr="1">
\\<total type="fast" count="3" size="111"/>
\\<total type="rest" count="4" size="222"/>
\\<system type="current" size="8888"/>
\\</heap>
\\<total type="fast" count="4" size="211"/>
\\<total type="rest" count="6" size="422"/>
\\<system type="current" size="18887"/>
\\</malloc>
;
try std.testing.expectEqual(@as(?u64, 18887), lastSizeAttr(xml, "system type=\"current\""));
try std.testing.expectEqual(@as(?u64, 211), lastSizeAttr(xml, "total type=\"fast\""));
try std.testing.expectEqual(@as(?u64, 422), lastSizeAttr(xml, "total type=\"rest\""));
try std.testing.expectEqual(@as(u32, 2), countOccurrences(xml, "<heap nr="));
}
// statvfs — only the fields we use (f_frsize, f_blocks, f_bavail)
const StatVfs = extern struct {
f_bsize: c_ulong,
f_frsize: c_ulong,
f_blocks: c_ulong,
f_bfree: c_ulong,
f_bavail: c_ulong,
f_files: c_ulong,
f_ffree: c_ulong,
f_favail: c_ulong,
f_fsid: c_ulong,
f_flag: c_ulong,
f_namemax: c_ulong,
};
const statvfs_fn = @extern(*const fn ([*:0]const u8, *StatVfs) callconv(.c) c_int, .{ .name = "statvfs" });
fn appendDiskMetrics(w: *Io.Writer, data_dir: []const u8) void {
// statvfs needs a null-terminated path
var path_buf: [4096]u8 = undefined;
if (data_dir.len >= path_buf.len) return;
@memcpy(path_buf[0..data_dir.len], data_dir);
path_buf[data_dir.len] = 0;
var stat: StatVfs = undefined;
if (statvfs_fn(@ptrCast(&path_buf), &stat) != 0) return;
const block_size: u64 = stat.f_frsize;
const total = stat.f_blocks * block_size;
const available = stat.f_bavail * block_size;
w.print(
\\# TYPE relay_disk_total_bytes gauge
\\relay_disk_total_bytes {d}
\\
\\# TYPE relay_disk_available_bytes gauge
\\relay_disk_available_bytes {d}
\\
, .{ total, available }) catch {};
}
pub fn formatStatsResponse(stats: *const Stats, buf: []u8, io: Io) []const u8 {
return std.fmt.bufPrint(buf,
\\{{"seq":{d},"relay_seq":{d},"consumers":{d},"connected_inbound":{d},"frames_in":{d},"frames_out":{d},"validated":{d},"failed":{d},"skipped":{d},"decode_errors":{d},"cache_hits":{d},"cache_misses":{d},"slow_consumers":{d},"chain_breaks":{d},"pool_backpressure":{d},"uptime_seconds":{d}}}
, .{
stats.seq.load(.acquire),
stats.relay_seq.load(.acquire),
stats.consumer_count.load(.acquire),
stats.connected_inbound.load(.acquire),
stats.frames_in.load(.acquire),
stats.frames_out.load(.acquire),
stats.validated.load(.acquire),
stats.failed.load(.acquire),
stats.skipped.load(.acquire),
stats.decode_errors.load(.acquire),
stats.cache_hits.load(.acquire),
stats.cache_misses.load(.acquire),
stats.slow_consumers.load(.acquire),
stats.chain_breaks_since.load(.acquire) + stats.chain_breaks_prev_data.load(.acquire),
stats.pool_backpressure.load(.acquire),
timestamp(io) - stats.start_time,
}) catch "";
}
// --- tests ---
var test_shutdown: std.atomic.Value(bool) = .{ .raw = false };
test "broadcaster add and remove consumer" {
var b = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer b.deinit();
try std.testing.expectEqual(@as(u64, 0), b.stats.seq.load(.acquire));
try std.testing.expectEqual(@as(usize, 0), b.consumerCount());
}
test "broadcast updates stats and history" {
var b = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer b.deinit();
b.broadcast(1, "frame1");
b.broadcast(2, "frame2");
b.broadcast(3, "frame3");
try std.testing.expectEqual(@as(u64, 3), b.stats.seq.load(.acquire));
// frames_in is now incremented in subscriber, not broadcast
try std.testing.expectEqual(@as(u64, 0), b.stats.frames_in.load(.acquire));
try std.testing.expectEqual(@as(u64, 1), b.history.oldestSeq().?);
try std.testing.expectEqual(@as(u64, 3), b.history.newestSeq().?);
}
test "frame history supports cursor replay" {
var b = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer b.deinit();
for (1..6) |i| {
var buf: [32]u8 = undefined;
const data = std.fmt.bufPrint(&buf, "frame{d}", .{i}) catch unreachable;
b.broadcast(@intCast(i), data);
}
const frames = try b.history.framesSince(std.testing.allocator, 3);
defer {
for (frames) |f| std.testing.allocator.free(f.data);
std.testing.allocator.free(frames);
}
try std.testing.expectEqual(@as(usize, 2), frames.len);
try std.testing.expectEqual(@as(u64, 4), frames[0].seq);
try std.testing.expectEqual(@as(u64, 5), frames[1].seq);
}
test "enqueue refuses frames for a dead consumer" {
// regression: replay for an abruptly-disconnected consumer kept
// accumulating frames, compounding into the 2026-08-06 canary OOM.
var consumer = Consumer{
.conn = undefined, // enqueue never touches the connection
.allocator = std.testing.allocator,
.io = std.testing.io,
};
try std.testing.expect(consumer.enqueueRaw("frame1"));
consumer.alive.store(false, .release);
try std.testing.expect(!consumer.enqueueRaw("frame2"));
// drain the accepted frame
consumer.mutex.lockUncancelable(consumer.io);
while (consumer.dequeue()) |f| f.release();
consumer.mutex.unlock(consumer.io);
}
test "shared frame ref counting" {
const frame = try SharedFrame.create(std.testing.allocator, "hello");
frame.acquire(); // ref=2
frame.acquire(); // ref=3
frame.release(); // ref=2
frame.release(); // ref=1
frame.release(); // ref=0 → freed
}
test "error frame is valid CBOR" {
const cbor = zat.cbor;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const frame = buildErrorFrame(alloc) orelse return error.FrameBuildFailed;
// decode header
const h_result = try cbor.decode(alloc, frame);
const h = h_result.value;
try std.testing.expectEqual(@as(i64, -1), h.getInt("op").?);
// spec: error frames have {op: -1} only, no `t` field
try std.testing.expect(h.getString("t") == null);
// decode payload
const p = try cbor.decodeAll(alloc, frame[h_result.consumed..]);
try std.testing.expectEqualStrings("ConsumerTooSlow", p.getString("error").?);
try std.testing.expectEqualStrings("consumer buffer full", p.getString("message").?);
}
test "formatPrometheusMetrics produces valid output" {
var stats = Stats{ .start_time = timestamp(std.testing.io) - 60 };
stats.seq.store(99999, .release);
stats.relay_seq.store(12345, .release);
stats.consumer_count.store(3, .release);
stats.frames_in.store(10000, .release);
stats.frames_out.store(9000, .release);
stats.validated.store(500, .release);
stats.failed.store(2, .release);
stats.skipped.store(9498, .release);
stats.cache_hits.store(400, .release);
stats.cache_misses.store(100, .release);
stats.host_authority_cache_hits.store(321, .release);
stats.host_authority_network_checks.store(12, .release);
stats.host_authority_network_time_us.store(456_000, .release);
stats.host_authority_pool_wait_us.store(789_000, .release);
var buf: [65536]u8 = undefined;
const output = formatPrometheusMetrics(&stats, 42, .{
.host_authority_cache_entries = 9,
}, "/tmp", &buf, std.testing.io);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_frames_received_total 10000") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_frames_broadcast_total 9000") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_consumers_active 3") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_validation_total{result=\"validated\"} 500") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_validation_total{result=\"failed\"} 2") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_connected_inbound 0") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_upstream_seq 99999") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_seq 12345") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "# TYPE relay_uptime_seconds gauge") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_validator_cache_entries 42") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_validator_cache_evictions_total 0") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_host_authority_cache_hits_total 321") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_host_authority_network_checks_total 12") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_host_authority_network_time_us_total 456000") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_host_authority_pool_wait_us_total 789000") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_host_authority_cache_entries 9") != null);
}
test "ws ping counters render on their own lines with no cross-wiring" {
var stats = Stats{ .start_time = timestamp(std.testing.io) };
stats.ws_pings_sent.store(111_111, .release);
stats.ws_ping_timeout_closes.store(222, .release);
stats.ws_ping_write_failures.store(3, .release);
var buf: [65536]u8 = undefined;
const output = formatPrometheusMetrics(&stats, 0, .{
.host_authority_cache_entries = 0,
}, "/tmp", &buf, std.testing.io);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_ws_pings_sent_total 111111\n") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_ws_ping_timeout_closes_total 222\n") != null);
try std.testing.expect(std.mem.indexOf(u8, output, "relay_ws_ping_write_failures_total 3\n") != null);
}
test "formatStatsResponse produces valid JSON" {
var stats = Stats{ .start_time = timestamp(std.testing.io) - 42 };
stats.seq.store(100, .release);
stats.frames_in.store(200, .release);
stats.consumer_count.store(5, .release);
var buf: [4096]u8 = undefined;
const response = formatStatsResponse(&stats, &buf, std.testing.io);
try std.testing.expect(std.mem.startsWith(u8, response, "{"));
try std.testing.expect(std.mem.indexOf(u8, response, "\"seq\":100") != null);
try std.testing.expect(std.mem.indexOf(u8, response, "\"consumers\":5") != null);
try std.testing.expect(std.mem.indexOf(u8, response, "\"frames_in\":200") != null);
try std.testing.expect(std.mem.indexOf(u8, response, "\"slow_consumers\":0") != null);
}
test "resequenceFrame replaces seq in payload" {
const cbor = zat.cbor;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// build a frame with upstream seq=12345
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = "#commit" } },
} };
const payload: cbor.Value = .{ .map = &.{
.{ .key = "repo", .value = .{ .text = "did:plc:test123" } },
.{ .key = "seq", .value = .{ .unsigned = 12345 } },
.{ .key = "rev", .value = .{ .text = "3k2abc000000" } },
} };
const header_bytes = try cbor.encodeAlloc(alloc, header);
const payload_bytes = try cbor.encodeAlloc(alloc, payload);
const frame = try alloc.alloc(u8, header_bytes.len + payload_bytes.len);
@memcpy(frame[0..header_bytes.len], header_bytes);
@memcpy(frame[header_bytes.len..], payload_bytes);
// resequence to relay seq 99999
const result = resequenceFrame(alloc, frame, 99999) orelse return error.ResequenceFailed;
// decode result and verify
const h_result = try cbor.decode(alloc, result);
const p = try cbor.decodeAll(alloc, result[h_result.consumed..]);
// header preserved
try std.testing.expectEqualStrings("#commit", h_result.value.getString("t").?);
try std.testing.expectEqual(@as(i64, 1), h_result.value.getInt("op").?);
// seq replaced with relay seq
try std.testing.expectEqual(@as(u64, 99999), p.getUint("seq").?);
// other fields preserved
try std.testing.expectEqualStrings("did:plc:test123", p.getString("repo").?);
try std.testing.expectEqualStrings("3k2abc000000", p.getString("rev").?);
// tooBig injected for commit frames missing it
try std.testing.expectEqual(false, p.getBool("tooBig").?);
try std.testing.expectEqual(false, p.getBool("rebase").?);
}
test "resequenceFrame preserves identity frame fields" {
const cbor = zat.cbor;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = "#identity" } },
} };
const payload: cbor.Value = .{ .map = &.{
.{ .key = "did", .value = .{ .text = "did:plc:alice" } },
.{ .key = "seq", .value = .{ .unsigned = 500 } },
.{ .key = "time", .value = .{ .text = "2024-01-15T10:30:00Z" } },
} };
const header_bytes = try cbor.encodeAlloc(alloc, header);
const payload_bytes = try cbor.encodeAlloc(alloc, payload);
const frame = try alloc.alloc(u8, header_bytes.len + payload_bytes.len);
@memcpy(frame[0..header_bytes.len], header_bytes);
@memcpy(frame[header_bytes.len..], payload_bytes);
const result = resequenceFrame(alloc, frame, 42) orelse return error.ResequenceFailed;
const h_result = try cbor.decode(alloc, result);
const p = try cbor.decodeAll(alloc, result[h_result.consumed..]);
try std.testing.expectEqualStrings("#identity", h_result.value.getString("t").?);
try std.testing.expectEqual(@as(u64, 42), p.getUint("seq").?);
try std.testing.expectEqualStrings("did:plc:alice", p.getString("did").?);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", p.getString("time").?);
// tooBig NOT injected for non-commit frames
try std.testing.expectEqual(@as(?bool, null), p.getBool("tooBig"));
try std.testing.expectEqual(@as(?bool, null), p.getBool("rebase"));
}
test "encodeErrorFrame produces valid error frame CBOR" {
const cbor = zat.cbor;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
var buf: [256]u8 = undefined;
const frame = encodeErrorFrame("FutureCursor", "Cursor in the future.", &buf) orelse return error.EncodeFailed;
// decode header — must be {op: -1}
const h_result = try cbor.decode(alloc, frame);
const h = h_result.value;
try std.testing.expectEqual(@as(i64, -1), h.getInt("op").?);
try std.testing.expect(h.getString("t") == null); // no t field on error frames
// decode payload — must have error and message fields
const p = try cbor.decodeAll(alloc, frame[h_result.consumed..]);
try std.testing.expectEqualStrings("FutureCursor", p.getString("error").?);
try std.testing.expectEqualStrings("Cursor in the future.", p.getString("message").?);
}
test "encodeInfoMessage produces valid #info message frame CBOR" {
const cbor = zat.cbor;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
var buf: [256]u8 = undefined;
const frame = encodeInfoMessage("OutdatedCursor", "Requested cursor exceeded limit. Possibly missing events", &buf) orelse return error.EncodeFailed;
// decode header — must be {op: 1, t: "#info"}
const h_result = try cbor.decode(alloc, frame);
const h = h_result.value;
try std.testing.expectEqual(@as(i64, 1), h.getInt("op").?);
try std.testing.expectEqualStrings("#info", h.getString("t").?);
// decode payload — must have name and message fields (not error)
const p = try cbor.decodeAll(alloc, frame[h_result.consumed..]);
try std.testing.expectEqualStrings("OutdatedCursor", p.getString("name").?);
try std.testing.expectEqualStrings("Requested cursor exceeded limit. Possibly missing events", p.getString("message").?);
// info messages must NOT have an error field
try std.testing.expect(p.getString("error") == null);
}
test "concurrent broadcast queue + drain produces monotonic sequences" {
// regression test: multiple worker threads push to the broadcast queue
// under persist_order lock, then the broadcaster fiber drains and broadcasts.
// the ring buffer history must be strictly monotonic.
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer bc.deinit();
const num_threads = 8;
const frames_per_thread = 500;
const total_frames = num_threads * frames_per_thread;
var seq_counter = std.atomic.Value(u64).init(0);
const Worker = struct {
fn run(bc_ptr: *Broadcaster, counter: *std.atomic.Value(u64)) void {
for (0..frames_per_thread) |_| {
bc_ptr.lockPersistOrder(std.testing.io);
const seq = counter.fetchAdd(1, .monotonic) + 1;
const data = std.testing.allocator.dupe(u8, "x") catch {
bc_ptr.unlockPersistOrder();
continue;
};
bc_ptr.broadcast_queue.push(seq, data, &bc_ptr.stats, std.testing.io);
bc_ptr.unlockPersistOrder();
}
}
};
var threads: [num_threads]std.Thread = undefined;
for (&threads) |*t| {
t.* = std.Thread.spawn(.{}, Worker.run, .{ &bc, &seq_counter }) catch unreachable;
}
for (&threads) |*t| t.join();
// drain the queue (simulating the broadcaster fiber)
while (bc.broadcast_queue.pop()) |item| {
bc.broadcast(item.seq, item.data);
std.testing.allocator.free(@constCast(item.data));
}
// verify: ring buffer history has strictly monotonic sequences
const frames = try bc.history.framesSince(std.testing.allocator, 0);
defer {
for (frames) |f| std.testing.allocator.free(f.data);
std.testing.allocator.free(frames);
}
// history is capped at 50K, we pushed 4K — all should be present
try std.testing.expectEqual(total_frames, frames.len);
var prev_seq: u64 = 0;
for (frames) |f| {
if (f.seq <= prev_seq) {
std.debug.print("monotonicity violation: seq {d} after {d}\n", .{ f.seq, prev_seq });
return error.NonMonotonicSequence;
}
prev_seq = f.seq;
}
}
test "shutdown keeps draining until the last producer finishes" {
var shutdown = std.atomic.Value(bool){ .raw = true };
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &shutdown);
defer bc.deinit();
const drain = try std.Thread.spawn(.{}, Broadcaster.runBroadcastLoop, .{&bc});
defer drain.join();
defer bc.producers_done.store(true, .release);
for (1..10_001) |seq| {
const data = try std.testing.allocator.dupe(u8, "event");
bc.broadcast_queue.push(seq, data, &bc.stats, std.testing.io);
}
bc.producers_done.store(true, .release);
while (bc.stats.seq.load(.acquire) != 10_000) {
try std.testing.io.sleep(Io.Duration.fromMilliseconds(1), .awake);
}
try std.testing.expectEqual(@as(u32, 0), bc.broadcast_queue.depth());
}
test "push on a full ring sleeps instead of spinning, and completes once drained" {
// regression: 2026-10-18 — a full ring turned every producer into a
// busy spinner (7.5 cores on an 8-vCPU node) and starved the drain.
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer bc.deinit();
// fill the ring to capacity (CAPACITY - 1 usable slots)
var seq: u64 = 1;
while (bc.broadcast_queue.depth() < BroadcastQueue.CAPACITY - 1) : (seq += 1) {
const data = try std.testing.allocator.dupe(u8, "x");
bc.broadcast_queue.push(seq, data, &bc.stats, std.testing.io);
}
const Producer = struct {
fn run(b: *Broadcaster, s: u64, done: *std.atomic.Value(bool)) void {
const data = std.testing.allocator.dupe(u8, "y") catch unreachable;
b.broadcast_queue.push(s, data, &b.stats, std.testing.io);
done.store(true, .release);
}
};
var done = std.atomic.Value(bool){ .raw = false };
const t = try std.Thread.spawn(.{}, Producer.run, .{ &bc, seq, &done });
// give the producer time to exhaust its spin budget and start sleeping
try std.testing.io.sleep(Io.Duration.fromMilliseconds(30), .awake);
try std.testing.expect(!done.load(.acquire));
try std.testing.expect(bc.stats.broadcast_queue_full_waits.load(.acquire) > 0);
try std.testing.expect(bc.stats.broadcast_queue_full.load(.acquire) > 0);
// one pop frees a slot; the producer must complete
const item = bc.broadcast_queue.pop().?;
std.testing.allocator.free(@constCast(item.data));
t.join();
try std.testing.expect(done.load(.acquire));
while (bc.broadcast_queue.pop()) |it| std.testing.allocator.free(@constCast(it.data));
}
test "persist ordering lock backs off while held" {
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer bc.deinit();
bc.lockPersistOrder(std.testing.io);
const Waiter = struct {
fn run(b: *Broadcaster, acquired: *std.atomic.Value(bool)) void {
b.lockPersistOrder(std.testing.io);
acquired.store(true, .release);
b.unlockPersistOrder();
}
};
var acquired = std.atomic.Value(bool){ .raw = false };
const t = try std.Thread.spawn(.{}, Waiter.run, .{ &bc, &acquired });
try std.testing.io.sleep(Io.Duration.fromMilliseconds(30), .awake);
try std.testing.expect(!acquired.load(.acquire));
try std.testing.expect(bc.stats.persist_order_waits.load(.acquire) > 0);
bc.unlockPersistOrder();
t.join();
try std.testing.expect(acquired.load(.acquire));
}
test "broadcast skips a replaying consumer and never writes to a kicked socket" {
// the consumer's conn is undefined: any socket write from broadcast()
// or dropSlowConsumer would fault. a replaying consumer gets nothing live;
// a full consumer is kicked by flag only.
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer bc.deinit();
const consumer = try std.testing.allocator.create(Consumer);
consumer.* = .{
.conn = undefined,
.allocator = std.testing.allocator,
.io = std.testing.io,
.replaying = .{ .raw = true },
};
{
bc.consumers_mutex.lockUncancelable(bc.io);
defer bc.consumers_mutex.unlock(bc.io);
try bc.consumers.append(std.testing.allocator, consumer);
_ = bc.stats.consumer_count.fetchAdd(1, .monotonic);
}
bc.broadcast(1, "live-1");
try std.testing.expectEqual(@as(usize, 0), consumer.buf_len);
try std.testing.expectEqual(@as(u64, 0), bc.stats.frames_out.load(.acquire));
// hand off to live and fill the buffer: the next broadcast kicks by flag
consumer.replaying.store(false, .release);
while (consumer.buf_len < Consumer.BUFFER_CAP) {
try std.testing.expect(consumer.enqueueRaw("fill"));
}
bc.broadcast(2, "live-2");
try std.testing.expect(consumer.kicked.load(.acquire));
try std.testing.expect(!consumer.alive.load(.acquire));
try std.testing.expectEqual(@as(u64, 1), bc.stats.slow_consumers.load(.acquire));
try std.testing.expectEqual(@as(usize, 0), bc.consumerCount());
consumer.mutex.lockUncancelable(consumer.io);
while (consumer.dequeue()) |f| f.release();
consumer.mutex.unlock(consumer.io);
consumer.deinit();
std.testing.allocator.destroy(consumer);
}
test "replay handoff delivers staged live frames after the catch-up, in order, without duplicates" {
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &test_shutdown);
defer bc.deinit();
const consumer = try std.testing.allocator.create(Consumer);
defer std.testing.allocator.destroy(consumer);
defer consumer.deinit();
consumer.* = .{
.conn = undefined,
.allocator = std.testing.allocator,
.io = std.testing.io,
.replaying = .{ .raw = true },
};
{
bc.consumers_mutex.lockUncancelable(bc.io);
defer bc.consumers_mutex.unlock(bc.io);
try bc.consumers.append(std.testing.allocator, consumer);
_ = bc.stats.consumer_count.fetchAdd(1, .monotonic);
}
// replay delivers 1..3 while live 4 is skipped (it is on disk and the
// catch-up pass will deliver it)
try std.testing.expect(consumer.enqueueRaw("r1"));
try std.testing.expect(consumer.enqueueRaw("r2"));
bc.broadcast(4, "l4");
try std.testing.expect(consumer.enqueueRaw("r3"));
// handoff: live 5 and 6 are staged; the catch-up pass delivers 4 and 5
consumer.beginStaging();
bc.broadcast(5, "l5");
bc.broadcast(6, "l6");
try std.testing.expectEqual(@as(usize, 2), consumer.pending.items.len);
try std.testing.expect(consumer.enqueueRaw("r4"));
try std.testing.expect(consumer.enqueueRaw("r5"));
try std.testing.expect(consumer.finishStaging(5));
// live 7 goes straight to the buffer
bc.broadcast(7, "l7");
const expected = [_][]const u8{ "r1", "r2", "r3", "r4", "r5", "l6", "l7" };
consumer.mutex.lockUncancelable(consumer.io);
defer consumer.mutex.unlock(consumer.io);
for (expected) |want| {
const f = consumer.dequeue() orelse return error.MissingFrame;
defer f.release();
try std.testing.expectEqualStrings(want, f.data);
}
try std.testing.expectEqual(@as(usize, 0), consumer.buf_len);
try std.testing.expect(!consumer.staging);
bc.consumers_mutex.lockUncancelable(bc.io);
_ = bc.consumers.swapRemove(0);
bc.consumers_mutex.unlock(bc.io);
}
test "replay enqueue waits for buffer space instead of aborting" {
var consumer = Consumer{
.conn = undefined,
.allocator = std.testing.allocator,
.io = std.testing.io,
};
defer {
consumer.mutex.lockUncancelable(consumer.io);
while (consumer.dequeue()) |f| f.release();
consumer.mutex.unlock(consumer.io);
}
while (consumer.buf_len < Consumer.BUFFER_CAP) {
try std.testing.expect(consumer.enqueueRaw("fill"));
}
var waits = std.atomic.Value(u64){ .raw = 0 };
const Replayer = struct {
fn run(c: *Consumer, w: *std.atomic.Value(u64), ok: *std.atomic.Value(bool)) void {
ok.store(c.enqueueRawWait("late", &test_shutdown, w), .release);
}
};
var ok = std.atomic.Value(bool){ .raw = false };
const t = try std.Thread.spawn(.{}, Replayer.run, .{ &consumer, &waits, &ok });
try std.testing.io.sleep(Io.Duration.fromMilliseconds(40), .awake);
try std.testing.expect(waits.load(.acquire) > 0);
consumer.mutex.lockUncancelable(consumer.io);
const f = consumer.dequeue().?;
consumer.mutex.unlock(consumer.io);
f.release();
t.join();
try std.testing.expect(ok.load(.acquire));
// a dead consumer ends the wait with false
consumer.alive.store(false, .release);
try std.testing.expect(!consumer.enqueueRawWait("dead", &test_shutdown, &waits));
}
test "resequenceFrame preserves explicit commit flags and signed blocks" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const cbor = zat.cbor;
const header = try cbor.encodeAlloc(a, .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = "#commit" } },
} });
const payload = try cbor.encodeAlloc(a, .{ .map = &.{
.{ .key = "seq", .value = .{ .unsigned = 1 } },
.{ .key = "rebase", .value = .{ .boolean = true } },
.{ .key = "tooBig", .value = .{ .boolean = true } },
.{ .key = "blocks", .value = .{ .bytes = "signed CAR bytes" } },
} });
const frame = try std.mem.concat(a, u8, &.{ header, payload });
const result = resequenceFrame(a, frame, 42) orelse return error.ResequenceFailed;
const h = try cbor.decode(a, result);
const p = try cbor.decodeAll(a, result[h.consumed..]);
try std.testing.expectEqual(true, p.getBool("rebase").?);
try std.testing.expectEqual(true, p.getBool("tooBig").?);
try std.testing.expectEqualStrings("signed CAR bytes", p.getBytes("blocks").?);
try std.testing.expectEqual(@as(i64, 42), p.getInt("seq").?);
}
test "live-only mode does not retain RAM replay frames" {
var shutdown = std.atomic.Value(bool).init(false);
var bc = Broadcaster.init(std.testing.allocator, std.testing.io, &shutdown);
defer bc.deinit();
var dp: event_log_mod.DiskPersist = .{
.allocator = std.testing.allocator,
.io = std.testing.io,
.dir_path = "",
.dir = undefined,
.db = undefined,
.did_cache = undefined,
.host_id_cache = undefined,
.history_enabled = false,
};
bc.persist = &dp;
bc.broadcast(1, "not retained");
try std.testing.expectEqual(@as(usize, 0), bc.history.count());
dp.history_enabled = true;
bc.retain_ram_history = false;
bc.broadcast(2, "disk replay without RAM retention");
try std.testing.expectEqual(@as(usize, 0), bc.history.count());
bc.retain_ram_history = true;
bc.broadcast(3, "retained");
try std.testing.expectEqual(@as(usize, 1), bc.history.count());
}