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
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
|
//! pardes-replicas: a session and its clients in one process
//! (core/replica.zig), each a process of its own for what a process holds
//! (`Proc`): the session's own frontend typing in its view and drawing it,
//! and each client (a terminal's loop or a window's, by turns) joined from
//! the session's dump for a view of its own, typing at once over its own
//! delayed, jittered link, as monkey.zig's scripts type at a tty, through
//! the real `replica.Link` on a socket pair: it draws its view, asks for
//! the rows it lacks, takes a copy while idle, asks the session's digest
//! when quiet; one joins late, one leaves, one is put off the session once
//! and joins again for its view, and those past the views a session has
//! are refused until one is let go.
//!
//! Terminals cross as screen state (core/term/screen_state.zig): the session's
//! shell pane runs a full-screen program and then a `yes` flood (`--flood`
//! MB of it) while the clients type, its output stepped by the authority
//! and sent to each replica as deltas, once a frame and before any input
//! the authority steps, each replica acknowledging them over its link and
//! asking for the rows it scrolls back into and does not hold.
//!
//! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB]
//! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K]
//! zig build replicas -Dplatform=tui -Doptimize=ReleaseFast -- --screen-state <dir>
//!
//! `--echo` types a corpus into a shell instead, with and without the
//! predicted echo (core/term/echo.zig), and gates what it draws: below, at
//! "predicted echo". `--screen-state` runs recorded pty streams through
//! screen_state's soak and measures its encoder: below, at screenState.
//!
//! Gates, per seed and RTT: no replica diverges (every confirmed unit's
//! digests agree as it is replayed), and at quiescence every replica's
//! digest and every file's text are the authority's; every delta a replica applies leaves its
//! terminal what the authority's was at that version, and at quiescence it
//! is the authority's, cell for cell. Reported per RTT: how inputs went
//! (applied at once, stopped at a host call, left to the authority), how
//! units were taken (fast path, rollback for a misprediction or another's
//! input), what a speculative apply, a copy and a rollback cost against a
//! frame, and the terminals': deltas a second, wire bytes a second under
//! the flood, encode a frame (every peer), apply a delta.
const std = @import("std");
const libc = std.c;
const pardes = @import("pardes");
const replica = pardes.replica;
const screen_state = @import("term").screen_state;
const Echo = pardes.Echo;
const Key = pardes.Key;
const gpa = std.heap.c_allocator;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
var trace = false;
/// The PDF the soak opens (`--pdf`), absolute.
var pdf_path: ?[]const u8 = null;
const frame_us = 16_667;
/// A frontend's workers for pictures' draws (Kind.drawer, tui.zig
/// `Shell.draw`): each draw asked of any core here runs `draw_us` later,
/// as a worker's does, and lands on its core's loop then (`.draw`):
/// after the speculation that asked it may have been rolled back.
const Draws = struct {
var jobs: std.ArrayListUnmanaged(*pardes.host_io.KindJob) = .empty;
var net: ?*Net = null;
var now: u64 = 0;
const draw_us = 3_000;
fn go(_: ?*anyopaque, j: *pardes.host_io.KindJob) bool {
const n = net orelse return false;
jobs.append(gpa, j) catch return false;
n.send(.{ .at = now + draw_us, .n = 0, .kind = .draw, .who = 0, .bytes = &.{} }) catch {
_ = jobs.pop();
return false;
};
return true;
}
};
/// The authority's host: no frames drawn (a replica draws its own), and a
/// pty that echoes what it is written, 2 ms later, as a shell's.
const Host = struct {
echo: std.ArrayListUnmanaged(struct { pane: u8, bytes: []u8 }) = .empty,
/// The session draws its own view in its pump, as one with a frontend
/// of its own does (Pardes.pump), what that writes in its core and
/// none of the replicas' with it.
draws: bool = false,
/// The session's clock (`run`'s: its loop's, tui.zig `clockNow`): the
/// soak's time at a frame, an input of its own frontend's or a pty's
/// read; a pump woken by a client's mail alone reads the last again.
clocked: bool = false,
now_ns: u64 = 0,
/// Its core, and the view a step's Detach was typed in (tui.zig
/// `detach`: a client's link ends; the session's own view's is its
/// terminal's, which the soak has none of).
core: ?*pardes.Pardes = null,
detach_view: ?u8 = null,
fn watched(ctx: ?*anyopaque) bool {
const h: *Host = @ptrCast(@alignCast(ctx.?));
return h.draws;
}
fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
const h: *Host = @ptrCast(@alignCast(ctx.?));
h.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {};
}
fn ignore(_: ?*anyopaque, _: []const u8) void {}
fn now(ctx: ?*anyopaque) u64 {
const h: *Host = @ptrCast(@alignCast(ctx.?));
return h.now_ns;
}
fn detach(ctx: ?*anyopaque) void {
const h: *Host = @ptrCast(@alignCast(ctx.?));
h.detach_view = h.core.?.live;
}
/// A kind's job on a worker, as tui.zig's `job` runs one: its answer
/// the session's own step `draw_us` later (`.draw`, `Authority.output`),
/// as a worker's is its loop's event (with no `job`, Effect.perform runs
/// it at once on the core's side, inside the perform that asked it,
/// where no tape records it: a client replays that perform without it).
/// At the setup, before any client, at once inside this call.
fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void {
const h: *Host = @ptrCast(@alignCast(ctx.?));
const j = pardes.host_io.KindJob.take(h.core.?, pane, serial, token) orelse return;
if (Draws.go(null, j)) return;
j.run();
j.land(h.core.?);
}
const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .job = job };
const clocked_vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore, .now = now, .detach = detach, .job = job };
fn host(h: *Host) pardes.Host {
return .{ .ctx = h, .vtable = if (h.clocked) &clocked_vtable else &vtable };
}
};
const Kind = enum {
input,
to_authority,
to_replica,
echo,
frame,
output,
screen_down,
screen_up,
client_frame,
/// The session's own frontend's input, in its own view.
own,
/// A client's join: its dial at the session, its dump (or refusal)
/// back; its check of the session's digest asked and answered; its
/// bye; a wake its loop asked for (`quietCheck`); its quit.
dial,
dump,
refused,
check_up,
checked,
bye_up,
wake,
quit,
/// The session ended its link (a Detach typed in its view).
gone,
/// A picture's draw done on a worker, onto its loop (`Draws`).
draw,
};
const Msg = struct {
at: u64,
n: u64,
kind: Kind,
who: u16,
bytes: []u8,
/// An echo's: the client's input that made it (--echo); a bye's
/// `again`.
seq: u32 = 0,
/// The client's join it belongs to: one of an earlier join (its link
/// ended since) is dropped, as the closed socket drops it.
gen: u32 = 0,
fn order(_: void, a: Msg, b: Msg) std.math.Order {
if (a.at != b.at) return std.math.order(a.at, b.at);
return std.math.order(a.n, b.n);
}
};
const Link = struct {
last: u64 = 0,
/// When a message sent at `now` arrives: half the RTT, jitter on top,
/// and never before the one sent ahead of it (a stream keeps order).
fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 {
const at = @max(l.last + 1, now + one_way + random.uintLessThan(u64, jitter + 1));
l.last = at;
return at;
}
};
const Totals = struct {
inputs: u64 = 0,
speculated: u64 = 0,
stopped: u64 = 0,
unspeculated: u64 = 0,
units: u64 = 0,
fast: u64 = 0,
mispredicted: u64 = 0,
foreign: u64 = 0,
rebases: u64 = 0,
/// A client's digest compared with the session's (a unit's, quiet).
checks: u64 = 0,
copies: u64 = 0,
copy_bytes: u64 = 0,
divergences: u64 = 0,
unequal: u64 = 0,
spec_ns: std.ArrayListUnmanaged(u64) = .empty,
copy_ns: std.ArrayListUnmanaged(u64) = .empty,
rollback_ns: std.ArrayListUnmanaged(u64) = .empty,
// Terminals.
apply_ns: std.ArrayListUnmanaged(u64) = .empty,
frame_ns: std.ArrayListUnmanaged(u64) = .empty,
deltas: u64 = 0,
delta_bytes: u64 = 0,
unit_bytes: u64 = 0,
/// Deltas the replicas applied while the flood ran.
flood_deltas: u64 = 0,
flood_us: u64 = 0,
flood_delta_bytes: u64 = 0,
flood_unit_bytes: u64 = 0,
fetched: u64 = 0,
/// Bytes of rows sent before a step's unit, the step having read them.
filled_bytes: u64 = 0,
resets: u64 = 0,
screens_wrong: u64 = 0,
screens_checked: u64 = 0,
/// Joins from a dump, refused, again after a divergence put on it
/// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks.
joins: u64 = 0,
refused: u64 = 0,
rejoined: u64 = 0,
detached: u64 = 0,
agree: u64 = 0,
differ: u64 = 0,
/// Resizes the windows posted (each pass whose view's size is not
/// the window's: gui.zig `OwnView.run`).
resizes: u64 = 0,
/// Clients let go by a Detach typed in their view.
detach_words: u64 = 0,
/// Panes of each plain kind the session opened (image, life).
kind_panes: [3]u64 = @splat(0),
fn add(t: *Totals, s: *const replica.Stats) !void {
t.inputs += s.inputs;
t.speculated += s.speculated;
t.stopped += s.stopped;
t.unspeculated += s.unspeculated;
t.units += s.units;
t.fast += s.fast;
t.mispredicted += s.mispredicted;
t.foreign += s.foreign;
t.rebases += s.rebases;
t.checks += s.checks;
t.copies += s.copies;
t.copy_bytes += s.copy_bytes;
try t.spec_ns.appendSlice(gpa, s.spec_ns.items);
try t.copy_ns.appendSlice(gpa, s.copy_ns.items);
try t.rollback_ns.appendSlice(gpa, s.rollback_ns.items);
try t.apply_ns.appendSlice(gpa, s.apply_ns.items);
}
};
/// One client's next input: monkey.zig's mix, as events, and now and then
/// a wheel over the shell pane, which scrolls its history into view; a
/// file looked at (`looks`, its words) and a pane closed, the Panes and
/// Recent pickers (the store's and Recent's rows, the authority's), a jump;
/// a picture looked at, a game of life opened and a PDF looked at, at a
/// page and at a search's hit (plain kinds a client runs as the session
/// does, `looks` past the texts), the keys after going to its pane; a
/// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its
/// wheel; now and then a client's Detach.
fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script) pardes.Event {
const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()";
const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC";
if (script.at < script.n) {
script.at += 1;
return script.evs[script.at - 1];
}
switch (random.uintLessThan(u8, 46)) {
0...15 => {
buf[0] = typed[random.uintLessThan(usize, typed.len)];
return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
},
16...27 => {
buf[0] = normal[random.uintLessThan(usize, normal.len)];
return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } };
},
28...31 => return .{ .key = .{ .cp = Key.escape } },
32 => return .{ .key = .{ .cp = Key.enter } },
33 => return .{ .key = .{ .cp = Key.backspace } },
34 => return .{ .key = .{ .cp = switch (random.uintLessThan(u8, 4)) {
0 => Key.up,
1 => Key.down,
2 => Key.left,
else => Key.right,
} } },
35 => {
const n = random.intRangeAtMost(usize, 1, 24);
for (buf[0..n]) |*c| c.* = typed[random.uintLessThan(usize, typed.len)];
return .{ .paste = buf[0..n] };
},
36 => return .{ .command = switch (random.uintLessThan(u8, 14)) {
0 => "Newcol",
1 => "Zerox",
2 => "Undo",
3 => "Redo",
4 => "Search Panes",
5 => "Search Recent",
6, 7 => looks[random.uintLessThan(usize, looks.len)],
8 => "Del",
// A tab's width: every pane's layout, and a process global
// (config.tab_now) its step writes.
9 => "Tab 2",
10 => "Tab 8",
11 => "Life",
// Its link ended by the session (the session's own view's,
// its terminal's: none here).
12 => if (random.uintLessThan(u8, 4) == 0) "Detach" else "Undo",
else => return .{ .key = .{ .cp = if (random.boolean()) 'o' else 'i', .ctrl = true } },
} },
37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } },
38 => return .{ .mouse = .{ .button = .left, .kind = .press, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } },
39 => return .{ .mouse = .{ .button = .left, .kind = .release, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } },
// Out of a shell's tty mode and back: its text, a cursor and
// selections over it.
40 => return .{ .key = .{ .cp = 'b', .ctrl = true } },
// A search in the pane with the keyboard (a PDF's `/` is its own):
// `/`, a pattern, Enter.
41 => {
script.* = .{ .n = 2, .evs = .{ .{ .paste = ([_][]const u8{ "the", "view", "pardes" })[random.uintLessThan(usize, 3)] }, .{ .key = .{ .cp = Key.enter } }, undefined } };
return .{ .key = .{ .cp = '/', .text = "/" } };
},
// A sweep of B1 over the PDF: a selection (or a page's pan, or nothing).
42 => {
const at = aim.pdf orelse return .{ .key = .{ .cp = Key.escape } };
const x = at[0] + random.uintLessThan(u16, at[2]);
const y = at[1] + random.uintLessThan(u16, at[3]);
const x1 = at[0] + random.uintLessThan(u16, at[2]);
const y1 = @min(at[1] + at[3] - 1, y + random.uintLessThan(u16, 3));
script.* = .{ .n = 2, .evs = .{ .{ .mouse = .{ .button = .left, .kind = .drag, .col = x1, .row = y1 } }, .{ .mouse = .{ .button = .left, .kind = .release, .col = x1, .row = y1 } }, undefined } };
return .{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } };
},
// The wheel over the shell, which scrolls its history into view,
// or over the PDF, which glides.
else => {
const over = if (random.boolean()) aim.shell else if (aim.pdf) |p| [2]u16{ p[0] + p[2] / 2, p[1] + p[3] / 2 } else aim.shell;
const at = over orelse return .{ .key = .{ .cp = Key.escape } };
return .{ .mouse = .{ .button = if (random.uintLessThan(u8, 3) == 0) .wheel_down else .wheel_up, .kind = .press, .col = at[0], .row = at[1] } };
},
}
}
/// Where a typist's wheel and sweeps land in the session's view: the
/// shell's middle, the PDF's body (x, y, w, h).
const Aim = struct { shell: ?[2]u16, pdf: ?[4]u16 };
/// What a typist types in a row, after the first: a search's pattern and
/// Enter, a sweep's drag and release.
const Script = struct {
evs: [3]pardes.Event = undefined,
n: u8 = 0,
at: u8 = 0,
};
fn writeFile(path: [:0]const u8, lines: usize) !void {
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return error.OpenFailed;
defer _ = libc.close(fd);
var line: [80]u8 = undefined;
for (0..lines) |n| {
const text = try std.fmt.bufPrint(&line, "const value_{d:0>4} = {d};\t// a line to edit\n", .{ n, n *% 7919 });
if (libc.write(fd, text.ptr, text.len) != @as(isize, @intCast(text.len))) return error.WriteFailed;
}
}
fn writeText(path: [:0]const u8, text: []const u8) !void {
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return error.OpenFailed;
defer _ = libc.close(fd);
if (libc.write(fd, text.ptr, text.len) != @as(isize, @intCast(text.len))) return error.WriteFailed;
}
const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, flood_mb: u64 };
/// The terminal pane's screen as a hash of screen_state's dump of it.
/// The module's own replica behind the core's handle (Replica.screens).
fn replicaOf(r: *pardes.Term.Replica) *screen_state.Replica {
return @ptrCast(@alignCast(r));
}
/// The module's own track behind the core's handle (Screens.tracks).
fn trackOf(t: *pardes.Term.Track) *screen_state.Track {
return @ptrCast(@alignCast(t));
}
fn screenHash(t: *screen_state.Terminal) u64 {
var buf: [8192]u8 = undefined;
var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf);
screen_state.dumpScreen(t, &h.writer) catch {};
h.writer.flush() catch {};
return h.hasher.final();
}
/// A process's own globals, where the soak runs the session and every
/// client in one: a step writes `config.tab_now` from its core's settings
/// (exec.zig's Tab, a dump's load), which a client's process and the
/// session's each hold apart. Shared, one core's rollback that left it
/// stale would leave the other cores reading it too, and agree. And the
/// kinds a client caught breaking PA_PLAIN (Addon.distrust): shared, one
/// client's catch would leave every other without the kind's code at its
/// next join, never to run it (and diverge) again.
const Proc = struct {
tab_now: u16 = pardes.config.tab_width,
distrusted: @TypeOf(pardes.Addon.distrusted) = undefined,
ndistrusted: usize = 0,
var current: ?*Proc = null;
fn enter(p: *Proc) void {
if (current == p) return;
if (current) |was| {
was.tab_now = pardes.config.tab_now;
was.distrusted, was.ndistrusted = .{ pardes.Addon.distrusted, pardes.Addon.ndistrusted };
}
pardes.config.tab_now = p.tab_now;
pardes.Addon.distrusted, pardes.Addon.ndistrusted = .{ p.distrusted, p.ndistrusted };
current = p;
}
};
/// A client of the session: a process of its own (`proc`) whose loop is
/// the terminal's (tui.zig `runClient`) or the window's (gui.zig
/// `clientSession`), over the real `replica.Link` on a socket pair whose
/// other end the soak reads as the session's Peer does (`drain`). It joins
/// from the session's dump, may be refused (every view taken), leaves, and
/// joins again for its view after a divergence.
const Client = struct {
kind: enum { tty, window },
proc: Proc = .{},
link: replica.Link = undefined,
r: ?*replica.Replica = null,
fds: [2]c_int = .{ -1, -1 },
check: [:0]u8 = undefined,
/// The session's side of its socket: bytes not yet a whole frame, the
/// stamp before an input, and the inputs it took (Peer.seq).
got: std.ArrayListUnmanaged(u8) = .empty,
stamp: std.ArrayListUnmanaged(u8) = .empty,
seq: u32 = 0,
/// Its id and its terminals' peer at the session, and the view the
/// session made or keeps for it (`back`, joining again).
id: u16 = 0,
sid: u16 = 0,
view: u8 = 0,
back: ?u8 = null,
digest: u64 = 0,
/// Joins the session made for it (its side), and the one its replica
/// is of (0: none, its link ended).
gen: u32 = 0,
live: u32 = 0,
joined: bool = false,
dialling: bool = false,
/// Refusals in a row, until it gives up (a person would).
tries: u32 = 0,
left: usize,
cols: u16,
rows: u16,
last_input: u64 = 0,
asked_at: u64 = 0,
wake_at: u64 = 0,
drew: bool = false,
resize: ?pardes.Event = null,
/// What it types in a row (a search, a sweep).
script: Script = .{},
/// gui.zig `Client.posted`: a size posted once while it waits.
posted: ?@FieldType(pardes.Event, "resize") = null,
resizes: u32 = 0,
fn present(ctx: ?*anyopaque, _: *const pardes.Surface) void {
const cl: *Client = @ptrCast(@alignCast(ctx.?));
cl.drew = true;
}
/// tui.zig `Client.draw` (gui.zig's is the same): its own view drawn
/// outside any step, what presenting writes in the core put back.
fn draw(cl: *Client) void {
const r = cl.r.?;
const core = r.core();
const skipped = core.present_skipped;
const needs = core.needs_frame;
core.frames.mark_start = pardes.FrameStats.nowNs();
core.frames.mark_update = core.frames.mark_start;
cl.drew = false;
r.draw(.{ .ctx = cl, .f = present });
core.frames.mark_render = core.frames.mark_update;
cl.link.owed = core.present_skipped;
core.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed);
core.present_skipped = skipped;
core.needs_frame = needs;
cl.link.drawn(cl.drew);
}
/// gui.zig `OwnView.run` over its own view (`Replica.within`): the
/// window's size against the view's, a resize posted when they differ.
fn own(cl: *Client, core: *pardes.Pardes) anyerror!void {
const v = core.view();
const metrics: pardes.RowMetrics = .{ .body_w = 9, .body_h = 18, .tagline_w = 9, .tagline_h = 18 };
if (cl.cols == v.screen_w and cl.rows == v.screen_h and v.cell_pixels.w == 9 and v.cell_pixels.h == 18 and std.meta.eql(metrics, v.row_metrics)) return;
cl.resize = .{ .resize = .{ .cols = cl.cols, .rows = cl.rows, .cell_pixels = .{ .w = 9, .h = 18 }, .row_metrics = metrics } };
}
/// The window's own pass over its view, and what it posted fed.
fn within(cl: *Client) void {
if (cl.kind != .window) return;
cl.r.?.within(cl, own);
if (cl.resize) |ev| {
if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) {
cl.link.input(ev);
cl.resizes += 1;
}
cl.posted = ev.resize;
} else cl.posted = null;
cl.resize = null;
}
};
const Queue = std.PriorityQueue(Msg, void, Msg.order);
/// What travels: the queue, its order, and each client's links.
const Net = struct {
q: Queue = .empty,
n: u64 = 0,
random: std.Random,
one_way: u64,
jitter: u64,
up: [8]Link = @splat(.{}),
down: [8]Link = @splat(.{}),
fn send(net: *Net, m: Msg) !void {
var mm = m;
mm.n = net.n;
net.n += 1;
try net.q.push(gpa, mm);
}
/// Down client `c`'s link (the session's stream to it), `bytes` its.
fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void {
try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen });
}
};
/// What client `c` wrote to its socket since (its inputs, its terminal
/// messages, a check asked, its bye), read off the other end as the
/// session's Peer reads it (`Peer.take`), up its link.
fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void {
var buf: [1 << 16]u8 = undefined;
while (true) {
const k = libc.read(cl.fds[0], &buf, buf.len);
if (k <= 0) break;
try cl.got.appendSlice(gpa, buf[0..@intCast(k)]);
}
const wire = pardes.wire;
var at: usize = 0;
while (try wire.framed(cl.got.items[at..])) |f| : (at += f.total) {
const frame = cl.got.items[at..][0..f.total];
const kind: Kind = switch (std.enums.fromInt(wire.ClientTag, f.tag) orelse return error.BadFrame) {
.stamp => {
cl.stamp.clearRetainingCapacity();
try cl.stamp.appendSlice(gpa, frame);
continue;
},
.screen_ack => .screen_up,
.check => .check_up,
.bye => .bye_up,
else => .to_authority,
};
var seq: u32 = 0;
const bytes: []u8 = switch (kind) {
.to_authority => in: {
// Its head (its id and seq at the session), its stamp, its event.
cl.seq += 1;
const msg = try gpa.alloc(u8, 6 + cl.stamp.items.len + frame.len);
std.mem.writeInt(u16, msg[0..2], cl.id, .little);
std.mem.writeInt(u32, msg[2..6], cl.seq, .little);
@memcpy(msg[6..][0..cl.stamp.items.len], cl.stamp.items);
@memcpy(msg[6 + cl.stamp.items.len ..], frame);
cl.stamp.clearRetainingCapacity();
if (replica.parseInput(msg) == null) return error.BadInput;
break :in msg;
},
.screen_up => try gpa.dupe(u8, f.payload),
.bye_up => bye: {
seq = @intFromBool((try wire.decodeClient(f.tag, f.payload)).bye.again);
break :bye &.{};
},
else => &.{},
};
try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .seq = seq, .gen = cl.gen });
}
std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]);
cl.got.shrinkRetainingCapacity(cl.got.items.len - at);
}
/// The rest of a pass of the client's loop, after what woke it (an input
/// applied and sent, a message of the stream taken): as the two loops do
/// each time round (tui.zig `runClient`, gui.zig `clientSession`): its
/// inputs settled, a rollback drawn again, then its predicted echo judged,
/// its view drawn if anything changed (the rows it lacks asked after),
/// the copy taken while idle, and the session's digest asked once quiet.
fn pass(cl: *Client, c: usize, net: *Net, now: u64) !void {
const r = cl.r orelse return;
const link = &cl.link;
r.settle();
if (r.moved) {
r.moved = false;
link.dirty = true;
}
if (link.owed or r.echo.changed) link.dirty = true;
if (r.diverged != null) link.quit = true;
if (!link.quit) {
cl.within();
if (r.echoFrame()) link.dirty = true;
if (link.dirty) cl.draw();
// Idle, its frame drawn: the window whenever its wait is not 0,
// the terminal unless an event is held already (one pass in four).
if (cl.kind == .window or net.random.uintLessThan(u8, 4) != 0) r.ready();
// `quietCheck`, on the soak's clock: 300 ms after its last input
// and its last check, changed since and quiet, the digest asked.
if (link.changed and !link.asked and r.quiet()) {
const due = @max(cl.last_input, cl.asked_at) + 300_000;
if (now >= due) {
link.input_ns = 0;
link.asked_ns = 0;
_ = link.quietCheck();
cl.asked_at = now;
} else if (cl.wake_at < due) {
cl.wake_at = due;
try net.send(.{ .at = due, .n = 0, .kind = .wake, .who = @intCast(c + 1), .bytes = &.{}, .gen = cl.live });
}
}
}
try drain(cl, c, net, now);
}
/// Its link ended (it diverged, or it quits): its bye, and its join again
/// for its view after a divergence (`Link.rejoins`), the core it leaves
/// held until the dump comes, as `replica.join` holds it.
fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, typing: *usize) !void {
const r = cl.r.?;
const link = &cl.link;
// Its link ended by the session (a Detach), it says nothing more.
if (!link.gone) replica.bye(cl.fds[1], r.diverged != null);
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {
if (link.put_off) totals.rejoined += 1 else {
totals.divergences += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ run_.seed, run_.rtt_ms, c + 1, why });
}
}
if (link.rejoins()) {
cl.back = r.view;
cl.dialling = true;
return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
try totals.add(&r.stats);
r.deinit();
cl.r = null;
totals.detached += 1;
// Let go before it typed all it had: the rest is never typed.
if (link.gone) totals.detach_words += 1;
if (cl.left > 0) {
typing.* -= 1;
cl.left = 0;
}
}
fn run(r: Run, dir: []const u8, totals: *Totals) !void {
if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms });
// Last: the processes' globals were this run's.
defer Proc.current = null;
var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms);
const random = prng.random();
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var paths: [3][256:0]u8 = undefined;
var look_lines: [8][300]u8 = undefined;
var looks_buf: [8][]const u8 = undefined;
for (&paths, look_lines[0..3], looks_buf[0..3], 0..) |*p, *l, *look, i| {
const path = try std.fmt.bufPrintSentinel(p, "{s}/f{d}.zig", .{ dir, i }, 0);
try writeFile(path, 60 + 40 * i);
look.* = try std.fmt.bufPrint(l, "Look {s}", .{path});
}
// A picture (the image addon's), when
// the soak has their libraries (`--addon`).
var picture: [256:0]u8 = undefined;
var nlooks: usize = 3;
const kinds = pardes.Addon.scan();
for (kinds) |l| if (std.mem.eql(u8, l.name, "image")) {
const path = try std.fmt.bufPrintSentinel(&picture, "{s}/picture.ppm", .{dir}, 0);
var ppm: std.ArrayListUnmanaged(u8) = .empty;
defer ppm.deinit(gpa);
try ppm.print(gpa, "P6\n64 48\n255\n", .{});
for (0..48) |y| for (0..64) |x| try ppm.appendSlice(gpa, &.{ @intCast(x * 4), @intCast(y * 5), @intCast((x + y) * 2) });
try writeText(path, ppm.items);
looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}", .{path});
nlooks += 1;
};
// The PDF (`--pdf`, the pdf addon's), and two places in it: a page, a
// search's hit on a page (a miss until a search found one there).
const with_pdf = nlooks > 3 and pdf_path != null and for (kinds) |l| {
if (std.mem.eql(u8, l.name, "pdf")) break true;
} else false;
if (with_pdf) for ([_][]const u8{ "", ":3", ":1:1" }) |at| {
looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}{s}", .{ pdf_path.?, at });
nlooks += 1;
};
const looks = looks_buf[0..nlooks];
// The tty's own boot (a raw shell, a text pane under it), then three
// files looked at: the session's own frontend shows the first view
// and types in it; each client joins from a dump for a view of its own.
var session: Proc = .{};
session.enter();
host.clocked = true;
host.now_ns = std.time.ns_per_s;
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .addons = kinds }, host.host(), true);
defer {
session.enter();
a.deinit();
}
host.core = a.core;
var screens: replica.Screens = .init(gpa);
defer screens.deinit(a.core);
for (&paths) |*path| {
var line: [300]u8 = undefined;
_ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) });
}
// The picture and the PDF in a column of their own: every client joins
// with them (a plain kind's pane loaded from a dump, its file read by
// its path), its keys go to the one it is in when it has them.
if (looks.len > 3) {
_ = try a.local(.{ .command = "Newcol" });
_ = try a.local(.{ .command = looks[3] });
}
if (with_pdf) _ = try a.local(.{ .command = looks[4] });
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
} else return error.NoShell;
// Where a wheel over the shell lands in the session's view, which a
// client's view is a copy of as it joins; and the PDF's body there.
const sr = a.core.view().rects[shell];
const pr = if (with_pdf) a.core.view().rects[a.core.view().active] else pardes.Rect{};
const aim: Aim = .{
.shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null,
.pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } else null,
};
var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 };
defer {
while (net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes);
net.q.deinit(gpa);
}
pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go };
Draws.net = &net;
defer {
pardes.Kind.drawer = null;
Draws.net = null;
for (Draws.jobs.items) |j| j.drop();
Draws.jobs.clearRetainingCapacity();
}
// The clients: terminals and windows by turns. The first two dial at
// once, the third late (the shell's program on), more later still
// (refused while every view is taken, dialling again until one is
// let go); the first leaves when it is done; the second is put off
// the session once (PARDES_TEST_DIVERGE) and joins again for its view.
var clients: [8]Client = undefined;
for (clients[0..r.clients], 0..) |*cl, c| {
cl.* = .{ .kind = if (c % 2 == 0) .tty else .window, .left = r.steps, .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) };
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &cl.fds) != 0) return error.NoSocket;
_ = libc.fcntl(cl.fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true })));
var name: [300]u8 = undefined;
cl.check = try gpa.dupeSentinel(u8, try std.fmt.bufPrint(&name, "{s}/check-{d}", .{ dir, c }), 0);
_ = libc.unlink(cl.check);
cl.dialling = true;
const at: u64 = switch (c) {
0, 1 => random.uintLessThan(u64, 100_000),
2 => 1_200_000,
else => 2_000_000 + c * 100_000,
};
try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
defer for (clients[0..r.clients]) |*cl| {
cl.proc.enter();
if (cl.r) |rp| rp.deinit();
_ = libc.close(cl.fds[0]);
_ = libc.close(cl.fds[1]);
cl.got.deinit(gpa);
cl.stamp.deinit(gpa);
gpa.free(cl.check);
};
// The link is made at the first join (its replica the dump's).
var has_link: [8]bool = @splat(false);
defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) {
cl.link.check = null;
cl.link.deinit(gpa);
};
// What the shell's program prints: a full-screen program, a shell's
// session (prompts, titles, directories, a clear now and then), then a
// flood of `yes`, read 4 KB at a time as a pty gives it.
const tui = try screen_state.tuiStream(gpa);
defer gpa.free(tui);
const shell_session = try screen_state.shellStream(gpa);
defer gpa.free(shell_session);
const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3));
defer gpa.free(yes);
const tui_at: u64 = 400_000;
const session_at: u64 = 1_000_000;
const flood_at: u64 = 2_500_000;
var flood_end: u64 = 0;
var program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{};
// The authority's version of each terminal, as its screen showed then.
var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty;
defer versions.deinit(gpa);
var flood_deltas: [8]u64 = @splat(0);
// The session's own typist, and every client's, until each is done.
var own_left = r.steps;
var own_script: Script = .{};
var typing: usize = r.clients + 1;
var next_id: u16 = 1;
try net.send(.{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} });
try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} });
try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} });
try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} });
try net.send(.{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
var frames_left: u32 = 0;
var owed: std.ArrayListUnmanaged([]u8) = .empty;
defer owed.deinit(gpa);
const Session = struct {
a: *replica.Authority,
screens: *replica.Screens,
clients: []Client,
net: *Net,
owed: *std.ArrayListUnmanaged([]u8),
versions: *std.AutoHashMapUnmanaged(u64, u64),
totals: *Totals,
host: *Host,
kinds_seen: *u32,
/// A Detach its step took (Host.detach) in a client's view: that
/// client's link shut inside the step, before its unit goes
/// (Peers.detach), so it hears its end and not the unit; which it is.
fn detaching(s: @This(), now: u64) !?usize {
const k = s.host.detach_view orelse return null;
s.host.detach_view = null;
for (s.clients, 0..) |*cl, c| if (cl.joined and cl.view == k) {
cl.joined = false;
s.screens.dropPeer(cl.sid);
try s.net.toClient(c, now, .gone, cl.gen, &.{});
return c;
};
return null;
}
/// ...and let go at the next boundary, its view closed (Peers.leave).
fn detached(s: @This(), c: ?usize, now: u64) !void {
const gone = c orelse return;
try s.unit(try s.a.leave(s.clients[gone].id, false), now, false);
}
/// The batch of its own steps as a unit, if any (`Authority.pending`).
fn pending(s: @This(), now: u64, flooding: bool) !void {
if (try s.a.pending()) |batch| try s.unit(batch, now, flooding);
}
/// A unit to every client joined (Peers.unit), after the rows of
/// its terminals its steps read that a client holds as holes.
fn unit(s: @This(), u: []const u8, now: u64, flooding: bool) !void {
// The kinds' panes it has opened, each counted once.
for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) {
s.kinds_seen.* = pane.serial;
for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name));
};
var rows: std.ArrayListUnmanaged([]u8) = .empty;
defer rows.deinit(gpa);
for (s.clients, 0..) |*cl, c| if (cl.joined) {
rows.clearRetainingCapacity();
try s.screens.fill(s.a.core, cl.sid, &rows);
for (rows.items) |bytes| {
s.totals.filled_bytes += bytes.len;
try s.net.toClient(c, now, .screen_down, cl.gen, bytes);
}
};
s.screens.filled(s.a.core);
// The sizes its steps gave terminals, after their rows.
pardes.panes.resizeDeferred(s.a.core);
for (s.clients, 0..) |*cl, c| if (cl.joined) {
s.totals.unit_bytes += u.len;
if (flooding) s.totals.flood_unit_bytes += u.len;
try s.net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, u));
};
}
/// What each client is owed of the terminals (`Screens.flush`).
fn flush(s: @This(), now: u64, only: ?usize) !void {
for (s.clients, 0..) |*cl, c| if (cl.joined and (only == null or only.? == c)) {
s.owed.clearRetainingCapacity();
try s.screens.flush(s.a.core, cl.sid, 0, s.owed);
for (s.owed.items) |bytes| {
s.totals.deltas += 1;
s.totals.delta_bytes += bytes.len;
try s.net.toClient(c, now, .screen_down, cl.gen, bytes);
}
};
// Each version as the authority's screen showed it.
for (&s.screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| {
const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version;
if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue;
_ = s.a.core.panes[id] orelse continue;
try s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt));
};
}
};
var kinds_seen: u32 = 0;
const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals, .host = &host, .kinds_seen = &kinds_seen };
while (net.q.pop()) |m| {
defer if (m.bytes.len > 0) gpa.free(m.bytes);
Draws.now = m.at;
const flooding = m.at >= flood_at and flood_end == 0;
// A client's message, but an echo's and an output's `who` (a pane,
// a program).
const c: usize = if (m.who == 0 or m.kind == .echo or m.kind == .output) 0 else m.who - 1;
const cl = &clients[c];
switch (m.kind) {
// ---- the session ----
.own => {
session.enter();
host.now_ns = std.time.ns_per_s + m.at * 1000;
var buf: [64]u8 = undefined;
const ev = nextEvent(random, &buf, aim, looks, &own_script);
try ses.pending(m.at, flooding);
try ses.flush(m.at, null);
const u = try a.own(ev);
// Its own view's Detach is its terminal's: none here.
host.detach_view = null;
try ses.unit(u, m.at, false);
try ses.flush(m.at, null);
for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes });
host.echo.clearRetainingCapacity();
own_left -= 1;
if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1;
},
.to_authority, .echo, .output => {
session.enter();
// A pty's read wakes its loop as an input does; a client's
// mail alone leaves the clock where it was.
if (m.kind != .to_authority) host.now_ns = std.time.ns_per_s + m.at * 1000;
const unit = switch (m.kind) {
.echo => echo: {
a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } });
break :echo null;
},
.output => out: {
// The program's next read, 4 KB, then the next a
// fraction of a millisecond on (ghostty's pace).
if (program.at == program.bytes.len) {
program = .{ .bytes = switch (m.who) {
0 => tui,
1 => yes,
else => shell_session,
} };
}
const k = @min(program.bytes.len - program.at, if (m.who == 1) @as(usize, 4096) else 700);
const chunk = program.bytes[program.at..][0..k];
program.at += k;
if (program.at < program.bytes.len)
try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} })
else if (m.who == 1) flood_end = m.at;
a.output(.{ .output = .{ .pane = shell, .bytes = chunk } });
break :out null;
},
else => in: {
if (!cl.joined or m.gen != cl.gen) break :in null;
// The authority's own steps since the last unit, and
// the terminals as they are: what the input's step
// reads, before it is stepped (Peers.input).
try ses.pending(m.at, flooding);
try ses.flush(m.at, null);
break :in try a.take(m.bytes);
},
};
if (unit) |u| {
const gone = try ses.detaching(m.at);
try ses.unit(u, m.at, false);
try ses.detached(gone, m.at);
try ses.flush(m.at, null);
}
for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes });
host.echo.clearRetainingCapacity();
},
.frame => {
session.enter();
// Its own frontend's frame: its loop woken when a frame is
// owed or the core's next wake is due, a pump that advances
// its clock (what is due ticks: messages, glides, a kind's
// tick) and draws its view, as its host's loop paces it.
host.now_ns = std.time.ns_per_s + m.at * 1000;
if (a.core.needs_frame or (a.core.nextWake() orelse std.math.maxInt(u64)) <= host.now_ns) {
host.draws = true;
a.pump();
host.draws = false;
}
try ses.pending(m.at, flooding);
const t0 = screens.encode_ns;
const before = totals.delta_bytes;
try ses.flush(m.at, null);
if (m.at >= flood_at and (flood_end == 0 or m.at <= flood_end)) {
totals.flood_delta_bytes += totals.delta_bytes - before;
try totals.frame_ns.append(gpa, screens.encode_ns - t0);
}
// Frames go on while anyone types or the flood runs, and two
// seconds after (a session with a clock wakes on: a blink, a
// kind's tick; what is in flight still comes, unpumped).
const busy = typing > 0 or flood_end == 0;
frames_left = if (busy) 120 else frames_left -| 1;
if (frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
},
.dial => {
// Peers.join at the session's next boundary: its view kept
// for it, or a new one, or refused when all are taken.
session.enter();
try ses.pending(m.at, flooding);
const id = next_id;
const j = (try a.join(id, cl.back)) orelse {
totals.refused += 1;
try net.toClient(c, m.at, .refused, cl.gen, &.{});
continue;
};
next_id += 1;
try ses.unit(j.unit, m.at, false);
cl.joined = true;
cl.gen += 1;
cl.id = id;
cl.seq = 0;
cl.view = j.view;
cl.digest = j.digest;
cl.sid = try screens.addPeer();
totals.joins += 1;
try net.toClient(c, m.at, .dump, cl.gen, j.dump);
// Its terminals afresh, after its dump and before any unit.
try ses.flush(m.at, c);
},
.check_up => {
session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
const d = try gpa.alloc(u8, 8);
std.mem.writeInt(u64, d[0..8], replica.digestOf(a), .little);
try net.toClient(c, m.at, .checked, cl.gen, d);
},
.bye_up => {
// Peers.leave: its view kept for it (`again`) or closed.
session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
try ses.pending(m.at, flooding);
cl.joined = false;
screens.dropPeer(cl.sid);
try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false);
},
.screen_up => {
session.enter();
if (!cl.joined or m.gen != cl.gen) continue;
if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little);
if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer);
},
// ---- a client ----
.refused => {
if (!cl.dialling) continue;
// Said and gone; started again a while later (a person
// does), while it has keys left to type.
cl.back = null;
if (cl.r) |old| {
cl.proc.enter();
try totals.add(&old.stats);
old.deinit();
cl.r = null;
}
cl.tries += 1;
if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else {
// Given up on: its keys are never typed.
cl.dialling = false;
if (cl.left > 0) typing -= 1;
cl.left = 0;
}
},
.dump => {
cl.proc.enter();
cl.dialling = false;
cl.tries = 0;
// replica.join: the core it left let go once the new one
// is here, the dump loaded and checked by the digest.
if (cl.r) |old| {
try totals.add(&old.stats);
old.deinit();
}
const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows });
cl.r = rp;
rp.stats.samples = true;
rp.t.local_files = true;
rp.echo.now = m.at * 1000;
if (!rp.loaded(cl.digest)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ r.seed, r.rtt_ms, m.who });
}
cl.live = m.gen;
var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} };
if (!has_link[c]) {
cl.link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check };
has_link[c] = true;
if (c == 1) cl.link.test_diverge = 40;
}
cl.link.reset(rp, &j);
cl.posted = null;
// What it is, then its size, are its view's first inputs
// (the window's size from its own pass over its view).
cl.link.input(.{ .frontend = if (cl.kind == .window) .{ .windowed = true, .native_images = true, .native_image_patches = true } else .{ .windowed = false } });
if (cl.kind == .tty) cl.link.input(.{ .resize = .{ .cols = cl.cols, .rows = cl.rows } });
cl.last_input = m.at;
try pass(cl, c, &net, m.at);
if (cl.left > 0 and cl.left == r.steps) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
},
.draw => {
// A worker's draw done, onto the loop of the core that asked
// it (tui.zig `.kind_job`): kept for its pane's next paint,
// a frame owed; one of a core gone since is let go.
const j = Draws.jobs.orderedRemove(0);
j.run();
// A state job's answer: a step of the session's own.
if (j.draw == null) {
session.enter();
host.now_ns = std.time.ns_per_s + m.at * 1000;
a.output(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
j.drop();
continue;
}
if (j.draw == @as(?*const pardes.Pardes, a.core)) {
session.enter();
pardes.Kind.landDraw(a.core, j);
continue;
}
const k = for (clients[0..r.clients], 0..) |*dc, k| {
if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k;
} else {
j.drop();
continue;
};
const dc = &clients[k];
dc.proc.enter();
pardes.Kind.landDraw(dc.r.?.core(), j);
dc.link.dirty = true;
try pass(dc, k, &net, m.at);
if (dc.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing);
},
.input, .to_replica, .screen_down, .checked, .wake, .quit, .gone => {
cl.proc.enter();
if (m.kind == .input and cl.left == 0) continue;
const rp = cl.r orelse if (m.kind == .input and cl.dialling) {
try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
continue;
} else continue;
if (m.kind == .input) {
// A key typed while it joins again waits for the link.
if (cl.live == 0) {
try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} });
continue;
}
} else if (m.kind != .quit and m.gen != cl.live) continue;
rp.echo.now = m.at * 1000;
switch (m.kind) {
.input => {
var buf: [64]u8 = undefined;
const ev = nextEvent(random, &buf, aim, looks, &cl.script);
cl.within();
cl.link.input(ev);
cl.last_input = m.at;
cl.left -= 1;
if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else {
typing -= 1;
// The first leaves once it is done.
if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} });
}
},
.to_replica => cl.link.take(.{ .unit = try gpa.dupe(u8, m.bytes) }),
.screen_down => {
const pane = m.bytes[0];
const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0;
cl.link.take(.{ .screen = try gpa.dupe(u8, m.bytes) });
if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| {
const now_seq = replicaOf(sc.rep).seq;
if (now_seq == was) totals.resets += 1 else {
// Applied: the screen is the authority's at that version.
totals.screens_checked += 1;
const want = versions.get(@as(u64, sc.serial) << 32 | now_seq);
const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt;
if (want == null or want.? != screenHash(vt)) {
totals.screens_wrong += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, now_seq });
}
// Deltas while the flood runs (an RTT/2 behind it).
if (m.at >= flood_at + net.one_way and (flood_end == 0 or m.at <= flood_end + net.one_way)) flood_deltas[c] += 1;
}
};
},
.checked => cl.link.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }),
.wake => cl.wake_at = 0,
.quit => cl.link.quit = true,
.gone => {
cl.link.quit = true;
cl.link.gone = true;
},
else => unreachable,
}
try pass(cl, c, &net, m.at);
if (cl.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing);
},
.client_frame => {},
}
}
totals.flood_us += flood_end -| flood_at;
for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d;
session.enter();
const want = replica.digestOf(a);
for (clients[0..r.clients], 1..) |*cl, id| {
totals.resizes += cl.resizes;
// Its quiet checks: what the session's digest was against its own.
if (readAll(cl.check)) |said| {
defer gpa.free(said);
var lines = std.mem.tokenizeScalar(u8, said, '\n');
while (lines.next()) |line| if (std.mem.startsWith(u8, line, "agree")) {
totals.agree += 1;
} else {
totals.differ += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s quiet check: {s}\n", .{ r.seed, r.rtt_ms, id, line });
};
}
const rp = cl.r orelse continue;
cl.proc.enter();
try totals.add(&rp.stats);
if (cl.live == 0) continue;
if (rp.diverged) |why| {
totals.divergences += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ r.seed, r.rtt_ms, id, why });
} else if (!rp.quiet() or rp.digest() != want) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ r.seed, r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" });
}
// At quiescence, every terminal the authority's, cell for cell.
for (a.core.panes, 0..) |slot, pid| {
const pane = slot orelse continue;
const state = pane.terminal orelse continue;
const mine = (rp.core().panes[pid] orelse {
totals.unequal += 1;
continue;
}).terminal orelse continue;
if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid });
}
}
// ...and every file's text the authority's, byte for byte: a digest
// takes a text of 4 KiB and up by its length (core/walk.zig).
for (a.core.panes, 0..) |slot, pid| {
const f = (slot orelse continue).file orelse continue;
const mine = if (rp.core().panes[pid]) |pane| pane.file else null;
if (mine == null or !std.mem.eql(u8, f.content, mine.?.content)) {
totals.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: client {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid });
}
}
}
session.enter();
}
/// A typist: keys 50-200 ms apart, a pause now and then.
fn typistGap(random: std.Random) u64 {
return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000);
}
/// A file's bytes, or null.
fn readAll(path: [:0]const u8) ?[]u8 {
const fd = libc.open(path, .{ .ACCMODE = .RDONLY });
if (fd < 0) return null;
defer _ = libc.close(fd);
var out: std.ArrayListUnmanaged(u8) = .empty;
var buf: [4096]u8 = undefined;
while (true) {
const k = libc.read(fd, &buf, buf.len);
if (k <= 0) break;
out.appendSlice(gpa, buf[0..@intCast(k)]) catch return null;
}
return out.toOwnedSlice(gpa) catch null;
}
/// A .patch looked at opens a +Diff, whose rows are made from files read
/// in the step (hunks.zig: the patch, the file each section names, its
/// declarations). Looked at by the authority, a replica replays the reads
/// the unit carries and makes the same +Diff; looked at as the replica's own
/// input, the first read poisons the speculation, which shows nothing and
/// waits for the authority's unit (no rollback of what it showed). Either
/// way the replica's digest and the +Diff's text are the authority's.
fn diffCase(dir: []const u8) !bool {
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var buf: [256]u8 = undefined;
const source = try std.fmt.bufPrintSentinel(&buf, "{s}/a.zig", .{dir}, 0);
try writeText(source, "// one\n// two\nconst S = struct {\n fn f() void {\n a();\n b();\n log();\n }\n};\n");
var pbuf: [256]u8 = undefined;
const patch = try std.fmt.bufPrintSentinel(&pbuf, "{s}/change.patch", .{dir}, 0);
try writeText(patch, "--- a.zig\n+++ a.zig\n@@ -3,4 +3,5 @@\n fn f() void {\n- c();\n+ a();\n b();\n+ log();\n }\n");
var lbuf: [300]u8 = undefined;
const look = try std.fmt.bufPrint(&lbuf, "Look {s}", .{patch});
var ok = true;
for ([_]bool{ false, true }) |own| {
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
if (own) {
const msg = try gpa.dupe(u8, try rp.input(.{ .command = look }));
defer gpa.free(msg);
if (rp.stats.stopped != 1) {
std.debug.print("diff: the replica's own look at a .patch was not stopped at its first read ({d} stopped, {d} applied)\n", .{ rp.stats.stopped, rp.stats.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
} else rp.confirm(try a.local(.{ .command = look }));
rp.settle();
const named = for (a.core.panes, 0..) |slot, pid| {
const f = (slot orelse continue).file orelse continue;
if (std.mem.endsWith(u8, f.path, "/+Diff")) break pid;
} else null;
const mine = if (named) |pid| if (rp.core().panes[pid]) |pane| pane.file else null else null;
if (named == null or mine == null or !std.mem.eql(u8, a.core.panes[named.?].?.file.?.content, mine.?.content) or
std.mem.indexOf(u8, mine.?.content, "a.zig:5 *") == null)
{
std.debug.print("diff: {s}: the replica holds no +Diff of the authority's\n", .{if (own) "its own look" else "the authority's look"});
ok = false;
}
if (rp.diverged) |why| {
std.debug.print("diff: {s}: the replica diverged: {s}\n", .{ if (own) "its own look" else "the authority's look", why });
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("diff: {s}: the replica's digest is not the authority's\n", .{if (own) "its own look" else "the authority's look"});
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("diff: {s}: {d} rollbacks\n", .{ if (own) "its own look" else "the authority's look", rp.stats.mispredicted + rp.stats.foreign });
ok = false;
}
}
std.debug.print("diff: a .patch looked at by the authority and as a replica's own input: {s}\n", .{if (ok) "the same +Diff" else "FAILED"});
return ok;
}
/// Looks the plumber takes (core/plumbing), each as the authority's input
/// and as a replica's own: a URL (its web port: no disk asked, so a
/// replica's own look speculates whole and is confirmed with no rollback),
/// and a commit hash in a git work tree (Diff's `git show`, its `.git`
/// asked at a read the unit carries). The replica's digest is the
/// authority's either way.
fn plumbCase(dir: []const u8) !bool {
var host: Host = .{};
defer {
for (host.echo.items) |e| gpa.free(e.bytes);
host.echo.deinit(gpa);
}
var gbuf: [256]u8 = undefined;
try std.Io.Dir.createDirAbsolute(std.Io.Threaded.global_single_threaded.io(), try std.fmt.bufPrint(&gbuf, "{s}/.git", .{dir}), .default_dir);
var nbuf: [256]u8 = undefined;
const notes = try std.fmt.bufPrintSentinel(&nbuf, "{s}/notes.txt", .{dir}, 0);
try writeText(notes, "fixed in 3f2a9c1, see https://ziglang.org\n");
var obuf: [300]u8 = undefined;
const open = try std.fmt.bufPrint(&obuf, "Look {s}", .{notes});
var ok = true;
for ([_][]const u8{ "Look https://ziglang.org", "Look 3f2a9c1" }) |look| for ([_]bool{ false, true }) |own| {
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
rp.confirm(try a.local(.{ .command = open }));
rp.settle();
const before = rp.stats;
const url = std.mem.indexOf(u8, look, "://") != null;
if (own) {
const msg = try gpa.dupe(u8, try rp.input(.{ .command = look }));
defer gpa.free(msg);
if (url and (rp.stats.stopped != before.stopped or rp.stats.speculated == before.speculated)) {
std.debug.print("plumb: {s}: the replica's own look did not speculate whole ({d} stopped, {d} applied)\n", .{ look, rp.stats.stopped, rp.stats.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
} else rp.confirm(try a.local(.{ .command = look }));
rp.settle();
const who = if (own) "its own look" else "the authority's look";
if (!url) {
const paged = for (a.core.panes) |slot| {
if ((slot orelse continue).command_pages) break true;
} else false;
if (!paged) {
std.debug.print("plumb: {s}: {s}: no git show paged\n", .{ look, who });
ok = false;
}
}
if (rp.diverged) |why| {
std.debug.print("plumb: {s}: {s}: the replica diverged: {s}\n", .{ look, who, why });
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("plumb: {s}: {s}: the replica's digest is not the authority's\n", .{ look, who });
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("plumb: {s}: {s}: {d} rollbacks\n", .{ look, who, rp.stats.mispredicted + rp.stats.foreign });
ok = false;
}
};
// A rule to a port a program reads (plumb/seemail), of a URL, which a
// look reads no disk for: whether the port is read is the authority's
// 9P state, asked through the tape. A replica's own look waits for the
// first answer, then guesses the last; the second look speculates whole
// and is confirmed with no rollback.
{
// The rule from the session's plumbing file, read at boot.
var pbuf: [256]u8 = undefined;
try writeText(try std.fmt.bufPrintSentinel(&pbuf, "{s}/plumbing", .{dir}, 0), "type is text\ndata matches 'https://letters/.*'\nplumb to seemail\n\ninclude basic\n");
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host(), true);
defer a.deinit();
const first = try gpa.dupe(u8, try a.unit(0, 0));
defer gpa.free(first);
const rp = try replica.Replica.init(gpa, 1, first, true);
defer rp.deinit();
rp.confirm(try a.local(.{ .command = open }));
rp.settle();
if (pardes.Plumb.portIndex(rp.core(), "seemail") == null) {
std.debug.print("plumb: a look to a port: the plumbing file's port is not the replica's\n", .{});
ok = false;
}
for (0..2) |n| {
const before = rp.stats;
const msg = try gpa.dupe(u8, try rp.input(.{ .command = "Look https://letters/42" }));
defer gpa.free(msg);
if (n == 1 and (rp.stats.stopped != before.stopped or rp.stats.speculated == before.speculated)) {
std.debug.print("plumb: a look to a port: the replica's second look did not speculate whole ({d} stopped, {d} applied)\n", .{ rp.stats.stopped - before.stopped, rp.stats.speculated - before.speculated });
ok = false;
}
if (try a.pending()) |batch| rp.confirm(batch);
rp.confirm(try a.take(msg));
rp.settle();
}
if (rp.diverged) |why| {
std.debug.print("plumb: a look to a port: the replica diverged: {s}\n", .{why});
ok = false;
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
std.debug.print("plumb: a look to a port: the replica's digest is not the authority's\n", .{});
ok = false;
}
if (rp.stats.mispredicted + rp.stats.foreign != 0) {
std.debug.print("plumb: a look to a port: {d} rollbacks\n", .{rp.stats.mispredicted + rp.stats.foreign});
ok = false;
}
}
std.debug.print("plumb: a URL, a commit hash and a look to a port read by programs, by the authority and as a replica's own input: {s}\n", .{if (ok) "the same session" else "FAILED"});
return ok;
}
fn push(q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, m: Msg) !void {
var mm = m;
mm.n = nn.*;
nn.* += 1;
try q.push(gpa, mm);
}
/// What each peer is owed of the terminals, onto its link (before the
/// authority steps an input, and once a frame); each version as the
/// authority's screen showed it.
fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *std.ArrayListUnmanaged([]u8), q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, now: u64, dl: []Link, rnd: std.Random, ow: u64, jt: u64, vs: *std.AutoHashMapUnmanaged(u64, u64), tot: *Totals) !void {
for (ps, 0..) |peer, c| {
list.clearRetainingCapacity();
// Terminals alone cross: the view is not read.
try sc.flush(core, peer, 0, list);
for (list.items) |bytes| {
tot.deltas += 1;
tot.delta_bytes += bytes.len;
try push(q, nn, .{ .at = dl[c].arrive(rnd, now, ow, jt), .n = 0, .kind = .screen_down, .who = @intCast(c + 1), .bytes = bytes });
}
}
// Each version as the authority's screen showed it.
for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| {
const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version;
if (trackOf(tr.track).version == 0 or vs.contains(key)) continue;
_ = core.panes[id] orelse continue;
try vs.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt));
};
}
/// A unit of the authority's to every replica, down its link: first the
/// rows of its terminals its step read that a replica holds as holes.
fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void {
var rows: std.ArrayListUnmanaged([]u8) = .empty;
defer rows.deinit(gpa);
for (down, peers, 1..) |*l, peer, who| {
rows.clearRetainingCapacity();
try screens.fill(core, peer, &rows);
for (rows.items) |bytes| {
totals.filled_bytes += bytes.len;
try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes });
n.* += 1;
}
}
screens.filled(core);
// The sizes its steps gave terminals, after their rows (Peers.unit).
pardes.panes.resizeDeferred(core);
totals.unit_bytes += unit.len * down.len;
if (flooding) totals.flood_unit_bytes += unit.len * down.len;
for (down, 1..) |*l, who| {
try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .to_replica, .who = @intCast(who), .bytes = try gpa.dupe(u8, unit) });
n.* += 1;
}
}
// ---- predicted echo (--echo): one client typing a corpus into a shell ----
//
// The authority's pty is a shell played here (`FakeShell`): a line editor at
// a prompt with pardes's OSC 133 marks and Tab completion, and the programs
// the corpus runs in it: a password prompt (no echo), vim (the alternate
// screen), a program that ignores what is typed, and `cat` (the kernel's
// plain echo, no marks). Each key's echo comes back 2 ms after the authority
// writes it, as a shell's. The client types at a typist's pace and in bursts;
// each of its frames (60 Hz, a phase of its own) is what its screen shows:
// the predicted echo where it is drawn (core/term/echo.zig), the screen state
// under it. Per key the shell echoed at a prompt or in cat: the time from
// the key to its character on that screen, with prediction and without. Per
// key predicted: whether the authority's screen, right after its echo,
// shows what was predicted where it was. Per key drawn wrong: its frames.
const ascii: [128][1]u8 = blk: {
var t: [128][1]u8 = undefined;
for (&t, 0..) |*c, i| c.* = .{@intCast(i)};
break :blk t;
};
const Step = struct { gap: u64, key: Key, section: u8 };
/// The corpus's parts, each a case of the gates.
const sections = [_][]const u8{ "typing", "a burst", "backspace", "left, right", "tab", "password", "vim", "ignores input", "cat", "typed ahead" };
const Corpus = struct {
steps: std.ArrayListUnmanaged(Step) = .empty,
random: std.Random,
extra: u64 = 0,
section: u8 = 0,
fn add(c: *Corpus, gap: u64, key: Key) !void {
try c.steps.append(gpa, .{ .gap = gap + c.extra, .key = key, .section = c.section });
c.extra = 0;
}
fn typing(c: *Corpus, text: []const u8, fast: bool) !void {
for (text) |ch| try c.add(if (fast) c.random.intRangeAtMost(u64, 12_000, 60_000) else c.random.intRangeAtMost(u64, 60_000, 180_000), .{ .cp = ch, .text = &ascii[ch] });
}
fn press(c: *Corpus, key: Key) !void {
try c.add(c.random.intRangeAtMost(u64, 80_000, 250_000), key);
}
fn pause(c: *Corpus) void {
c.extra += c.random.intRangeAtMost(u64, 500_000, 1_200_000);
}
fn build(c: *Corpus) !void {
const enter: Key = .{ .cp = Key.enter };
const bs: Key = .{ .cp = Key.backspace };
c.pause();
// At a prompt, at a typist's pace, then in a burst.
c.section = 0;
try c.typing("echo hello world", false);
try c.press(enter);
c.pause();
c.section = 1;
try c.typing("echo the quick brown fox jumps over", true);
try c.press(enter);
c.pause();
// Backspace.
c.section = 2;
try c.typing("ecoh", false);
try c.press(bs);
try c.press(bs);
try c.typing("ho fixed tpyo", false);
for (0..3) |_| try c.press(bs);
try c.typing("ypo", false);
try c.press(enter);
c.pause();
// Left and right over what was typed.
c.section = 3;
try c.typing("echo abc", false);
for ([_]u21{ Key.left, Key.left, Key.right, Key.right }) |k| try c.press(.{ .cp = k });
try c.typing("def", false);
try c.press(enter);
c.pause();
// Tab completion, typed straight on.
c.section = 4;
try c.typing("ec", false);
try c.press(.{ .cp = Key.tab });
try c.typing("tab completed", false);
try c.press(enter);
c.pause();
// A password prompt: nothing typed there may show.
c.section = 5;
try c.typing("sudo ls", false);
try c.press(enter);
c.pause();
try c.typing("hunter2", false);
try c.press(enter);
c.pause();
// vim: the alternate screen, never predicted.
c.section = 6;
try c.typing("vim", false);
try c.press(enter);
c.pause();
try c.typing("ihello from vim", false);
try c.press(.{ .cp = Key.escape, .shift = true });
try c.typing(":q", false);
try c.press(enter);
c.pause();
// A program that ignores what is typed.
c.section = 7;
try c.typing("sink", false);
try c.press(enter);
c.pause();
try c.typing("this goes nowhere", false);
try c.press(.{ .cp = 'c', .ctrl = true });
c.pause();
// cat: the kernel's plain echo.
c.section = 8;
try c.typing("cat", false);
try c.press(enter);
c.pause();
try c.typing("plain echo", false);
try c.press(enter);
try c.typing("a second line", false);
try c.press(enter);
try c.press(.{ .cp = 'd', .ctrl = true });
c.pause();
// Typed on before the next prompt.
c.section = 9;
try c.typing("echo one", false);
try c.press(enter);
try c.typing("echo two", false);
try c.press(enter);
c.pause();
}
};
const prompt_bytes = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
/// The shell on the authority's pty, a key a write (as forwardKey writes).
const FakeShell = struct {
mode: Mode = .prompt,
line: [256]u8 = undefined,
len: usize = 0,
cur: usize = 0,
vim_cmd: [8]u8 = undefined,
vim_n: usize = 0,
out: std.ArrayListUnmanaged(u8) = .empty,
const Mode = enum { prompt, password, vim, vim_insert, sink, cat };
fn put(sh: *FakeShell, bytes: []const u8) void {
sh.out.appendSlice(gpa, bytes) catch {};
}
fn print(sh: *FakeShell, comptime fmt: []const u8, args: anytype) void {
sh.out.print(gpa, fmt, args) catch {};
}
fn done(sh: *FakeShell, status: u8) void {
sh.print("\x1b]133;D;{d};aid=pardes\x07" ++ prompt_bytes, .{status});
sh.mode = .prompt;
sh.len = 0;
sh.cur = 0;
}
fn insert(sh: *FakeShell, c: u8) void {
if (sh.len + 1 >= sh.line.len) return;
sh.put(&.{c});
if (sh.cur < sh.len) {
sh.put(sh.line[sh.cur..sh.len]);
sh.print("\x1b[{d}D", .{sh.len - sh.cur});
}
std.mem.copyBackwards(u8, sh.line[sh.cur + 1 .. sh.len + 1], sh.line[sh.cur..sh.len]);
sh.line[sh.cur] = c;
sh.len += 1;
sh.cur += 1;
}
fn key(sh: *FakeShell, b: []const u8) void {
const printable = b.len == 1 and b[0] >= 0x20 and b[0] < 0x7f;
const eql = std.mem.eql;
switch (sh.mode) {
.prompt => if (printable) sh.insert(b[0]) else if (eql(u8, b, "\x7f")) {
if (sh.cur == 0) return;
if (sh.cur == sh.len) sh.put("\x08\x1b[K") else {
sh.put("\x08");
sh.put(sh.line[sh.cur..sh.len]);
sh.print(" \x1b[{d}D", .{sh.len - sh.cur + 1});
}
std.mem.copyForwards(u8, sh.line[sh.cur - 1 .. sh.len - 1], sh.line[sh.cur..sh.len]);
sh.len -= 1;
sh.cur -= 1;
} else if (eql(u8, b, "\x1b[D")) {
if (sh.cur == 0) return;
sh.put(b);
sh.cur -= 1;
} else if (eql(u8, b, "\x1b[C")) {
if (sh.cur == sh.len) return;
sh.put(b);
sh.cur += 1;
} else if (eql(u8, b, "\t")) {
if (sh.cur != sh.len or std.mem.indexOfScalar(u8, sh.line[0..sh.len], ' ') != null) return;
for ([_][]const u8{ "echo", "sudo", "sink", "cat", "vim" }) |cmd| {
if (sh.len == 0 or sh.len >= cmd.len or !std.mem.startsWith(u8, cmd, sh.line[0..sh.len])) continue;
for (cmd[sh.len..]) |ch| sh.insert(ch);
sh.insert(' ');
return;
}
} else if (eql(u8, b, "\r")) {
var cmd_buf: [256]u8 = undefined;
const cmd = cmd_buf[0..sh.len];
@memcpy(cmd, sh.line[0..sh.len]);
sh.len = 0;
sh.cur = 0;
sh.put("\r\n\x1b]133;C;aid=pardes\x07");
if (cmd.len == 0) return sh.done(0);
if (std.mem.startsWith(u8, cmd, "echo")) {
sh.print("{s}\r\n", .{std.mem.trimStart(u8, cmd[4..], " ")});
sh.done(0);
} else if (std.mem.startsWith(u8, cmd, "sudo")) {
sh.put("[sudo] password for you: ");
sh.mode = .password;
} else if (eql(u8, cmd, "vim")) {
sh.put("\x1b[?1049h\x1b[2J\x1b[H~\r\n~\r\n~\x1b[H");
sh.mode = .vim;
} else if (eql(u8, cmd, "sink")) {
sh.mode = .sink;
} else if (eql(u8, cmd, "cat")) {
sh.mode = .cat;
} else {
sh.print("fake: unknown command: {s}\r\n", .{cmd});
sh.done(127);
}
} else if (eql(u8, b, "\x03")) {
sh.put("^C\r\n");
sh.done(130);
},
.password => if (eql(u8, b, "\r")) {
sh.put("\r\nsudo: 1 incorrect password attempt\r\n");
sh.done(1);
} else if (eql(u8, b, "\x03")) {
sh.put("^C\r\n");
sh.done(130);
},
.vim => if (sh.vim_n > 0) {
if (eql(u8, b, "\r")) {
const quit = eql(u8, sh.vim_cmd[0..sh.vim_n], ":q");
sh.vim_n = 0;
if (quit) {
sh.put("\x1b[?1049l");
sh.done(0);
}
} else if (printable and sh.vim_n < sh.vim_cmd.len) {
sh.vim_cmd[sh.vim_n] = b[0];
sh.vim_n += 1;
}
} else if (eql(u8, b, "i")) {
sh.mode = .vim_insert;
} else if (eql(u8, b, ":")) {
sh.vim_cmd[0] = ':';
sh.vim_n = 1;
},
.vim_insert => if (eql(u8, b, "\x1b")) {
sh.mode = .vim;
} else if (printable) sh.put(b),
.sink => if (eql(u8, b, "\x03")) {
sh.put("^C\r\n");
sh.done(130);
},
.cat => if (printable) {
sh.put(b);
if (sh.len < sh.line.len) {
sh.line[sh.len] = b[0];
sh.len += 1;
}
} else if (eql(u8, b, "\x7f")) {
if (sh.len == 0) return;
sh.put("\x08 \x08");
sh.len -= 1;
} else if (eql(u8, b, "\r")) {
sh.print("\r\n{s}\r\n", .{sh.line[0..sh.len]});
sh.len = 0;
} else if (eql(u8, b, "\x04") and sh.len == 0) {
sh.done(0);
} else if (eql(u8, b, "\x03")) {
sh.put("^C\r\n");
sh.done(130);
},
}
}
};
/// The authority's host: each pty write tagged with the client input that
/// made it.
const EchoHost = struct {
writes: std.ArrayListUnmanaged(struct { seq: u32, bytes: []u8 }) = .empty,
current: u32 = 0,
fn watched(_: ?*anyopaque) bool {
return false;
}
fn ptyWrite(ctx: ?*anyopaque, _: u8, bytes: []const u8) void {
const h: *EchoHost = @ptrCast(@alignCast(ctx.?));
h.writes.append(gpa, .{ .seq = h.current, .bytes = gpa.dupe(u8, bytes) catch return }) catch {};
}
fn ignore(_: ?*anyopaque, _: []const u8) void {}
const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite, .set_clipboard = ignore };
fn host(h: *EchoHost) pardes.Host {
return .{ .ctx = h, .vtable = &vtable };
}
};
const Typed = struct {
seq: u32,
section: u8,
at: u64,
printable: bool,
/// What was predicted: the cell (its row in the active area) and the
/// cursor after it.
pred: ?struct { x: u16, y: u16, cp: u21 } = null,
pcur: ?struct { x: u16, y: u16 } = null,
/// The shell's mode as it took the key; whether it printed anything for
/// it; the authority's version of the screen before that.
mode: ?FakeShell.Mode = null,
echoed: bool = false,
version_before: u32 = 0,
/// The authority's screen right after its echo: its cursor and the
/// cursor's row; whether that is what was predicted.
after: ?struct { x: u16, y: u16, row: [128]u21 } = null,
truth: ?bool = null,
/// Its prediction drawn: first, and in how many frames.
first_visible: ?u64 = null,
visible_frames: u32 = 0,
/// The screen state showing its echo, first.
seen: ?u64 = null,
};
const EchoTotals = struct {
keys: u64 = 0,
echo_keys: u64 = 0,
latency: std.ArrayListUnmanaged(u64) = .empty,
predicted: u64 = 0,
unpredicted: u64 = 0,
confirmed: u64 = 0,
mispredicted: u64 = 0,
cursor_missed: u64 = 0,
right: u64 = 0,
wrong: u64 = 0,
wrong_shown: u64 = 0,
wrong_frames: u64 = 0,
wrong_max: u64 = 0,
secret_frames: u64 = 0,
alt_predicted: u64 = 0,
divergences: u64 = 0,
unequal: u64 = 0,
screens_wrong: u64 = 0,
/// The replica's frame drawn while it shows a prediction (its core's
/// render, the tty's and the GUI's), and the overlay's part of it (ns);
/// cells drawn otherwise than predicted.
render_ns: std.ArrayListUnmanaged(u64) = .empty,
paint_ns: std.ArrayListUnmanaged(u64) = .empty,
drawn_frames: u64 = 0,
paint_wrong: u64 = 0,
sec: [sections.len]Section = @splat(.{}),
const Section = struct { keys: u64 = 0, predicted: u64 = 0, wrong_frames: u64 = 0, latency: std.ArrayListUnmanaged(u64) = .empty };
fn deinit(et: *EchoTotals) void {
for (&et.sec) |*x| x.latency.deinit(gpa);
et.latency.deinit(gpa);
et.render_ns.deinit(gpa);
et.paint_ns.deinit(gpa);
}
};
fn cellCp(state: *pardes.Term.State, x: u16, y: u16) u21 {
const ci = pardes.Term.emulatorOf(state).vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return 0x10ffff;
const cp = ci.cell.codepoint();
return if (cp == 0) ' ' else cp;
}
/// A key's prediction against the authority's screen right after its echo,
/// once both are known (a key typed behind one not predicted is predicted
/// after the authority has it).
fn judgeTruth(k: *Typed) void {
if (k.truth != null) return;
const pc = k.pcur orelse return;
const after = k.after orelse return;
var ok = after.x == pc.x and after.y == pc.y;
if (k.pred) |cell| ok = ok and cell.y == after.y and cell.x < after.row.len and after.row[cell.x] == cell.cp;
k.truth = ok;
if (trace and !ok) std.debug.print("key {d} in {t} predicted cursor {d},{d} cell {any}; the authority's cursor {d},{d}\n", .{ k.seq, k.mode.?, pc.x, pc.y, k.pred, after.x, after.y });
}
fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void {
var prng = std.Random.DefaultPrng.init(seed *% 0x9e3779b97f4a7c15 +% rtt_ms);
const random = prng.random();
var host: EchoHost = .{};
defer {
for (host.writes.items) |w| gpa.free(w.bytes);
host.writes.deinit(gpa);
}
var sh: FakeShell = .{};
defer sh.out.deinit(gpa);
const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host(), true);
defer a.deinit();
var screens: replica.Screens = .init(gpa);
defer screens.deinit(a.core);
const peer = try screens.addPeer();
const peers = [_]u16{peer};
const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0), true);
defer rp.deinit();
rp.echo.on = on;
const shell: u8 = for (a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
} else return error.NoShell;
var corpus: Corpus = .{ .random = random };
defer corpus.steps.deinit(gpa);
try corpus.build();
var typed: std.ArrayListUnmanaged(Typed) = .empty;
defer typed.deinit(gpa);
var t: Totals = .{};
defer {
t.spec_ns.deinit(gpa);
t.copy_ns.deinit(gpa);
t.rollback_ns.deinit(gpa);
t.apply_ns.deinit(gpa);
t.frame_ns.deinit(gpa);
}
var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty;
defer versions.deinit(gpa);
var queue: std.PriorityQueue(Msg, void, Msg.order) = .empty;
defer {
while (queue.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes);
queue.deinit(gpa);
}
var n: u64 = 0;
const one_way = rtt_ms * 1000 / 2;
const jitter = one_way / 10;
var up: [1]Link = @splat(.{});
var down: [1]Link = @splat(.{});
var owed: std.ArrayListUnmanaged([]u8) = .empty;
defer owed.deinit(gpa);
// The shell's first prompt.
sh.put(prompt_bytes);
a.output(.{ .output = .{ .pane = shell, .bytes = sh.out.items } });
sh.out.clearRetainingCapacity();
var next_step: usize = 0;
try push(&queue, &n, .{ .at = corpus.steps.items[0].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} });
try push(&queue, &n, .{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} });
try push(&queue, &n, .{ .at = random.uintLessThan(u64, frame_us), .n = 0, .kind = .client_frame, .who = 1, .bytes = &.{} });
// Two clocks tick while anything else moves, and a second after.
var periodic: usize = 2;
var left: [2]u32 = .{ 60, 60 };
var frame_arena: std.heap.ArenaAllocator = .init(gpa);
defer frame_arena.deinit();
var made: std.ArrayListUnmanaged(Echo.Predicted) = .empty;
defer made.deinit(gpa);
rp.echo.log = &made;
while (queue.pop()) |m| {
defer if (m.bytes.len > 0) gpa.free(m.bytes);
rp.echo.now = m.at * 1000;
// What it predicted in the last event's calls (a key typed, or the
// keys behind one it did not, at a unit, a delta or a frame).
defer {
const top = rp.echo.tops[shell];
for (made.items) |pr| {
const k = &typed.items[pr.seq - 1];
if (trace) {
const sc = pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt.screens.active.cursor;
std.debug.print("{d} ms ({t}): key {d} predicted {any} cursor {d}; acked {d} wait {d} nd {d}; the screen's cursor {d},{d}\n", .{ m.at / 1000, m.kind, pr.seq, pr.cell, pr.cursor.x, rp.echo.acked, rp.echo.wait, rp.echo.nd, sc.x, sc.y });
}
if (pr.cell) |cell| k.pred = .{ .x = cell.x, .y = @intCast(cell.row - top), .cp = cell.cp };
k.pcur = .{ .x = pr.cursor.x, .y = @intCast(pr.cursor.row - top) };
judgeTruth(k);
}
made.clearRetainingCapacity();
}
switch (m.kind) {
.input => {
const step = corpus.steps.items[next_step];
next_step += 1;
const msg = try gpa.dupe(u8, try rp.input(.{ .key = step.key }));
const seq = rp.next_seq - 1;
try typed.append(gpa, .{ .seq = seq, .section = step.section, .at = m.at, .printable = step.key.text.len == 1 });
if (trace) std.debug.print("{d} ms: key {d} typed: '{s}' cp {x}\n", .{ m.at / 1000, seq, step.key.text, step.key.cp });
try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .to_authority, .who = 1, .bytes = msg });
if (next_step < corpus.steps.items.len) try push(&queue, &n, .{ .at = m.at + corpus.steps.items[next_step].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} });
},
.to_authority => {
if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers);
try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t);
host.current = (replica.parseInput(m.bytes) orelse return error.BadInput).seq;
const unit = try a.take(m.bytes);
host.current = 0;
try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers);
for (host.writes.items) |w| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = shell, .bytes = w.bytes, .seq = w.seq });
host.writes.clearRetainingCapacity();
},
.echo => {
const ty: ?*Typed = if (m.seq > 0) &typed.items[m.seq - 1] else null;
const state = a.core.panes[shell].?.terminal.?;
if (ty) |k| {
k.mode = sh.mode;
k.version_before = if (screens.tracks[shell]) |*tr| trackOf(tr.track).version else 0;
}
sh.key(m.bytes);
if (sh.out.items.len > 0) {
a.output(.{ .output = .{ .pane = shell, .bytes = sh.out.items } });
sh.out.clearRetainingCapacity();
if (ty) |k| k.echoed = true;
}
if (ty) |k| {
const cur = pardes.Term.emulatorOf(state).vt.screens.active.cursor;
k.after = .{ .x = @intCast(cur.x), .y = @intCast(cur.y), .row = undefined };
for (&k.after.?.row, 0..) |*cp, x| cp.* = cellCp(state, @intCast(x), @intCast(cur.y));
judgeTruth(k);
}
},
.frame => {
if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers);
try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t);
const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic;
left[0] = if (busy) 60 else left[0] -| 1;
if (left[0] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }) else periodic -= 1;
},
.client_frame => {
_ = rp.echoFrame();
const core = rp.core();
const drawn = rp.echo.visible(core) and core.panes[shell].?.body.mode == .tty;
if (drawn and rp.echo.n > 0) {
// Drawn as the client draws it: each cell where it was
// predicted.
_ = frame_arena.reset(.retain_capacity);
core.needs_frame = true;
const t0 = pardes.FrameStats.nowNs();
const surf = try core.render(frame_arena.allocator());
try et.render_ns.append(gpa, pardes.FrameStats.nowNs() - t0);
const body = surf.region(.body, shell).?.rect;
const top = rp.echo.tops[shell];
for (rp.echo.cells[0..rp.echo.n]) |cell| {
if (cell.row < top or surf.at(body.x + cell.x, body.y + @as(u16, @intCast(cell.row - top))).text[0] != cell.cp) et.paint_wrong += 1;
}
const t1 = pardes.FrameStats.nowNs();
rp.echo.paint(core, surf, core.panes[shell].?, shell, body.x, body.w, body.y, body.h, true);
try et.paint_ns.append(gpa, pardes.FrameStats.nowNs() - t1);
et.drawn_frames += 1;
}
if (drawn) for (rp.echo.cells[0..rp.echo.n]) |cell| {
const k = &typed.items[cell.seq - 1];
k.visible_frames += 1;
if (k.first_visible == null) {
k.first_visible = m.at;
if (trace) {
const st = core.panes[shell].?.terminal.?;
std.debug.print("{d} ms: key {d} ('{u}') drawn: trusted {} doubt {} phase {t} sem {t}\n", .{ m.at / 1000, cell.seq, cell.cp, rp.echo.trusted, rp.echo.doubt, pardes.Term.emulatorOf(st).stream.handler.phase, pardes.Term.emulatorOf(st).vt.screens.active.cursor.semantic_content });
}
}
};
const applied = if (rp.screens[shell]) |sc| replicaOf(sc.rep).seq else 0;
for (typed.items) |*k| if (k.echoed and k.seen == null and applied > k.version_before) {
k.seen = m.at;
};
const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic;
left[1] = if (busy) 60 else left[1] -| 1;
if (left[1] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .client_frame, .who = 1, .bytes = &.{} }) else periodic -= 1;
},
.to_replica => {
rp.confirm(m.bytes);
rp.settle();
},
.screen_down => {
if (rp.screen(m.bytes)) |reply| {
const pane = m.bytes[0];
if (reply[5] == 1) {
const sc = rp.screens[pane].?;
if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| {
if (want != screenHash(&pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt)) t.screens_wrong += 1;
} else t.screens_wrong += 1;
}
try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, reply) });
}
if (rp.screenRequest()) |req| try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, req) });
},
.screen_up => {
if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer });
},
.output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw => {},
}
}
const s = rp.echo.stats;
et.predicted += s.predicted;
et.unpredicted += s.unpredicted;
et.confirmed += s.confirmed;
et.mispredicted += s.mispredicted;
et.cursor_missed += s.cursor_missed;
et.screens_wrong += t.screens_wrong;
for (typed.items) |k| {
et.keys += 1;
const sec = &et.sec[k.section];
sec.keys += 1;
if (k.pcur != null) sec.predicted += 1;
if (k.visible_frames > 0 and k.truth != true) sec.wrong_frames += k.visible_frames;
if (k.truth) |ok| {
if (ok) et.right += 1 else et.wrong += 1;
}
const md = k.mode orelse .prompt;
if (md == .password or md == .sink) et.secret_frames += k.visible_frames;
if ((md == .vim or md == .vim_insert) and k.pcur != null) et.alt_predicted += 1;
if (k.visible_frames > 0 and k.truth != true) {
if (trace) std.debug.print("seed {d}: key {d} at {d} ms in {t} drawn {d} frames, truth {?}, predicted {any} cursor {any}, the authority after it {any}\n", .{ seed, k.seq, k.at / 1000, md, k.visible_frames, k.truth, k.pred, k.pcur, if (k.after) |af| .{ af.x, af.y } else null });
et.wrong_shown += 1;
et.wrong_frames += k.visible_frames;
et.wrong_max = @max(et.wrong_max, k.visible_frames);
}
if (k.printable and k.echoed and (md == .prompt or md == .cat)) {
const seen = k.seen orelse std.math.maxInt(u64);
const drawn = if (k.first_visible != null and k.truth == true) @min(k.first_visible.?, seen) else seen;
if (drawn == std.math.maxInt(u64)) {
std.debug.print("seed {d} rtt {d} ms: a key's echo was never drawn\n", .{ seed, rtt_ms });
et.unequal += 1;
continue;
}
et.echo_keys += 1;
try et.latency.append(gpa, drawn - k.at);
try sec.latency.append(gpa, drawn - k.at);
if (trace and drawn - k.at > 2 * frame_us) std.debug.print("key {d} at {d} ms in {t}: drawn after {d} ms, {s}\n", .{ k.seq, k.at / 1000, md, (drawn - k.at) / 1000, if (k.pcur == null) "not predicted" else if (k.first_visible == null) "predicted, not drawn" else if (k.truth != true) "predicted wrong" else "predicted, drawn late" });
}
}
if (rp.diverged) |why| {
et.divergences += 1;
std.debug.print("seed {d} rtt {d} ms: the replica diverged: {s}\n", .{ seed, rtt_ms, why });
} else if (!rp.quiet() or rp.digest() != replica.digestOf(a)) {
et.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: the replica at quiescence: {s}\n", .{ seed, rtt_ms, if (rp.quiet()) "another digest" else "inputs still pending" });
}
if (screenHash(&pardes.Term.emulatorOf(a.core.panes[shell].?.terminal.?).vt) != screenHash(&pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt)) {
et.unequal += 1;
std.debug.print("seed {d} rtt {d} ms: the shell at quiescence is not the authority's\n", .{ seed, rtt_ms });
}
}
fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool {
var failed = false;
var draw_lines: std.ArrayList(u8) = .empty;
defer draw_lines.deinit(gpa);
std.debug.print("predicted echo: one client typing the corpus into a shell, {d} seeds a cell; from a key to its character on the client's screen (ms, frames at 60 Hz)\n", .{seeds});
std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal screens-wrong\n", .{});
var by_section: std.ArrayList(u8) = .empty;
defer by_section.deinit(gpa);
var off: [sections.len][2]u64 = undefined;
for (rtts) |rtt| for ([_]bool{ false, true }) |on| {
var et: EchoTotals = .{};
defer et.deinit();
for (first..first + seeds) |seed| try runEcho(seed, rtt, on, &et);
const ms = struct {
fn f(us: u64) f64 {
return @as(f64, @floatFromInt(us)) / 1000;
}
}.f;
std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7} {d:>13}\n", .{
rtt, if (on) "on" else "off", et.keys, et.echo_keys,
ms(pct(et.latency.items, 50)), ms(pct(et.latency.items, 90)), ms(pct(et.latency.items, 100)), et.predicted,
et.unpredicted, et.right, et.wrong, et.confirmed,
et.mispredicted, et.cursor_missed, et.wrong_shown, et.wrong_frames,
et.wrong_max, et.secret_frames, et.alt_predicted, et.divergences,
et.unequal, et.screens_wrong,
});
for (&et.sec, &off, sections) |*x, *o, name| {
const p50 = pct(x.latency.items, 50) / 1000;
const p90 = pct(x.latency.items, 90) / 1000;
if (!on) {
o.* = .{ p50, p90 };
continue;
}
try by_section.print(gpa, "{d:>4} {s:<14} {d:>5} {d:>9} {d:>7} {d:>4} -> {d:<4} {d:>4} -> {d:<4} {d:>12}\n", .{ rtt, name, x.keys, x.predicted, x.latency.items.len, o[0], p50, o[1], p90, x.wrong_frames });
}
if (on) try draw_lines.print(gpa, "{d:>4} {d:>12} {d:>6}/{d:<6} {d:>5}/{d:<5} {d:>10}\n", .{ rtt, et.drawn_frames, pct(et.render_ns.items, 50) / 1000, pct(et.render_ns.items, 99) / 1000, pct(et.paint_ns.items, 50), pct(et.paint_ns.items, 99), et.paint_wrong });
if (et.divergences > 0 or et.unequal > 0 or et.screens_wrong > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true;
};
std.debug.print("by part of the corpus (all seeds): keys typed, predicted, echoed (the latency sample); key to its character on the screen, ms, without -> with; frames a wrong prediction was drawn\n rtt part keys predicted echoed p50 off/on p90 off/on drawn-wrong\n{s}", .{by_section.items});
std.debug.print("the client's frames drawn with a prediction shown: its render (us) and the overlay's part (ns); cells drawn otherwise than predicted\n rtt frames-drawn render p50/p99 paint p50/p99 drawn-wrong\n{s}", .{draw_lines.items});
return !failed;
}
fn pct(samples: []u64, p: usize) u64 {
if (samples.len == 0) return 0;
std.mem.sort(u64, samples, {}, std.sort.asc(u64));
return samples[@min(samples.len - 1, samples.len * p / 100)];
}
/// `--screen-state <dir>`: every recorded pty stream in `dir` (a
/// `-<cols>x<rows>` in its name sizes it, 80x24 otherwise) through
/// screen_state's soak at three seeds, then the encode's cost and the bytes
/// floods put on the wire (numbers from a ReleaseFast build).
fn screenState(io: std.Io, dir_path: []const u8, w: *std.Io.Writer) !void {
var dir = try std.Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true });
defer dir.close(io);
var it = dir.iterate();
var files: usize = 0;
var failed: usize = 0;
while (try it.next(io)) |entry| {
if (entry.kind != .file) continue;
const bytes = try dir.readFileAlloc(io, entry.name, gpa, .unlimited);
defer gpa.free(bytes);
var cols: u16 = 80;
var rows: u16 = 24;
if (std.mem.lastIndexOfScalar(u8, entry.name, '-')) |dash| {
const size = std.mem.sliceTo(entry.name[dash + 1 ..], '.');
if (std.mem.indexOfScalar(u8, size, 'x')) |x| {
cols = std.fmt.parseInt(u16, size[0..x], 10) catch cols;
rows = std.fmt.parseInt(u16, size[x + 1 ..], 10) catch rows;
}
}
files += 1;
for (0..3) |seed| {
const st = screen_state.soak(gpa, io, bytes, cols, rows, 128 * 1024, seed, seed != 0) catch |err| {
try w.print("screen-state {s} seed {d}: {s}\n", .{ entry.name, seed, @errorName(err) });
failed += 1;
continue;
};
if (seed == 0) try w.print("screen-state {s} {d}x{d}: {d} bytes, {d} deltas ({d} lost, {d} refused, {d} in flight at most), {d} wire bytes, {d} history rows checked, {d} fetched\n", .{ entry.name, cols, rows, bytes.len, st.deltas, st.lost, st.refused, st.most_in_flight, st.bytes, st.history_checked, st.fetched });
}
}
try w.print("screen-state corpus: {d} streams x 3 seeds, {d} failed\n", .{ files, failed });
try w.flush();
try encodeBench(io, w);
}
fn encodeBench(io: std.Io, w: *std.Io.Writer) !void {
const t = try gpa.create(screen_state.Terminal);
defer gpa.destroy(t);
t.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 });
defer t.deinit(gpa);
var stream = t.vtStream();
defer stream.deinit();
var enc: screen_state.Encoder = .init(gpa);
defer enc.deinit();
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
var line: [1024]u8 = undefined;
// A full 200x60 screen, every row new to the peer: each a blob.
var full: [200]u64 = undefined;
var same: [200]u64 = undefined;
var full_bytes: usize = 0;
var same_bytes: usize = 0;
var changes: u32 = 0;
for (&full, &same, 0..) |*f, *u, rep| {
for (0..60) |y| {
var lw: std.Io.Writer = .fixed(&line);
try lw.print("\x1b[{d};1H\x1b[0;3{d};4{d}m{d} {d} ", .{ y + 1, rep % 8, y % 8, rep, y });
while (lw.end < 190) try lw.writeAll("\x1b[1mbold\x1b[22m text ");
stream.nextSlice(lw.buffered());
}
changes += 1;
var tr: screen_state.Track = .init(gpa);
defer tr.deinit(gpa, t);
var peer: screen_state.Peer = .{};
defer peer.deinit(gpa);
out.clearRetainingCapacity();
var t0 = std.Io.Clock.awake.now(io).nanoseconds;
_ = try screen_state.encode(&enc, &tr, &peer, t, changes, "", &out.writer);
f.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0);
full_bytes = out.written().len;
// The same screen again as a new version: every row held.
out.clearRetainingCapacity();
t0 = std.Io.Clock.awake.now(io).nanoseconds;
_ = try screen_state.encode(&enc, &tr, &peer, t, changes + 1, "", &out.writer);
u.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0);
same_bytes = out.written().len;
}
std.mem.sort(u64, &full, {}, std.sort.asc(u64));
std.mem.sort(u64, &same, {}, std.sort.asc(u64));
try w.print("screen-state encode 200x60, every row new: p50 {d} us p99 {d} us, {d} bytes\n", .{ full[100] / 1000, full[198] / 1000, full_bytes });
try w.print("screen-state encode 200x60, nothing new: p50 {d} us p99 {d} us, {d} bytes\n", .{ same[100] / 1000, same[198] / 1000, same_bytes });
try w.flush();
// Floods: a second of output as fast as ghostty takes it, a frame every
// 16 ms: one version, a delta for each peer (the same bytes for peers
// at the same base), each replica applying its own at once. Under the C
// allocator, as a replica's.
try floods(io, w);
}
fn floods(io: std.Io, w: *std.Io.Writer) !void {
var enc: screen_state.Encoder = .init(gpa);
defer enc.deinit();
var out: std.Io.Writer.Allocating = .init(gpa);
defer out.deinit();
const yes = try screen_state.yesStream(gpa, 1 << 16);
defer gpa.free(yes);
const shell = try screen_state.shellStream(gpa);
defer gpa.free(shell);
for ([_]struct { name: []const u8, bytes: []const u8 }{ .{ .name = "yes", .bytes = yes }, .{ .name = "varied text", .bytes = shell } }) |flood| for ([_]usize{ 1, 3 }) |npeers| {
const a = try gpa.create(screen_state.Terminal);
defer gpa.destroy(a);
a.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 });
defer a.deinit(gpa);
var as = a.vtStream();
defer as.deinit();
var tr: screen_state.Track = .init(gpa);
defer tr.deinit(gpa, a);
var peers: [3]screen_state.Peer = @splat(.{});
var reps: [3]screen_state.Replica = @splat(.{});
var bs: [3]screen_state.Terminal = undefined;
for (bs[0..npeers]) |*b| b.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 32 << 20 });
defer for (bs[0..npeers], reps[0..npeers], peers[0..npeers]) |*b, *r, *peer| {
b.deinit(gpa);
r.deinit(gpa);
peer.deinit(gpa);
};
var applies: std.ArrayList(u64) = .empty;
defer applies.deinit(gpa);
var frames: std.ArrayList(u64) = .empty;
defer frames.deinit(gpa);
const start = std.Io.Clock.awake.now(io).nanoseconds;
var next = start;
var fed: u64 = 0;
var deltas: u64 = 0;
var wire: u64 = 0;
var version: u32 = 0;
while (true) {
const now = std.Io.Clock.awake.now(io).nanoseconds;
if (now - start >= std.time.ns_per_s) break;
as.nextSlice(flood.bytes);
version += 1;
fed += flood.bytes.len;
if (now < next) continue;
next += 16 * std.time.ns_per_ms;
var frame_ns: u64 = 0;
for (peers[0..npeers], reps[0..npeers], bs[0..npeers]) |*peer, *rep, *b| {
out.clearRetainingCapacity();
const e0 = std.Io.Clock.awake.now(io).nanoseconds;
if (!try screen_state.encode(&enc, &tr, peer, a, version, "", &out.writer)) continue;
frame_ns += @intCast(std.Io.Clock.awake.now(io).nanoseconds - e0);
const a0 = std.Io.Clock.awake.now(io).nanoseconds;
peer.ack((try rep.apply(gpa, io, b, out.written())).seq);
try applies.append(gpa, @intCast(std.Io.Clock.awake.now(io).nanoseconds - a0));
deltas += 1;
wire += out.written().len;
}
try frames.append(gpa, frame_ns);
}
std.mem.sort(u64, applies.items, {}, std.sort.asc(u64));
std.mem.sort(u64, frames.items, {}, std.sort.asc(u64));
const p = struct {
fn at(s: []const u64, q: usize) u64 {
return if (s.len == 0) 0 else s[@min(s.len - 1, s.len * q / 100)] / 1000;
}
}.at;
try w.print("screen-state flood of {s}, {d} peer(s): {d} MB/s of output, {d} deltas/s a peer, {d} wire bytes/s a peer ({d} a delta); encode a frame, all peers: p50 {d} us p99 {d} us; apply a delta p50 {d} us p99 {d} us\n", .{
flood.name, npeers, fed / 1_000_000, deltas / npeers, wire / npeers,
wire / @max(1, deltas), p(frames.items, 50), p(frames.items, 99), p(applies.items, 50),
p(applies.items, 99),
});
};
try w.flush();
}
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
var seeds: u64 = 4;
var first: u64 = 0;
var steps: usize = 120;
var clients: u16 = 5;
var rtts: []const u64 = &.{ 30, 80, 207 };
var echo_mode = false;
var flood_mb: u64 = 8;
var screen_dir: ?[]const u8 = null;
var rtt_buf: [8]u64 = undefined;
var addons: std.ArrayListUnmanaged([]const u8) = .empty;
defer addons.deinit(gpa);
var i: usize = 1;
while (i < args.len) : (i += 1) {
const name = args[i];
if (std.mem.eql(u8, name, "--echo")) {
echo_mode = true;
continue;
}
if (i + 1 >= args.len) return error.MissingValue;
i += 1;
const value = args[i];
if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) {
var whole: [libc.PATH_MAX]u8 = undefined;
pdf_path = try init.arena.allocator().dupe(u8, std.mem.span(libc.realpath(try init.arena.allocator().dupeSentinel(u8, value, 0), &whole) orelse return error.NoPdf));
} else if (std.mem.eql(u8, name, "--rtt")) {
var it = std.mem.tokenizeScalar(u8, value, ',');
var k: usize = 0;
while (it.next()) |v| : (k += 1) rtt_buf[k] = try std.fmt.parseInt(u64, v, 10);
rtts = rtt_buf[0..k];
} else return error.UnknownOption;
}
if (screen_dir) |d| {
var buf: [4096]u8 = undefined;
var out = std.Io.File.stderr().writer(init.io, &buf);
return screenState(init.io, d, &out.interface);
}
trace = libc.getenv("PARDES_REPLICA_TRACE") != null;
if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff;
var dir_buf: [256]u8 = undefined;
const tmp = std.mem.span(libc.getenv("TMPDIR") orelse "/tmp");
const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) });
try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir);
defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {};
// Its own data directory, the only one its addon scan reads (never the
// user's): the libraries it was given (`--addon`), as a user's are
// installed, read by the session's core and its clients' alike.
var data_buf: [300]u8 = undefined;
const data = try std.fmt.bufPrintSentinel(&data_buf, "{s}/data", .{dir}, 0);
var lib_dir_buf: [300]u8 = undefined;
const lib_dir = try std.fmt.bufPrint(&lib_dir_buf, "{s}/pardes/addons", .{data});
try std.Io.Dir.cwd().createDirPath(init.io, lib_dir);
for (addons.items) |lib| {
var to: [600]u8 = undefined;
var from: [600]u8 = undefined;
var whole: [libc.PATH_MAX]u8 = undefined;
const at = libc.realpath(try std.fmt.bufPrintSentinel(&from, "{s}", .{lib}, 0), &whole) orelse return error.NoAddon;
if (libc.symlink(at, try std.fmt.bufPrintSentinel(&to, "{s}/{s}", .{ lib_dir, std.Io.Dir.path.basename(lib) }, 0)) != 0) return error.NoAddon;
}
if (setenv("XDG_DATA_HOME", data, 1) != 0) return error.NoDataDir;
if (echo_mode) {
if (!try echoMain(seeds, first, rtts)) std.process.exit(1);
return;
}
var failed = !try diffCase(dir);
if (!try plumbCase(dir)) failed = true;
std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us });
std.debug.print(" rtt inputs at-once stopped view units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{});
var term_lines: std.ArrayList(u8) = .empty;
defer term_lines.deinit(gpa);
var join_lines: std.ArrayList(u8) = .empty;
defer join_lines.deinit(gpa);
for (rtts) |rtt| {
var t: Totals = .{};
for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t);
const rollbacks = t.mispredicted + t.foreign;
std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>4} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{
rtt, t.inputs, t.speculated,
t.stopped, t.unspeculated, t.units,
t.fast, rollbacks, t.mispredicted,
t.foreign, @as(f64, @floatFromInt(rollbacks)) * 100 / @as(f64, @floatFromInt(@max(t.inputs, 1))), t.rebases,
pct(t.spec_ns.items, 50) / 1000, pct(t.spec_ns.items, 99) / 1000, pct(t.copy_ns.items, 50) / 1000,
pct(t.copy_ns.items, 99) / 1000, t.copy_bytes / @max(t.copies, 1) / 1024, pct(t.rollback_ns.items, 50) / 1000,
pct(t.rollback_ns.items, 99) / 1000, t.divergences, t.unequal,
});
const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6;
try term_lines.print(gpa, "{d:>4} {d:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>9} {d:>6} {d:>6}/{d:<6}\n", .{
rtt,
@as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)),
@as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
@as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)),
pct(t.frame_ns.items, 50) / 1000,
pct(t.frame_ns.items, 99) / 1000,
pct(t.apply_ns.items, 50) / 1000,
pct(t.apply_ns.items, 99) / 1000,
t.fetched,
t.filled_bytes / 1024,
t.resets,
t.screens_checked,
t.screens_wrong,
});
try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] });
if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0) failed = true;
}
std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{});
std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items});
std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{});
std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items});
if (failed) std.process.exit(1);
}
|