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
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
|
#!/usr/bin/env python3
"""The per-user daemon end to end (docs/next-daemon.md, phase 3), under a
private HOME and runtime directory:
- a terminal's session detached (the stub ends, exit 0), then attached
from another terminal N times, each a client (an attach is always one);
- the daemon killed: its sessions start the next and register again with
it, their shells too, and a client attaches (`relink`);
- a session killed outright: its shells live on, held by the daemon, and
another session adopts them as terminal panes;
- a replica's hello on the daemon's stream socket (phase 5): one of this
build handed to its session, which welcomes it, sends its dump and
answers its pings; another build's refused, and a session nobody has;
- replica clients (`pardes --attach=<socket>:<name>`, phase 5 part B) of a
detached session, one through the delay relay: each one's keys in the
session's text, every client's digest the session's once quiet, one
killed outright while the other types on;
- nothing left behind: no session, shell, daemon or socket.
python3 -B test/daemon.py <pardes> [cycles]
python3 -B test/daemon.py --gui <pardes-gui> [cycles] (hidden windows,
offscreen, and a pardes beside it for the terminal's client)
python3 -B test/daemon.py --ping <socket> <session> <pardes> [n]
a hello of <pardes>'s build and n pings on a replica socket (one
`ssh -L` forwards, say), timed
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
python3 -B test/daemon.py --launch <pardes>
`pardes new --detach` returns once its session runs
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --with-pair <mode> ...
any mode with PARDES_PAIR set in every process it starts
python3 -B test/daemon.py --attach-upgrading <pardes>
an attach started as its session upgrades, and two clients' views
across an Upgrade (in plain and --pair too)
python3 -B test/daemon.py --relink <pardes>
the daemon killed: its sessions register again with the next; and
one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, one under `yes` across
a slow link, and a file by its hash
python3 -B test/daemon.py --kitty-image <pardes>
a plain client watching a kitty image in its session's terminal
python3 -B test/daemon.py --games <pardes> <lib> [seconds]
the games in the clients that show them, from zig build
addon-test's <prefix>/lib (libsnake, liblife, libliar)
python3 -B test/daemon.py --window-clients <pardes> <pardes-gui>
window replica clients (hidden, offscreen) of a terminal's session,
at 0/30/80/207 ms, and a window's session serving replicas
python3 -B test/daemon.py --client-motion <pardes> <pardes-gui>
a run of pointer motions over a client window is a few inputs, not
one each (also run by --window-clients)
python3 -B test/daemon.py --client-resize-real <pardes> <pardes-gui>
a client window showing a PDF resized 30 times in a second by the
real compositor (driftwm), the caller's display: no SDL assertion,
the last size taken, an input a size at most
python3 -B test/daemon.py --client-idle <pardes> <pardes-gui>
a window's session (the test surface, and offscreen with no test
mode) and a terminal's, each with a PDF and a terminal client,
nobody typing: no more steps than the text alone (pdf.so in both
prefixes)
"""
import fcntl
import json
import os
import random
import re
import select
import shutil
import signal
import socket
import statistics
import struct
import subprocess
import sys
import tempfile
import termios
import threading
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from ninep import Client # noqa: E402
# `--with-pair` before a mode: that mode as a user who exported PARDES_PAIR.
WITH_PAIR = False
def base_env():
"""This process's environment without the caller's PARDES_* (a session
of the user's) or a pager; under `--with-pair`, PARDES_PAIR set in it, as
for a user who exported it: every mode run with the variable."""
env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
if WITH_PAIR:
env['PARDES_PAIR'] = '1'
return env
def listed_as(word, kind='tty'):
"""How `--ps` lists a session `detached` (started so, or Detached in its
own frontend) or that `has a frontend`: under the variable the first is
kept (from birth, or at the Detach) and the second a pair (P36)."""
if WITH_PAIR:
return f'({kind}, kept)' if word == 'detached' else f'({kind})'
return f'({kind}, {word})'
def wait_for(what, check, timeout=10):
deadline = time.monotonic() + timeout
while True:
got = check()
if got:
return got
if time.monotonic() > deadline:
raise TimeoutError(what)
time.sleep(.01)
class Term:
"""A terminal: a pty whose other end is read and kept, its frame
requests answered (CSI 5 n), as a terminal emulator does."""
def __init__(self, rows=24, cols=80):
self.master, self.slave = os.openpty()
fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0))
self.out = bytearray()
self.lock = threading.Lock()
self.closing = False
self.tail = b''
self.reader = threading.Thread(target=self.drain, daemon=True)
self.reader.start()
def drain(self):
# Never blocked in a read when `close` comes: a master closed under a
# read stays open until it returns, so the terminal would not hang
# up, and its fd's number, taken again, would be read here.
while not self.closing:
try:
if not select.select([self.master], [], [], 0.05)[0]:
continue
# Read and kept in one hold of the lock: `last` counts what
# waits on the master under it.
with self.lock:
got = os.read(self.master, 65536)
self.out += got
except OSError:
return
if not got:
return
# A request split across two reads is answered too.
seen, self.tail = self.tail + got, got[-3:]
if b'\x1b[5n' in seen:
try:
os.write(self.master, b'\x1b[0n')
except OSError:
return
def spawn(self, argv, env):
slave = self.slave
return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave,
start_new_session=True,
preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0))
def text(self):
with self.lock:
return bytes(self.out)
def last(self):
"""Its text once what was written to it is read, for a read after
its writer ended (or wrote its last before an event seen
elsewhere): the reader may not have the last bytes yet (it reads
every 50 ms, later under load). Nothing waiting on the master and
nothing more read for 0.1 s."""
quiet = None
def done():
nonlocal quiet
with self.lock:
now = (struct.unpack('i', fcntl.ioctl(self.master, termios.FIONREAD, b'\0\0\0\0'))[0], len(self.out))
if now[0] or quiet is None or quiet[0] != now:
quiet = (now, time.monotonic())
return time.monotonic() - quiet[1] >= .1
wait_for('the terminal\'s last bytes read', done)
return self.text()
def close(self):
self.closing = True
self.reader.join(timeout=2)
os.close(self.slave)
os.close(self.master)
def run(client, serial, line):
"""pty/run: a line in, `exit N` and its output out."""
fid = client.open(f'/pane/{serial}/pty/run', 2)
try:
client.rpc(118, struct.pack('<IQI', fid, 0, len(line)) + line)
return client.read_fid(fid)
finally:
client.close(fid)
def pid_in(client, pane):
"""The pid of terminal `pane`'s shell, its `echo $$` by pty/run, asked
at once: a run written before its first prompt (or before the prompt
after its greeting) waits for it, and one under a prompt drawn again
(a window's first size, an adoption's two) is still the line run
(core/ninep/pty.zig). Any other answer is said whole."""
said = run(client, pane, b'echo $$\n')
pid = re.fullmatch(rb'exit 0\n([0-9]+)\n', said)
assert pid, f'pane {pane}: `echo $$` answered {said!r}'
return int(pid[1])
# FreeBSD has no /proc: ps and procstat answer instead.
procfs = os.path.isdir('/proc/self')
def ps(*args):
return subprocess.run(['ps', *args], capture_output=True).stdout
def exit_session(nine, pane):
"""Exit, by the session's 9P, again when unsaved text asks first. The
Exit that ends the session may close its link before the write's clunk
is answered: that EOF is the session gone, as asked."""
for _ in range(2):
try:
nine.write(f'/pane/{pane}/exec', b'Exit\n')
return
except EOFError:
return
except OSError as err:
# An edited file asks before it goes.
assert 'Exit again' in str(err), err
def processes(root):
"""The pids whose environment is this run's (its runtime directory)."""
found = []
mark = f'XDG_RUNTIME_DIR={root}'.encode()
if not procfs: # ps -e prints each environment before its command
return [int(row.split()[0]) for row in ps('-axeww', '-o', 'pid=', '-o', 'command=').splitlines()
if mark in row.split()]
for entry in os.listdir('/proc'):
if not entry.isdigit():
continue
try:
environ = open(f'/proc/{entry}/environ', 'rb').read().split(b'\0')
except OSError:
continue
if mark in environ:
found.append(int(entry))
return found
def cmdline(pid):
if not procfs:
return ps('-ww', '-o', 'args=', '-p', str(pid)).split()
try:
return open(f'/proc/{pid}/cmdline', 'rb').read().split(b'\0')
except OSError:
return []
def alive(pid):
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
if not procfs:
return not ps('-o', 'state=', '-p', str(pid)).startswith(b'Z')
try:
state = open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[0]
except OSError:
return False
return state != 'Z'
def fds(pid):
if not procfs:
return len(subprocess.run(['procstat', '-f', str(pid)], capture_output=True).stdout.splitlines()) - 1
try:
return len(os.listdir(f'/proc/{pid}/fd'))
except OSError:
return -1
def links(pid):
"""What its fds are open on."""
if not procfs:
return [line.split()[-1] for line in subprocess.run(['procstat', '-f', str(pid)], capture_output=True,
text=True).stdout.splitlines()[1:] if line.split()]
out = []
for fd in os.listdir(f'/proc/{pid}/fd'):
try:
out.append(os.readlink(f'/proc/{pid}/fd/{fd}'))
except OSError:
pass
return out
def sockets(pid):
"""The sockets process `pid` holds (`socket:[inode]`): a client's link
among them, the same one while it joins again over it."""
out = set()
for fd in os.listdir(f'/proc/{pid}/fd'):
try:
link = os.readlink(f'/proc/{pid}/fd/{fd}')
except OSError:
continue
if link.startswith('socket:'):
out.add(link)
return out
def session_stats(path):
"""A session's PARDES_REPLICA_STATS line, its words a dict, and its joins'
count (`joins_us`'s)."""
text = path.read_text() if path.exists() else ''
line = next((l for l in text.splitlines() if l.startswith('session inputs')), '')
w = line.split()
d = {w[i]: w[i + 1] for i in range(1, len(w) - 1, 2)}
joins = next((len(l.split()) - 2 for l in text.splitlines() if l.startswith('session joins_us')), 0)
return d, joins
def state_fds(pid):
"""Its fds on the state file, which a session keeps open (Db.zig)."""
return sum(1 for path in links(pid) if path.endswith('/pardes.xitdb'))
def semantics(binary):
"""What a replica's build must share with its session's (--version)."""
out = subprocess.run([binary, '--version'], capture_output=True, check=True).stdout.decode()
return int(next(line.split()[1] for line in out.splitlines() if line.startswith('semantics ')), 16)
class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
WIRE = 38
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.s.settimeout(timeout)
self.s.connect(os.fspath(path))
def send(self, tag, payload):
self.s.sendall(struct.pack('<BI', tag, len(payload)) + payload)
def take(self, n):
got = b''
while len(got) < n:
more = self.s.recv(n - len(got))
if not more:
raise EOFError('the connection ended')
got += more
return got
def read(self):
tag, n = struct.unpack('<BI', self.take(5))
return tag, self.take(n)
def hello(self, session, build, wire=None):
"""('welcome', pid, name) or ('refused', why); a welcome's dump
is read, whole. A daemon of another replica protocol (an older
build's, across an Upgrade) is dialled again in its own."""
name = session.encode()
# Its first word (not far) in the same write, as a client's join
# sends it (core/replica.zig joinOn): a refused hello's connection
# is closed, and a second write after it would meet that.
hello = struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff'
self.s.sendall(struct.pack('<BI', 0x01, len(hello)) + hello + struct.pack('<BIB', 0x06, 1, 0))
tag, body = self.read()
if tag == 0x01:
pid, n = struct.unpack_from('<IH', body)
client, view, dump_len, gmtoff, digest = struct.unpack_from("<HBQiQ", body, 6 + n)
got = 0
while got < dump_len:
tag, piece = self.read()
assert tag == 0x04, tag
got += len(piece)
self.dump_len = dump_len
return 'welcome', pid, body[6:6 + n].decode()
assert tag == 0x02, (tag, body)
n, = struct.unpack_from('<H', body)
why = body[2:2 + n].decode()
other = re.search(r'replica protocol \d+, and this daemon (\d+)', why)
if other and wire is None:
self.close()
self.__init__(self.path, self.timeout)
return self.hello(session, build, int(other.group(1)))
return 'refused', why
def ping(self, value):
"""One round trip, in ms (the session's units on the way are
passed over)."""
t = time.monotonic()
self.send(0x03, struct.pack('<Q', value))
while True:
tag, body = self.read()
if tag != 0x05:
break
assert (tag, body) == (0x03, struct.pack('<Q', value)), (tag, body)
return (time.monotonic() - t) * 1000
def close(self):
self.s.close()
def replicas(root, binary, session, daemon):
sock = root / 'pardes-replica.sock'
wait_for('the replicas\' socket', sock.exists)
assert len(os.fspath(sock)) < 104, 'FreeBSD\'s sun_path'
ours = semantics(binary)
before = fds(session), fds(daemon)
t = time.monotonic()
r = Replica(sock)
said = r.hello('work', ours)
hello_ms = (time.monotonic() - t) * 1000
# The session answers, so the connection is its own now: the daemon
# keeps no copy of it.
assert said == ('welcome', session, 'work'), said
rtt = [r.ping(i) for i in range(50)]
assert fds(session) == before[0] + 1 and fds(daemon) == before[1], (before, fds(session), fds(daemon))
r.close()
wait_for('the replica\'s end, in the session', lambda: fds(session) == before[0])
said = Replica(sock).hello('work', ours ^ 1)
assert said[0] == 'refused' and 'another build' in said[1] and f'{ours ^ 1:016x}' in said[1], said
said = Replica(sock).hello('nobody', ours)
assert said == ('refused', "no session called 'nobody'"), said
wait_for('the daemon\'s refused connections closed', lambda: fds(daemon) == before[1])
print(f'daemon: a replica handed to its session (hello {hello_ms:.2f} ms, ping median '
f'{statistics.median(rtt):.3f} ms); another build, and a session nobody has, refused')
def ping(path, session, binary, n):
build = semantics(binary)
t = time.monotonic()
r = Replica(path, timeout=30)
said = r.hello(session, build)
hello_ms = (time.monotonic() - t) * 1000
if said[0] != 'welcome':
sys.exit(f'refused: {said[1]}')
rtt = sorted(r.ping(i) for i in range(n))
r.send(0x02, b'')
r.close()
print(f'connect and hello {hello_ms:.2f} ms; {n} pings min/median/p90/max '
f'{rtt[0]:.2f}/{statistics.median(rtt):.2f}/{rtt[int(n * .9) - 1]:.2f}/{rtt[-1]:.2f} ms')
def checks(path):
"""A replica client's checks against its session (PARDES_REPLICA_CHECK)."""
try:
return path.read_text().splitlines()
except FileNotFoundError:
return []
def normal_again(term):
"""The client's cursor a block again after its beam: the Esc it was sent
ended insert mode. A key written before that can reach it in one read
with the Esc, which is then Alt on that key."""
t = term.text()
return t.rfind(b'\x1b[0 q') > t.rfind(b'\x1b[6 q')
def agreed(path, after):
"""A check after the first `after` agreed; one that differed fails."""
lines = checks(path)
bad = [line for line in lines if line.startswith('differ')]
assert not bad, (path.name, bad)
return len(lines) > after
def made_live(term, check):
"""A key in a replica client's terminal (`gg`), stepped by its session
(a check after it agreed): its view is the live one, the one /layout
reads and /exec runs in, until the next input. A client asks one check
at a time, and checks come on (each answer wakes its session): the
first after the key may have been asked before it, the second was not."""
seen = len(checks(check))
os.write(term.master, b'gg')
wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=20)
def view_panes(client):
"""The panes the live view lays out (/layout's pane serials)."""
return {int(x) for line in client.read('/layout').decode().splitlines()
if line.split()[:1] != ['active'] for x in line.split()[6:]}
def in_own_view(what, live, client, pane, theirs):
"""`live()` makes a client's view the live one (made_live, still), and
/layout read after it lays out its pane and not the other client's:
asked again until it does, for a view is the live one only until the
next input (the session's own terminal answering a query late, the
other client's rejoin sizing it). A view lost lays out neither pane,
another's lays out theirs: neither ever passes."""
def own():
live()
shown = view_panes(client)
return pane in shown and theirs not in shown
try:
wait_for(what, own, timeout=30)
except TimeoutError:
raise AssertionError((what, pane, theirs, client.read('/layout'))) from None
def clients(binary):
"""Replica clients of a detached session: one on the replica socket,
one through the delay relay; each one's keys in the session's text and
every client's digest the session's once quiet; one killed outright
while the other types on; nothing left behind."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started = []
terms = []
try:
# Its joins counted at its end (PARDES_REPLICA_STATS): those over a
# client's own link (`again`) and all of them (`joins_us`).
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')),
cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
alone = fds(sess.pid)
relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'),
str(root / 'relay.sock'), str(sock), '--delay', '40'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
started.append(relay.pid)
wait_for('the relay', (root / 'relay.sock').exists)
ta, tb = Term(30, 100), Term(24, 80)
terms += [ta, tb]
a = ta.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'a.check')))
b = tb.spawn([binary, f'--attach={root / "relay.sock"}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'b.check')))
started += [a.pid, b.pid]
for t in (ta, tb):
wait_for('a client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=20)
os.write(ta.master, b'Ofrom-A\x1b')
os.write(tb.master, b'jjofrom-B\x1b')
wait_for('both clients\' keys in the session\'s text', lambda: b'from-A' in nine.read(f'/pane/{pane}/body')
and b'from-B' in nine.read(f'/pane/{pane}/body'))
wait_for('both clients out of insert mode', lambda: normal_again(ta) and normal_again(tb))
wait_for('client A agrees once quiet', lambda: agreed(root / 'a.check', 0))
wait_for('client B agrees once quiet', lambda: agreed(root / 'b.check', 0))
# A terminal attached by the session's name alone while a client's
# view is live (its input the last): a client too, drawn.
tt = Term(24, 80)
terms.append(tt)
stub = tt.spawn([binary, '--attach=files'], env)
started.append(stub.pid)
wait_for('the attached terminal\'s frame', lambda: b'line 3 of the notes' in tt.text(), timeout=20)
stub.send_signal(signal.SIGHUP)
stub.wait(timeout=10)
# One put off the session's state (PARDES_TEST_DIVERGE, at its
# 100th unit): the next unit's digest finds it, it says so in a line
# and joins again for its view, a pane of its own in it, its keys
# after go into that pane and it agrees.
td = Term(24, 90)
terms.append(td)
d = td.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'd.check'), PARDES_TEST_DIVERGE='100'))
started.append(d.pid)
wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20)
made_live(td, root / 'd.check')
d_links = sockets(d.pid)
shown = view_panes(nine)
nine.write('/exec', b'New\n')
mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop()
# Others' units, replayed on D's core: one after its 100th finds it.
deadline = time.monotonic() + 60
while b'joined again' not in td.text():
assert time.monotonic() < deadline, 'client D diverged and joined again'
os.write(ta.master, b'jk')
time.sleep(.2)
assert d.poll() is None
# Over its own link: the same connection, no hand-over (counted at
# the session's end).
assert sockets(d.pid) == d_links, ('client D joined again over its own link', d_links, sockets(d.pid))
made_live(td, root / 'd.check')
assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout'))
seen = len(checks(root / 'd.check'))
os.write(td.master, b'Oafter-rejoin-D\x1b')
wait_for('client D\'s keys after its rejoin', lambda: b'after-rejoin-D' in nine.read(f'/pane/{mine}/body'))
wait_for('client D out of insert mode', lambda: normal_again(td))
wait_for('client D agrees after its rejoin', lambda: agreed(root / 'd.check', seen))
os.write(td.master, b' sD')
wait_for('client D let go', lambda: d.poll() is not None, timeout=10)
# Killed outright: the session and the other client carry on.
os.kill(b.pid, signal.SIGKILL)
b.wait(timeout=10)
seen = len(checks(root / 'a.check'))
os.write(ta.master, b'jjjAagain-A\x1b')
wait_for('client A\'s keys after B went', lambda: b'again-A' in nine.read(f'/pane/{pane}/body'))
wait_for('client A out of insert mode', lambda: normal_again(ta))
wait_for('client A agrees again', lambda: agreed(root / 'a.check', seen))
assert sess.poll() is None
# Detach typed in it: it alone goes, and says so (exit 0).
os.write(ta.master, b' sD')
wait_for('client A let go', lambda: a.poll() is not None, timeout=10)
assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.last(), ta.last()[-300:]
# A third client, a shell: its keys wait for the session (a pty
# write), its output comes back in units, the same on both sides.
nine.write(f'/pane/{pane}/exec', b'Term\n')
shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines()
if row.split()[1] == b'term'), None))
wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body'))
alone = fds(sess.pid)
tc = Term(30, 100)
terms.append(tc)
c = tc.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check')))
started.append(c.pid)
wait_for('client C\'s first frame', lambda: b'$' in tc.text(), timeout=20)
said = run(nine, shell, b'echo from-the-session\n')
assert said == b'exit 0\nfrom-the-session\n', said
os.write(tc.master, b'echo from-C\r')
wait_for('client C\'s keys in the shell', lambda: b'from-C' in nine.read(f'/pane/{shell}/body'))
wait_for('client C agrees with a shell\'s output', lambda: agreed(root / 'c.check', 0))
# Its terminal hung up: it dies, and the session carries on.
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
relay.kill()
relay.wait()
wait_for('the session\'s fds level', lambda: fds(sess.pid) == alone, timeout=10)
print(f'daemon: two replica clients (one through a 40 ms relay) typed into a detached session; '
f'digests agreed {len(checks(root / "a.check"))} and {len(checks(root / "b.check"))} times; '
f'one put off the session\'s state joined again in its own view and agreed {len(checks(root / "d.check"))} times; '
f'one killed, the other typed on and detached; a third typed into a shell, agreed '
f'{len(checks(root / "c.check"))} times, and was hung up')
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
said, joins = session_stats(root / 'session.stats')
here = int(said.get('again', '-1'))
assert here >= 1, ('the session joined client D again over its link', said)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
print(f'daemon: replica clients\' session ended, nothing left behind; its joins: {joins}, of them over a '
f'client\'s own link {here}, handed by the daemon {joins - here}')
finally:
for t in terms:
t.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def launch(binary):
"""`pardes new --detach=NAME` returns once its session is registered
and listening: exit 0, the name on stdout, the session a process of its
own in a session of its own, listed by `ps` and answering 9P at once;
bare `--detach`, its pid is its name; a name taken is refused in words,
exit 1; `pardes --detach=NAME` (no `new`) is still the session itself;
nothing left behind."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'notes.txt').write_text('notes\n')
def cli(*args, timeout=30):
return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout,
stdin=subprocess.DEVNULL)
def status_pid(name):
with Client(root / f'pardes-9p-{name}.sock') as c:
return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid'])
try:
t0 = time.monotonic()
try:
out = cli('new', '--detach=work', 'notes.txt', timeout=15)
except subprocess.TimeoutExpired:
raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s')
took = time.monotonic() - t0
assert out.returncode == 0 and out.stdout == b'work\n', out
# Registered and listening when it returned: no wait here.
assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
pid = status_pid('work')
listed = cli('ps').stdout.decode()
assert f'session work {pid} {listed_as('detached')}' in listed, listed
assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
out = cli('new', '--detach')
assert out.returncode == 0 and out.stdout.strip().isdigit(), out
unnamed = int(out.stdout)
assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} {listed_as('detached')}' in cli('ps').stdout.decode()
taken = cli('new', '--detach=work')
assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
# The flag alone runs the session in this process, as a supervisor
# or a harness wants it.
fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists)
assert status_pid('fg') == fg.pid and fg.poll() is None
print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening '
f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session')
for name in ('work', str(unnamed), 'fg'):
assert cli('kill', name).returncode == 0
fg.wait(timeout=10)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
print('launch: nothing left behind')
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def pair(binary):
"""PARDES_PAIR: `pardes FILE` in a terminal is a session forked off for
it with this terminal its first client (the last step's design, 1.1):
the job the client, the terminal its own; the session its child, in a
session of its own, registered (`ps`: detached, the client listed),
the file drawn, keys in, the digests agreed once quiet; the session's
Exit ends both. With no daemon the client killed outright ends the
session (its last link). Nothing left behind."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
def session_of(name):
sock = root / f'pardes-9p-{name}.sock'
wait_for(f'session {name}\'s 9P socket', sock.exists)
nine = Client(sock)
return nine, int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
try:
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, '--9p=pair', str(notes)], dict(env, PARDES_REPLICA_CHECK=str(root / 'pair.check')))
nine, session = session_of('pair')
assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
wait_for('the client listed', lambda: f'session pair {session} (tty)' in listed()
and f'client {c.pid} ' in listed())
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
os.write(t.master, b'Ofrom-the-pair\x1b')
wait_for('its keys in the session\'s text', lambda: b'from-the-pair' in nine.read(f'/pane/{pane}/body'))
wait_for('out of insert mode', lambda: normal_again(t))
wait_for('the client agrees once quiet', lambda: agreed(root / 'pair.check', 0))
exit_session(nine, pane)
code = c.wait(timeout=60)
assert code == 0 and not alive(session), (code, alive(session))
print(f'pair: client {c.pid} (the job) and session {session} (its child, setsid, listed detached with the client); '
f'drawn, typed, agreed; Exit ended both (the client exit {code})')
nine.socket.close()
lone = Term(24, 80)
terms.append(lone)
c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
nine2, session2 = session_of('lone')
wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
# An Upgrade refused, with why: its client could not find it again.
nine2.write('/ctl', b'Upgrade\n')
wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20)
assert alive(session2) and c2.poll() is None
nine2.socket.close()
os.kill(c2.pid, signal.SIGKILL)
c2.wait(timeout=10)
wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def pair_rows(binary):
"""PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
session's lifetime (2.2 B), one row a step. `ps` says a pair's session
`kept` (started --detach, or a Detach typed in any client since), or
nothing after its kind; an Upgrade carries which. Kept: a client ended
by TERM, KILL or a closed terminal (HUP) leaves it running, as does a
Detach typed in one (said, exit 0). With no daemon: a Detach refused
(nothing could attach), the client on; its terminal closed, the session
ends with its last link."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
def listed():
return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
def state_of(name):
"""What `ps` says of session `name` after its pid: `(tty)`, `(tty, kept)`."""
for line in listed().splitlines():
if line.split()[:2] == ['session', name]:
return line[line.index('('):]
def drawn(t):
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
def typed_detach(t, nine, pane):
# Its view the live one (it typed last), then the word.
os.write(t.master, b'j')
time.sleep(.3)
nine.write(f'/pane/{pane}/exec', b'Detach\n')
def started(name, e):
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, f'--9p={name}', str(notes)], e)
wait_for('the socket', (root / f'pardes-9p-{name}.sock').exists)
nine = Client(root / f'pardes-9p-{name}.sock')
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
drawn(t)
return t, c, nine, session, pane
def attached(name):
tt = Term(30, 100)
terms.append(tt)
a = tt.spawn([binary, 'attach', name], env)
drawn(tt)
wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
return tt, a
def ended_by(how, tt, a):
"""Client `a` on terminal `tt` ended: TERM, KILL, or HUP (its terminal
closed); its exit status, once it is unlisted."""
if how == 'HUP':
tt.close()
terms.remove(tt)
else:
os.kill(a.pid, getattr(signal, 'SIG' + how))
code = a.wait(timeout=20)
if how == 'TERM':
wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
return code
def upgraded(name, nine, session):
"""An Upgrade to the same build: the session exec'd under its pid, its
9P again: its socket made anew (a second Upgrade's command line says
`--upgraded=` before its exec too)."""
sock = root / f'pardes-9p-{name}.sock'
before = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60)
nine.socket.close()
again = reconnect(root / f'pardes-9p-{name}.sock')
assert alive(session)
return again
try:
# Kept from birth: `new --detach`. Its clients end and it runs on.
out = subprocess.run([binary, 'new', '--detach=kd', str(notes)], env=env, cwd=root, capture_output=True,
timeout=30, stdin=subprocess.DEVNULL)
assert out.returncode == 0, out
with Client(root / 'pardes-9p-kd.sock') as kn:
kd = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
assert state_of('kd') == '(tty, kept)', listed()
for how in ('HUP', 'TERM'):
ended_by(how, *attached('kd'))
assert alive(kd) and state_of('kd') == '(tty, kept)', (how, listed())
# Started by `new` with a file: an Upgrade keeps it (its `new` is the
# verb still: taken for a file's name, the file was "the second" and
# the session ended), and it is attached to after.
upgraded('kd', Client(root / 'pardes-9p-kd.sock'), kd).socket.close()
assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
ended_by('TERM', *attached('kd'))
assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
print('pair rows: `new --detach` with a file: an Upgrade keeps it, and it is attached to after')
assert subprocess.run([binary, 'kill', 'kd'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('kd ended', lambda: not alive(kd), timeout=30)
print('pair rows: `new --detach` kept from birth (ps: (tty, kept)); its client ended by HUP, by TERM: it runs on')
# Not kept: a client's close (its terminal closed, a TERM) ends the
# session when it was the last; a KILL is a loss, it runs on.
t, c, nine, session, pane = started('nk', env)
# Dead of the signal, its goodbye said, as the own path's stub dies.
assert ended_by('HUP', *attached('nk')) == -signal.SIGHUP
assert alive(session) and state_of('nk') == '(tty)', ('not its last client', listed())
os.kill(c.pid, signal.SIGKILL)
c.wait(timeout=10)
wait_for('the client unlisted', lambda: f'client {c.pid} ' not in listed())
assert alive(session) and state_of('nk') == '(tty)', ('a loss', listed())
assert ended_by('TERM', *attached('nk')) == -signal.SIGTERM
wait_for('the session ended at its last client\'s close', lambda: not alive(session), timeout=20)
assert state_of('nk') is None, listed()
nine.socket.close()
print('pair rows: not kept: a client\'s terminal closed (not the last): it runs on; its own killed -9: it runs on, '
'listed; the last client TERMed (exit 0, its terminal put back): the session ended')
# The pair's own terminal closed after an Upgrade: its last client's
# close, which the Upgrade did not make kept.
t, c, nine, session, pane = started('nk2', env)
nine = upgraded('nk2', nine, session)
wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
nine.socket.close()
t.close()
terms.remove(t)
assert c.wait(timeout=20) == -signal.SIGHUP, c.returncode
wait_for('the session ended with its terminal', lambda: not alive(session), timeout=20)
print('pair rows: not kept, upgraded: its terminal closed (exit 0): the session ended')
# Without the variable nothing changes: an attach client's TERM
# leaves the session running, and its own terminal closed detaches it.
own_env = {k: v for k, v in env.items() if k != 'PARDES_PAIR'}
t, c, nine, session, pane = started('own', own_env)
assert state_of('own') == '(tty, has a frontend)', listed()
assert ended_by('TERM', *attached('own')) == -signal.SIGTERM
assert alive(session) and state_of('own') == '(tty, has a frontend)', listed()
nine.socket.close()
t.close()
terms.remove(t)
c.wait(timeout=20)
wait_for('the own session detached', lambda: state_of('own') == '(tty, detached)')
assert alive(session)
assert subprocess.run([binary, 'kill', 'own'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the own session ended', lambda: not alive(session), timeout=30)
print('pair rows: without the variable: an attach client TERMed, the session on; its terminal closed, it detached (ps: (tty, detached))')
# A pair: not kept, and not across an Upgrade either; a Detach typed
# in its client keeps it, across an Upgrade too.
t, c, nine, session, pane = started('rows', env)
assert state_of('rows') == '(tty)', listed()
nine = upgraded('rows', nine, session)
wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty)')
wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
typed_detach(t, nine, pane)
assert c.wait(timeout=20) == 0, c.returncode
wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
assert alive(session) and state_of('rows') == '(tty, kept)', listed()
nine = upgraded('rows', nine, session)
wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty, kept)')
print('pair rows: a pair (ps: (tty)), so after an Upgrade; Detach in its client: said, exit 0, it runs on, kept, so after an Upgrade')
for how in ('TERM', 'KILL', 'HUP'):
ended_by(how, *attached('rows'))
assert alive(session) and state_of('rows') == '(tty, kept)', (how, listed())
print(f'pair rows: kept: a client ended by {how}: the session runs on')
nine.socket.close()
assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off'))
typed_detach(t, nine, pane)
time.sleep(1)
# Which went, if one did: the client's exit and its screen's last
# words, the session's life (its stderr is /dev/null: no log).
went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone]
assert not went, (f'a Detach with no daemon is refused: {" and ".join(went)} went (client exit {c.poll()}, '
f'session {"alive" if alive(session) else "gone"}); the terminal\'s last bytes: {t.text()[-600:]!r}')
nine.socket.close()
t.close()
terms.remove(t)
c.wait(timeout=20)
wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
print('pair rows: no daemon: a Detach refused, the client on; its terminal closed, the session ended; nothing left')
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def pair_back(binary):
"""A pair with no daemon (PARDES_DAEMON=off, the pair's default-to-be
with none reachable): its client put off the session's state
(PARDES_TEST_DIVERGE), and apart from that stopped 3 s while the
session's file is edited over 9P (SIGSTOP: past replica.behind_max_ms):
each time it joins again over its own link ("joined again" on its
screen, its socket the same), the session lives on with the text typed
in it, unsaved, and the client agrees; its terminal closed, the session
ends with its last link. Before pardes-link-1 its rejoin dialled the
daemon's socket, nothing took it, and the whole session went (the
client exit 1: reports/pardes-pair-12.md, 2b)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rb-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color',
SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1', PARDES_DAEMON='off')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
try:
for how in ('diverged', 'behind'):
t = Term(30, 100)
terms.append(t)
check = root / f'{how}.check'
e = dict(env, PARDES_REPLICA_CHECK=str(check), **({'PARDES_TEST_DIVERGE': '3'} if how == 'diverged' else {}))
c = t.spawn([binary, f'--9p={how}', str(notes)], e)
wait_for('the socket', (root / f'pardes-9p-{how}.sock').exists)
nine = Client(root / f'pardes-9p-{how}.sock')
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
links = sockets(c.pid)
mark = len(t.text())
words = f'unsaved-{how}'.encode()
os.write(t.master, b'O' + words + b'\x1b')
wait_for('its keys in the session\'s text', lambda: words in nine.read(f'/pane/{pane}/body'))
if how == 'behind':
os.kill(c.pid, signal.SIGSTOP)
for k in range(30):
nine.write(f'/pane/{pane}/exec', f'Edit 3a/ edit {k} /\n'.encode())
time.sleep(.1)
os.kill(c.pid, signal.SIGCONT)
deadline = time.monotonic() + 30
while b'joined again' not in t.text()[mark:]:
went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone]
assert not went, (f'{how}: {" and ".join(went)} went (client exit {c.poll()}); '
f'its terminal\'s last bytes: {t.text()[-600:]!r}')
assert time.monotonic() < deadline, f'{how}: the client joined again'
os.write(t.master, b'jk')
time.sleep(.2)
said = b'this client diverged' if how == 'diverged' else b' s behind'
wait_for(f'{how}: its notice says why', lambda: said in t.text()[mark:], timeout=10)
assert c.poll() is None and alive(session), (how, c.poll())
assert sockets(c.pid) == links, (f'{how}: joined again over its own link', links, sockets(c.pid))
assert words in nine.read(f'/pane/{pane}/body'), how
seen = len(checks(check))
os.write(t.master, b'jj')
wait_for(f'{how}: the client agrees after it', lambda: agreed(check, seen), timeout=30)
nine.socket.close()
t.close()
terms.remove(t)
c.wait(timeout=20)
wait_for(f'{how}: the session ended with its last link', lambda: not alive(session), timeout=20)
print(f'pair back: no daemon, its client {how}: joined again over its own link, the session alive, '
f'its unsaved text there, agreed; its terminal closed, the session ended')
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def attach_upgrading(binary, rounds=6, dump=True):
"""`pardes attach` as its session upgrades: started at once after the
Upgrade's word, it is handed to the session before the exec; told the
session is upgrading (never cut by the exec unanswered: "hung up before
the dump was whole", exit 1), it dials again and joins the new process.
A `new --detach` session, without the variable and with it."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
try:
for e in (env, dict(env, PARDES_PAIR='1')):
name = 'up' + e.get('PARDES_PAIR', '')
out = subprocess.run([binary, 'new', f'--detach={name}', str(notes)], env=e, cwd=root, capture_output=True,
timeout=30, stdin=subprocess.DEVNULL)
assert out.returncode == 0, out
sock = root / f'pardes-9p-{name}.sock'
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
for k in range(rounds):
before = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
time.sleep(k * .005)
t = Term(30, 100)
terms.append(t)
a = t.spawn([binary, 'attach', name], e)
wait_for('the client drawn, or gone', lambda: b'line 3 of the notes' in t.text() or a.poll() is not None, timeout=40)
assert a.poll() is None, (k, a.returncode, t.text()[-120:])
os.kill(a.pid, signal.SIGKILL)
a.wait(timeout=10)
wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60)
nine.socket.close()
nine = reconnect(sock)
assert alive(session)
nine.socket.close()
assert subprocess.run([binary, 'kill', name], env=e, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
# A join whose dump is still on its way when the Upgrade comes (a
# 100 MB file: the flush before the exec lets it go cut): it joins
# again, as one told so does; never "let this client go".
# Once a run (plain mode, --attach-upgrading): a slow round.
if dump:
big = root / 'big.txt'
with open(big, 'w') as f:
f.write('a line of a big file, long enough to be a fair line of text in a log: 0123456789\n' * 1_250_000)
out = subprocess.run([binary, 'new', '--detach=big', str(big)], env=env, cwd=root, capture_output=True,
timeout=60, stdin=subprocess.DEVNULL)
assert out.returncode == 0, out
sock = root / 'pardes-9p-big.sock'
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
for k in range(2):
t = Term(30, 100)
terms.append(t)
a = t.spawn([binary, 'attach', 'big'], env)
listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() # noqa: E731
wait_for('the attach joined', lambda: f'client {a.pid} ' in listed() or a.poll() is not None, timeout=60)
before = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
wait_for('joined again, or gone', lambda: b'joined again' in t.text() or a.poll() is not None, timeout=180)
assert a.poll() is None, ('a join cut mid-dump', k, a.returncode, t.text()[-120:])
a.terminate()
a.wait(timeout=20)
wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60)
nine.socket.close()
nine = reconnect(sock)
nine.socket.close()
assert subprocess.run([binary, 'kill', 'big'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the big session ended', lambda: not alive(session), timeout=30)
print(f'attach upgrading: an attach started as its session upgrades joins the new process ({rounds} of {rounds}, '
'without the variable and with it)' + ('; a join whose 100 MB dump the exec cut joined again, 2 of 2' if dump else ''))
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def kept_views(binary):
"""A view kept for its client's rejoin (views.away: a bye that says it
joins again, a client cut off behind, every client at an Upgrade) is
that client's for 30 s, then a join with no room takes it, in a session
nobody types in: a `new --detach` session at its four views (a client
attached, idle; raw replicas), two of them leaving to join again and
never coming back; a join at once is refused and told for how long, one
a second past that, nothing typed in between, is welcomed."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
t = Term(30, 100)
rs = []
try:
out = subprocess.run([binary, 'new', '--detach=kv'], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL)
assert out.returncode == 0, out
a = t.spawn([binary, 'attach', 'kv'], env)
wait_for('the client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
sock, build = root / 'pardes-replica.sock', semantics(binary)
while True:
r = Replica(sock)
said = r.hello('kv', build)
if said[0] != 'welcome':
break
rs.append(r)
assert said[0] == 'refused' and 'as many views' in said[1] and len(rs) >= 2, (said, len(rs))
for r in rs[:2]:
r.send(0x02, b'\x01')
r.close()
# The goodbyes reach the session on their own connections and the
# next join through the daemon, in no order between them: a join
# judged before the session took them is refused with no view kept
# yet. Dialled again until a refusal says one is.
dials = 0
def refused():
nonlocal dials
dials += 1
r = Replica(sock)
said = r.hello('kv', build)
r.close()
assert said[0] == 'refused' and 'as many views as it takes' in said[1], said
kept = re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1])
return kept and (said, int(kept.group(1)), time.monotonic())
said, more, at = wait_for('a join refused, a view kept', refused)
print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}" ({dials} dials)')
time.sleep(max(0, at + more + 1 - time.monotonic()))
said = Replica(sock).hello('kv', build)
assert said[0] == 'welcome', ('a view kept past what its refusal said in an idle session, still kept', more, said)
assert a.poll() is None
print(f'kept views: a join {more + 1} s after, nothing typed in between, took a kept view')
a.terminate()
a.wait(timeout=20)
assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
finally:
for r in rs:
r.close()
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
t.close()
shutil.rmtree(root, ignore_errors=True)
def pair_upgrade_views(binary):
"""PARDES_PAIR, two clients each in its own view (the pair's own terminal
and an attach), each with its own scroll and focus: the pair's scrolled
down a long file a page at a time, the attach's focus on a pane of its
own (New); an Upgrade lets both go and each joins again for its view
(views.away): the same lines shown, the cursor where it was, in each."""
import pyte
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
terms = []
def screen(t):
s = pyte.Screen(100, 30)
# Its colours (SGR with colons, which pyte misreads) left out.
pyte.ByteStream(s).feed(re.sub(rb'\x1b\[[0-9:;]*m', b'', t.text()))
return s
def shown(t):
"""The notes' lines it shows, and its cursor."""
s = screen(t)
return sorted(int(m.group(1)) for row in s.display for m in re.finditer(r'line (\d+) of the notes', row)), (s.cursor.x, s.cursor.y)
def settled(t):
last = [None, 0]
def same():
now = shown(t)
if now != last[0]:
last[0], last[1] = now, time.monotonic()
return time.monotonic() - last[1] > 1.5 and now
return wait_for('its screen settled', same, timeout=30)
try:
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, '--9p=pv', str(notes)], env)
sock = root / 'pardes-9p-pv.sock'
wait_for('the socket', sock.exists)
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
for _ in range(3):
os.write(t.master, b'\x1b[6~')
time.sleep(.2)
tt = Term(30, 100)
terms.append(tt)
a = tt.spawn([binary, 'attach', 'pv'], env)
wait_for('the attach drawn', lambda: b'\x1b[?1049h' in tt.text(), timeout=30)
os.write(tt.master, b'j')
time.sleep(.3)
before_panes = view_panes(nine)
nine.write('/exec', b'New\n')
wait_for('a pane in the attach\'s view', lambda: view_panes(nine) - before_panes)
def focus():
"""Each client's focus: its view live (a key that moves nothing)."""
got = []
for term in (t, tt):
os.write(term.master, b'\x1b')
time.sleep(.6)
got.append(nine.read('/focus'))
return got
focused = focus()
before = settled(t), settled(tt)
assert before[0][0] and before[0][0][0] >= 40, ('the pair scrolled', before[0])
marks = len(t.text()), len(tt.text())
ino = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
nine = reconnect(sock)
for term, mark in zip((t, tt), marks):
wait_for('joined again', lambda: b'joined again' in term.text()[mark:], timeout=30)
after = settled(t), settled(tt)
assert after == before, ('each client\'s lines and cursor as they were', before, after)
# Its focus: what it types lands in the pane it had the keyboard in
# (/focus, read after a key, is which view is live then: not a
# client's own).
for term, pane, word in zip((t, tt), focused, (b'PAIRTYPED', b'ATTACHTYPED')):
os.write(term.master, b'i' + word + b'\x1b')
wait_for('typed into its pane', lambda: word in nine.read(f'/pane/{int(pane)}/body'), timeout=10)
print('pair upgrade views: two clients, each its own view: the pair\'s scroll and the attach\'s focus as they were after an Upgrade')
nine.socket.close()
a.terminate()
a.wait(timeout=20)
os.kill(c.pid, signal.SIGTERM)
c.wait(timeout=20)
wait_for('the session ended', lambda: not alive(session), timeout=30)
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def pair_exec_reaps(old, new, early=False):
"""PARDES_PAIR across builds: a pair started from `root/bin` (old), its
session upgraded to the build installed there since (new): its client,
the session's parent, execs that build (the blink) and is still its
parent; Exit typed then: the client returns once the session is gone,
reaped, its status the session's (0), as before the exec. `early`: old
and new the same build, installed again at once, before the session's
first pass round its loop, where it first looks its start path up
(upgrade.zig `locate`), and as the client starts the daemon from its
own (daemon.zig `spawn`): the path is the path, not Linux's "PATH
(deleted)", so the daemon starts and the session execs it; the client,
its build the session's still, joins again in place (no exec)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'bin').mkdir()
binary = root / 'bin' / 'pardes'
install(old, binary)
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
sock = root / 'pardes-9p-px.sock'
c = session = None
try:
t = Term(30, 100)
terms.append(t)
c = t.spawn([str(binary), '--9p=px', str(notes)], env)
if early:
install(new, binary)
wait_for('the socket', sock.exists)
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
assert ppid(session) == c.pid
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
if not early:
install(new, binary)
ino = sock.stat().st_ino
# Before the Upgrade: the exec'd client can draw before its exec is seen.
mark = len(t.text())
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
if early:
wait_for('joined again in place', lambda: b'joined again' in t.text()[mark:], timeout=30)
else:
wait_for('the client on the new build', lambda: on_build(c, binary), timeout=30)
nine = reconnect(sock)
assert ppid(session) == c.pid
# The blink: its screen left and entered again, the notes drawn there.
if not early:
wait_for('drawn again', lambda: b'line 3 of the notes' in (entered_again(t.text(), mark) or b''), timeout=30)
nine.write('/ctl', b'Exit\n')
nine.socket.close()
assert c.wait(timeout=30) == 0, c.returncode
# Its parent's wait returned: the session reaped, not a zombie left
# to whoever takes it in.
assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read()
print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0'
+ (' (the same build installed again before the session looked its path up: joined again in place)' if early else ''))
except (TimeoutError, AssertionError, OSError, EOFError, subprocess.TimeoutExpired) as err:
kept = keep_evidence('pair-exec', root, env, binary, sock, [('session', session)] if session else [],
[('client', t, c, root / 'client.check', root / 'client.stats')] if c else [])
raise AssertionError(f'{type(err).__name__}: {err} (kept: {kept})') from None
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def far_exec(old, new):
"""A far client (PARDES_REPLICA_FAR, as through ssh's forward) of a
session started from `root/bin` (old), the session upgraded to the build
installed there since (new): the far client execs the build at its own
start path (its install holds the session's build now), the same
process, far still, and is back in its view: its key steps the session
and its digest agrees. Not through ssh: its forward's own end is not
here (its socket file left behind at the exec, the far install holding
another build: not covered)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'bin').mkdir()
binary = root / 'bin' / 'pardes'
install(old, binary)
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
try:
out = subprocess.run([str(binary), 'new', '--detach=fx', str(notes)], env=env, cwd=root, capture_output=True, timeout=30)
assert out.returncode == 0, out
sock = root / 'pardes-9p-fx.sock'
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
t = Term(30, 100)
terms.append(t)
check = root / 'f.check'
c = t.spawn([str(binary), f'--attach={root / "pardes-replica.sock"}:fx'],
dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check)))
wait_for('the far client drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
key = lambda b: os.write(t.master, b) # noqa: E731
seen = len(checks(check))
key(b'gg')
wait_for('its key stepped', lambda: agreed(check, seen + 1), timeout=30)
install(new, binary)
mark = len(t.text())
ino = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
nine = reconnect(sock)
wait_for('the far client on the new build', lambda: on_build(c, binary), timeout=30)
wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30)
# Its environment read once the new image runs (it entered the
# screen): an exec names the new file in /proc/PID/exe before it has
# written where the environment is, and a read between gets nothing
# (two CPUs: 170 execs of 200 read so).
assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True
seen = len(checks(check))
key(b'j')
wait_for('its key stepped after', lambda: agreed(check, seen + 1), timeout=30)
assert c.poll() is None
print('far exec: a far client exec\'d the build at its start path at its session\'s Upgrade, far still, and agrees')
c.terminate()
c.wait(timeout=20)
nine.socket.close()
assert subprocess.run([str(binary), 'kill', 'fx'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def pair_window_geometry(gui_binary, new_gui):
"""PARDES_PAIR, a window with `--geometry=WxH` (offscreen, not test
mode: its grid is its window's): another build at its start path, its
session upgraded: the window client execs it, and its new window is the
size it had (the session's grid as before), not the default's."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1',
SDL_VIDEO_DRIVER='offscreen')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
(root / 'bin').mkdir()
gui = root / 'bin' / 'pardes-gui'
install(Path(gui_binary), gui)
install(Path(gui_binary).with_name('pardes'), gui.with_name('pardes'))
procs = []
def grid(nine):
s = json.loads(nine.read('/screen'))
return s['cols'], s['rows']
def started(name, *flags):
p = subprocess.Popen([str(gui), f'--9p={name}', *flags, str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=open(root / f'{name}.err', 'w'), start_new_session=True)
procs.append(p)
sock = root / f'pardes-9p-{name}.sock'
wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
nine = Client(sock)
wait_for('its window\'s grid', lambda: grid(nine) != (80, 24), timeout=30)
time.sleep(1)
return p, nine, grid(nine)
try:
p0, n0, plain = started('plain')
n0.write('/ctl', b'Exit\n')
n0.socket.close()
p0.wait(timeout=30)
p, nine, sized = started('sized', '--geometry=900x560')
assert sized != plain, ('--geometry makes its own grid', sized, plain)
install(Path(new_gui), gui)
install(Path(new_gui).with_name('pardes'), gui.with_name('pardes'))
sock = root / 'pardes-9p-sized.sock'
ino = sock.stat().st_ino
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
wait_for('the window on the new build', lambda: on_build(p, gui), timeout=30)
nine = reconnect(sock)
time.sleep(3)
assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain)
print(f'pair window geometry: --geometry=900x560 ({sized[0]}x{sized[1]}, the default {plain[0]}x{plain[1]}): the window exec\'d at an Upgrade the size it had')
nine.write('/ctl', b'Exit\n')
nine.socket.close()
p.wait(timeout=30)
finally:
for p in procs:
if p.poll() is None:
p.kill()
for q in processes(root):
try:
os.kill(q, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
listed as no one's, the other ended by name with its shell, a name no
session has refused, the kept shell ended by --kill-all, and the daemon
gone after it."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
def cli(*args):
return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=30)
started = []
try:
sessions, shells = {}, {}
for name in ('one', 'two'):
(root / f'{name}.txt').write_text(f'{name}\n')
started.append(subprocess.Popen([binary, f'--detach={name}', str(root / f'{name}.txt')], env=env, cwd=root,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True).pid)
sock = root / f'pardes-9p-{name}.sock'
wait_for(f'session {name}\'s 9P socket', sock.exists)
with Client(sock) as c:
status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())
sessions[name] = int(status['pid'])
started.append(sessions[name])
c.write('/pane/1/exec', b'Term\n')
wait_for(f'session {name}\'s shell', lambda: terminals(c))
shell = terminals(c)[0]
shells[name] = pid_in(c, shell)
started.append(shells[name])
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
out = cli('--ps')
assert out.returncode == 0, out
listed = out.stdout.decode()
assert f'pardes daemon {daemon}' in listed, listed
for name in ('one', 'two'):
assert f'session {name} {sessions[name]} {listed_as('detached')}' in listed, listed
assert f'shell {shells[name]}' in listed, listed
# The same, a record a line, in each session's /sessions.
with Client(root / 'pardes-9p-one.sock') as c:
records = c.read('/sessions').decode().splitlines()
assert records[0] == f'daemon {daemon}', records
for name in ('one', 'two'):
at = records.index(f'session {sessions[name]} tty {"kept" if WITH_PAIR else "detached"} {name}')
assert records[at + 1] == f'shell {shells[name]}', records
print('manage: /sessions read over 9P listed the daemon, both sessions and their shells')
os.kill(sessions['two'], signal.SIGKILL)
wait_for('session two gone', lambda: not alive(sessions['two']))
wait_for('its shell no session\'s', lambda: 'no session holds' in cli('--ps').stdout.decode())
listed = cli('--ps').stdout.decode()
assert 'session two' not in listed and listed.index(f'shell {shells["two"]}') > listed.index('no session holds'), listed
assert alive(shells['two'])
print('manage: --ps listed two sessions and their shells, then a killed one\'s shell as no one\'s')
refused = cli('--kill=nobody')
assert refused.returncode == 1 and b"no session called 'nobody'" in refused.stderr, refused
killed = cli('--kill=one')
assert killed.returncode == 0, killed
assert not alive(sessions['one'])
wait_for('session one\'s shell hung up with it', lambda: not alive(shells['one']))
assert alive(shells['two']) and 'session one' not in cli('--ps').stdout.decode()
assert cli('--kill-all').returncode == 0
wait_for('the kept shell ended', lambda: not alive(shells['two']))
wait_for('the daemon gone once it keeps nothing', lambda: not alive(daemon))
none = cli('--ps')
assert none.returncode == 1 and b'no pardes daemon is running' in none.stderr, none
print('manage: --kill=one ended it and its shell, --kill-all the kept shell, a name nobody has refused; the daemon left')
finally:
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
shutil.rmtree(root, ignore_errors=True)
def wakeups(pid, secs):
"""Its threads' context switches over `secs` (Linux's /proc): none for
a process nothing wakes."""
def count():
n = 0
for task in os.listdir(f'/proc/{pid}/task'):
try:
for line in open(f'/proc/{pid}/task/{task}/status'):
if line.split(':')[0] in ('voluntary_ctxt_switches', 'nonvoluntary_ctxt_switches'):
n += int(line.split()[1])
except OSError:
pass
return n
before = count()
time.sleep(secs)
return count() - before
def relink(binary):
"""The daemon killed outright (docs/next-run.md, "A session registering
again"): a detached session and a terminal's, each with a shell, dial
the next daemon themselves (the first to find none starts it) and
register again with their shells' masters, so `--ps` lists both and
their shells, a client attaches, and the session then killed outright
leaves its shell to an Adopt. An idle session stays idle before and
after."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
def listed():
out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30)
return out.stdout.decode() if out.returncode == 0 else ''
def daemons():
return [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon'] and alive(p)]
started = []
terms = []
try:
(root / 'notes.txt').write_text('notes\n')
started.append(subprocess.Popen([binary, '--detach=work', str(root / 'notes.txt')], env=env, cwd=root,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True).pid)
wait_for('the detached session\'s 9P socket', (root / 'pardes-9p-work.sock').exists)
work = Client(root / 'pardes-9p-work.sock')
session = int(dict(line.split(maxsplit=1) for line in work.read('/status').decode().splitlines())['pid'])
started.append(session)
work.write('/pane/1/exec', b'Term\n')
wait_for('its shell', lambda: terminals(work))
shell = terminals(work)[0]
shell_pid = pid_in(work, shell)
started.append(shell_pid)
term = Term()
terms.append(term)
stub = term.spawn([binary, '--tty', '--9p=own'], env)
started.append(stub.pid)
wait_for('the terminal\'s session', (root / 'pardes-9p-own.sock').exists)
own = Client(root / 'pardes-9p-own.sock')
own_pid = int(dict(line.split(maxsplit=1) for line in own.read('/status').decode().splitlines())['pid'])
started.append(own_pid)
wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text())
own_shell = terminals(own)[0]
own_shell_pid = pid_in(own, own_shell)
started.append(own_shell_pid)
expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("has a frontend")}',
f'shell {shell_pid}', f'shell {own_shell_pid}']
assert all(row in listed() for row in expected), listed()
daemon = daemons()[0]
idle = wakeups(session, 2) if procfs else 0
os.kill(daemon, signal.SIGKILL)
wait_for('the daemon gone', lambda: not alive(daemon))
# Nobody runs pardes again: the sessions start the next one.
again = wait_for('a daemon again', daemons)[0]
started.append(again)
wait_for('both sessions and their shells listed again', lambda: all(row in listed() for row in expected))
idle_after = wakeups(session, 2) if procfs else 0
assert idle <= 2 and idle_after <= 2, ('an idle session woke', idle, idle_after)
print(f'relink: daemon {daemon} killed, {again} started by its sessions, both listed again with their shells; '
f'the detached one idle before and after ({idle} and {idle_after} wakeups in 2 s)')
tc = Term(30, 100)
terms.append(tc)
c = tc.spawn([binary, 'attach', 'work'], env)
started.append(c.pid)
wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30)
wait_for('the client in --ps', lambda: f'client {c.pid} ' in listed())
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
os.kill(session, signal.SIGKILL)
wait_for('the killed session gone', lambda: not alive(session))
wait_for('its shell no session\'s', lambda: 'no session holds' in listed())
assert alive(shell_pid), 'the new daemon held its master'
before = set(terminals(own))
own.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop()
assert (pid := pid_in(own, pane)) == shell_pid, (pid, shell_pid)
print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted')
exit_session(own, pane)
stub.wait(timeout=10)
own.socket.close()
work.socket.close()
wait_for('the shells hung up', lambda: not alive(shell_pid) and not alive(own_shell_pid))
wait_for('the daemon gone once idle', lambda: not alive(again), timeout=5)
left = [p for p in processes(root) if alive(p)]
assert not left, [cmdline(p) for p in left]
print('relink: nothing left behind')
finally:
for t in terms:
try:
t.close()
except OSError:
pass
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
shutil.rmtree(root, ignore_errors=True)
def answer_late(binary):
"""A session's Adopt asked at once, while its daemon has not answered
its hello (stopped 3 s, as a loaded machine can keep it), and before
the session's reader of the daemon has run: answered when the daemon
answers, never refused on a clock (daemon.zig `kept`)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
started = []
terms = []
wake = None
try:
term = Term()
terms.append(term)
stub = term.spawn([binary, '--tty', '--9p=one'], env)
started.append(stub.pid)
wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
one = Client(root / 'pardes-9p-one.sock')
session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
started.append(session)
shell_pid = pid_in(one, terminals(one)[0])
started.append(shell_pid)
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
[binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
os.kill(session, signal.SIGKILL)
one.socket.close()
wait_for('the killed session gone', lambda: not alive(session))
os.kill(daemon, signal.SIGSTOP)
wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
wake.start()
term = Term()
terms.append(term)
stub = term.spawn([binary, '--tty', '--9p=two'], env)
started.append(stub.pid)
wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
two = Client(root / 'pardes-9p-two.sock', timeout=30)
started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
before = set(terminals(two))
asked = time.monotonic()
two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
took = time.monotonic() - asked
pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
assert (pid := pid_in(two, pane)) == shell_pid, (pid, shell_pid)
print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
f'and shell {shell_pid} was adopted')
exit_session(two, pane)
two.socket.close()
wait_for('the shells hung up', lambda: not alive(shell_pid))
wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
finally:
if wake:
wake.cancel()
for t in terms:
try:
t.close()
except OSError:
pass
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
shutil.rmtree(root, ignore_errors=True)
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
pipe's lone ESC would hold for the next key)."""
def __init__(self, root, name, argv, env):
(root / name).mkdir()
self.err = root / f'{name}.err'
self.p = subprocess.Popen(argv, env=dict(env, PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / name), SDL_VIDEO_DRIVER='offscreen'),
cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=open(self.err, 'w'), start_new_session=True)
self.pid = self.p.pid
def keys(self, text):
self.p.stdin.write(text.replace(b'\x1b', b'\x1b[27u'))
self.p.stdin.flush()
def mouse(self, kind, button, x, y):
"""A pointer event at window pixels (gui.zig's test feed)."""
self.p.stdin.write(f'\x1b]777;mouse;{kind};{button};{x};{y}\x07'.encode())
self.p.stdin.flush()
def said(self):
return self.err.read_text(errors='replace') if self.err.exists() else ''
def close(self):
if self.p.poll() is None:
self.p.stdin.close()
self.p.wait(timeout=15)
return self.p.returncode
def sessions_listed(binary, env, root):
"""`pardes --ps`'s session lines, each `[name, pid, (kind, state)]`."""
out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30)
assert out.returncode == 0, out
rows = [line.split(maxsplit=3)[1:] for line in out.stdout.decode().splitlines() if line.lstrip().startswith('session ')]
return [[name, pid, rest] for name, pid, rest in rows]
def pdf_window(binary, gui_binary):
"""A PDF in a terminal's detached session (the pdf addon its prefix
installs, `<prefix>/lib/pardes/addons/pdf.so`), a window client attached
and its wheel turned over the PDF: the session's page moves, the
window's digest is the session's, and the window, which runs the
addon's code itself (its state is plain: PA_PLAIN), draws its own
pages from the file. Skipped when the build has no pdf.so."""
lib = Path(binary).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so'
if not lib.exists():
print(f'daemon: no {lib}: the PDF window case skipped')
return
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
env.pop('XDG_DATA_HOME', None)
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
doc = root / 'design.pdf'
shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc)
notes = root / 'notes.txt'
notes.write_text('notes\n')
started = []
try:
sess = subprocess.Popen([binary, '--detach=pdf', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-pdf.sock').exists)
nine = Client(root / 'pardes-9p-pdf.sock')
assert any(row.startswith(b'pdf ') for row in nine.read('/addons').splitlines()), nine.read('/addons')
nine.write('/look', f'{doc}\n'.encode())
pdf = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'pdf')
for row in nine.read('/index').splitlines():
if row.split()[1] == b'text':
nine.write(f'/pane/{int(row.split()[0])}/ctl', b'Del\n')
def page():
# A kind's prefix is its last frame's: one drawn first.
nine.read('/screen')
tag = nine.read(f'/pane/{pdf}/tag')
return int(tag[1:tag.index(b'/')]) if tag.startswith(b'[') else 0
wait_for('the PDF at its first page', lambda: page() == 1)
check = root / 'w.check'
w = Window(root, 'w', [gui_binary, '--attach=' + str(sock) + ':pdf'], dict(env, PARDES_REPLICA_CHECK=str(check)))
started.append(w.pid)
wait_for('the window client agrees', lambda: agreed(check, 0), timeout=30)
for _ in range(60):
w.mouse('wheel', -3, 400, 400)
time.sleep(0.02)
wait_for('the session\'s PDF past its first page', lambda: page() > 1, timeout=30)
n = len(checks(check))
wait_for('the window client agrees after the wheel', lambda: agreed(check, n), timeout=30)
assert w.close() == 0, w.said()[-800:]
print(f'daemon: a PDF in a detached session, a window client\'s wheel over it: the session at page {page()}, '
f'the window\'s digest the session\'s {len(checks(check))} times')
exit_session(nine, pdf)
sess.wait(timeout=60)
nine.socket.close()
finally:
for pid in started:
try:
os.killpg(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
shutil.rmtree(root, ignore_errors=True)
def window_clients(binary, gui_binary):
"""Window replica clients (`pardes-gui --attach=<socket>:<name>`): of a
terminal's detached session, directly and through the delay relay at
30, 80 and 207 ms, beside a terminal's client, one put off the session's
state that joins again, one that detaches; and a window's session served
to a terminal's client and a window's. Each one's keys in the session's
text, every client's digest the session's once quiet; nothing left."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started = []
terms = []
windows = []
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
body = lambda: nine.read(f'/pane/{pane}/body')
# A terminal's client beside the windows, typing as they do.
ta = Term(30, 100)
terms.append(ta)
a = ta.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'a.check')))
started.append(a.pid)
wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in ta.text(), timeout=30)
agreements = []
for i, rtt in enumerate((0, 30, 80, 207)):
to = sock
relay = None
if rtt:
relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'),
str(root / f'relay{rtt}.sock'), str(sock), '--delay', str(rtt / 2)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
started.append(relay.pid)
wait_for('the relay', (root / f'relay{rtt}.sock').exists)
to = root / f'relay{rtt}.sock'
check = root / f'w{rtt}.check'
w = Window(root, f'w{rtt}', [gui_binary, f'--attach={to}:files'], dict(env, PARDES_REPLICA_CHECK=str(check)))
windows.append(w)
started.append(w.pid)
seen = len(checks(root / 'a.check'))
w.keys(b'jjjjjjj' * (i + 1) + f'Ofrom-window-{rtt}\x1b'.encode())
os.write(ta.master, b'jjjjOfrom-terminal-%d\x1b' % rtt)
wait_for(f'the window\'s and the terminal\'s keys ({rtt} ms)', lambda: f'from-window-{rtt}'.encode() in body()
and b'from-terminal-%d' % rtt in body(), timeout=30)
wait_for('the terminal client normal again', lambda: normal_again(ta), timeout=20)
wait_for(f'the window client agrees ({rtt} ms)', lambda: agreed(check, 0), timeout=30)
wait_for('the terminal client agrees', lambda: agreed(root / 'a.check', seen), timeout=30)
if not rtt:
# Its clients are no sessions of the daemon's.
listed = sessions_listed(binary, env, root)
assert [(n, k) for n, _, k in listed] == [('files', listed_as('detached'))], listed
# Moved and scrolled, its own view only: agreed again.
n = len(checks(check))
w.keys(b'jjjjjkkk\x06\x06\x02')
wait_for(f'the window client agrees again ({rtt} ms)', lambda: agreed(check, n), timeout=30)
if rtt in (0, 207):
# The pointer over the tags (the workspace's, the column's,
# the pane's: the top rows, a test window's cells about 16 by
# 33 pixels) and over the body, a click there: a window's
# hits are its own frame's, which the session never draws,
# so they are its input's, not re-made from a frame. Each
# tag motion made it join again (the user's, 2026-10-30).
n = len(checks(check))
for y in range(5, 170, 11):
for x in range(4, 1280, 23):
w.mouse('motion', 0, x, y)
for k in range(40):
w.mouse('motion', 0, 100 + 25 * k, 200 + 9 * k)
w.mouse('down', 1, 400, 300)
w.mouse('motion', 1, 600, 360)
w.mouse('up', 1, 600, 360)
wait_for(f'the window client agrees after its pointer ({rtt} ms)', lambda: agreed(check, n), timeout=30)
assert 'joined again' not in w.said(), w.said()[-800:]
agreements.append(len(checks(check)))
assert w.close() == 0, w.said()[-800:]
if relay:
relay.kill()
relay.wait()
# One put off the session's state (PARDES_TEST_DIVERGE): the next
# unit it replays finds it, it joins again, and its keys after go in.
# Far (PARDES_REPLICA_FAR, as through ssh): its first join sent its
# blobs by hash, in zstd; its rejoin finds them in the core it left.
dcheck = root / 'wd.check'
wd = Window(root, 'wd', [gui_binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(dcheck), PARDES_TEST_DIVERGE='1',
PARDES_REPLICA_FAR='1', PARDES_REPLICA_STATS=str(root / 'wd.stats'),
XDG_CACHE_HOME=str(root / 'wd-cache')))
windows.append(wd)
started.append(wd.pid)
time.sleep(2)
wd.keys(b'jj')
time.sleep(.5)
os.write(ta.master, b'jj')
wait_for('the window client diverged and joined again', lambda: 'joined again' in wd.said(), timeout=30)
assert wd.p.poll() is None
seen = len(checks(dcheck))
wd.keys(b'Oafter-rejoin-W\x1b')
wait_for('the window\'s keys after its rejoin', lambda: b'after-rejoin-W' in body(), timeout=30)
wait_for('the window client agrees after its rejoin', lambda: agreed(dcheck, seen), timeout=30)
# An Upgrade (to the same build): the session lets it go in words
# (`refused`), it dials again, joins, and its keys after go in.
nine.write('/ctl', b'Upgrade\n')
wait_for('the window client joined again after the upgrade', lambda: 'joined again: the session is upgrading' in wd.said(), timeout=60)
nine.socket.close()
nine = reconnect(root / 'pardes-9p-files.sock')
seen = len(checks(dcheck))
wd.keys(b'jjjOafter-upgrade-W\x1b')
wait_for('the window\'s keys after the upgrade', lambda: b'after-upgrade-W' in body(), timeout=30)
wait_for('the window client agrees after the upgrade', lambda: agreed(dcheck, seen), timeout=30)
assert wd.p.poll() is None
# Detach typed in it: it alone goes, and says so (exit 0).
wd.keys(b' sD')
wait_for('the window client let go', lambda: wd.p.poll() is not None, timeout=15)
assert wd.p.returncode == 0 and "detached from 'files', which is still running" in wd.said(), wd.said()[-500:]
# A link a line: the first join sent every blob, its rejoins held them.
links = joins(root / 'wd.stats')
assert len(links) == 3 and links[0]['blobs'] > 0 and links[0]['from_memory'] + links[0]['from_disk'] == 0, links
assert links[1]['from_memory'] == links[1]['blobs'] and links[1]['sent_kb'] == 0, links
os.write(ta.master, b' sD')
wait_for('the terminal client let go', lambda: a.poll() is not None, timeout=10)
print(f'daemon: window clients of a terminal\'s session at 0/30/80/207 ms beside a terminal\'s, digests agreed '
f'{agreements} and {len(checks(root / "a.check"))} times; one put off the session\'s state joined again, '
f'joined again across an Upgrade, agreed {len(checks(dcheck))} times and detached (far: its joins {joins(root / "wd.stats")})')
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
# A window's session (its daemon on, as a desktop's is), served to a
# terminal's client and a window's, the window typing as they do.
win = Window(root, 'win', [gui_binary, '--9p=win', str(notes)], dict(env, PARDES_DAEMON='on'))
windows.append(win)
started.append(win.pid)
wait_for('the window session\'s 9P socket', (root / 'pardes-9p-win.sock').exists, timeout=30)
wait_for('the replica socket', sock.exists)
nine = Client(root / 'pardes-9p-win.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
tb = Term(30, 100)
terms.append(tb)
b = tb.spawn([binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'b.check')))
started.append(b.pid)
wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tb.text(), timeout=30)
wg = Window(root, 'wg', [gui_binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_CHECK=str(root / 'g.check')))
windows.append(wg)
started.append(wg.pid)
time.sleep(2)
os.write(tb.master, b'jjjOfrom-T\x1b')
wg.keys(b'jjjjjjOfrom-G\x1b')
win.keys(b'jjjjjjjjjOfrom-W\x1b')
wait_for('everyone\'s keys in the window\'s session', lambda: all(x in body() for x in (b'from-T', b'from-G', b'from-W')), timeout=30)
wait_for('the terminal client normal again', lambda: normal_again(tb), timeout=20)
for k in range(3):
nb, ng = len(checks(root / 'b.check')), len(checks(root / 'g.check'))
os.write(tb.master, b'jk')
wg.keys(b'kj')
win.keys(b'jj')
wait_for('the terminal client agrees with the window', lambda: agreed(root / 'b.check', nb), timeout=30)
wait_for('the window client agrees with the window', lambda: agreed(root / 'g.check', ng), timeout=30)
listed = sessions_listed(binary, env, root)
assert [(n, k) for n, _, k in listed] == [('win', listed_as('has a frontend', 'gui'))], listed
assert wg.close() == 0, wg.said()[-800:]
os.write(tb.master, b' sD')
wait_for('the terminal client let go', lambda: b.poll() is not None, timeout=10)
assert win.p.poll() is None
print(f'daemon: a window\'s session served a terminal\'s client and a window\'s, digests agreed '
f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, {listed_as("has a frontend", "gui")}')
win.close()
nine.socket.close()
# Under the variable the window is its session's client, and the
# terminal client's Detach kept that session (P36): ended by name.
if WITH_PAIR:
subprocess.run([binary, '--kill=win'], env=dict(env, PARDES_DAEMON='on'), cwd=root, capture_output=True, timeout=30)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=15)
print('daemon: window clients\' sessions ended, nothing left behind')
finally:
for t in terms:
t.close()
for w in windows:
if w.p.poll() is None:
w.p.kill()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def client_motion(binary, gui_binary):
"""A run of pointer motions is one move to its last position (gui.zig
Input.moved), over a client window and over the session's own window
with a client attached: not an input each, which the session steps one
by one and sends every client as a unit each, every one of them
replayed and drawn again (the user's "resizing feels very slow with
several clients", 2026-11-24: a 1000 Hz mouse is a thousand inputs a
second). 300 motions written at once, 30 bytes each: the window takes
them a read of its test feed (1024 bytes) a pass, so at most ten
passes, each one input; with the five a client makes anyway (what it
is, its size, its focus, two keys) at most 15, asserted at most 20.
Three roads: the feed's own dispatch (`motion`) and SDL's queue
(`pointer`: the same motion pushed as a mouse's comes) over a window
client of a terminal's session, the inputs it sent the session (its
PARDES_REPLICA_STATS); and SDL's queue over a window's session with a
terminal client watching, a drag, the frames the window drew (its
status: on main each motion was its own wait, `split`, a frame each)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='cm-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started, terms, windows = [], [], []
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
tt = Term(24, 80)
terms.append(tt)
t = tt.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_STATS=str(root / 't.stats')))
started.append(t.pid)
wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tt.text(), timeout=30)
motions = 300
def burst(win, kind, button=0):
win.p.stdin.write(b''.join(f'\x1b]777;mouse;{kind};{button};{200 + 3 * i};{300 + i % 40}\x07'.encode() for i in range(motions)))
win.p.stdin.flush()
def said(path, word):
line = checks(path)[-1].split()
return int(line[line.index(word) + 1])
sent = {}
for kind in ('motion', 'pointer'):
stats = root / f'w-{kind}.stats'
w = Window(root, f'w-{kind}', [gui_binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_STATS=str(stats)))
windows.append(w)
started.append(w.pid)
w.keys(b'jj')
wait_for('the window\'s keys in the session', lambda: b'line' in nine.read(f'/pane/{pane}/body'), timeout=30)
time.sleep(2)
burst(w, kind)
time.sleep(3)
assert w.close() == 0, w.said()[-800:]
sent[kind] = said(stats, 'inputs')
t.send_signal(signal.SIGHUP)
t.wait(timeout=10)
tt_units = said(root / 't.stats', 'units') if checks(root / 't.stats') else None
print(f'daemon: {motions} motions over a client window: it sent the session {sent["motion"]} inputs by the feed, '
f'{sent["pointer"]} by SDL\'s queue; the terminal client took {tt_units} units')
for kind, n in sent.items():
assert n <= 20, (f'{motions} pointer motions ({kind}) over a client window were {n} inputs to its session, '
'each a unit for every client: not one a pass')
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
# The session's own window, a terminal client watching: SDL's queue.
win = Window(root, 'win', [gui_binary, '--9p=win', str(notes)], dict(env, PARDES_DAEMON='on'))
windows.append(win)
started.append(win.pid)
wait_for('the window session\'s 9P socket', (root / 'pardes-9p-win.sock').exists, timeout=30)
wait_for('the replica socket', sock.exists)
nine = Client(root / 'pardes-9p-win.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
tb = Term(24, 80)
terms.append(tb)
b = tb.spawn([binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_STATS=str(root / 'b.stats')))
started.append(b.pid)
wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tb.text(), timeout=30)
time.sleep(2)
def frames():
return int((root / 'win' / 'status').read_text().split()[1])
# A drag selecting: each motion moves what the window shows.
win.mouse('down', 1, 200, 300)
time.sleep(1)
before = frames()
burst(win, 'pointer', 1)
time.sleep(3)
drawn = frames() - before
win.mouse('up', 1, 1097, 339)
time.sleep(1)
b.send_signal(signal.SIGHUP)
b.wait(timeout=10)
print(f'daemon: {motions} motions of a drag over the session\'s own window, a terminal client watching: '
f'the window drew {drawn} frames; the client {said(root / "b.stats", "draws")} in all')
assert drawn <= 20, (f'{motions} pointer motions over the session\'s window were {drawn} frames of it with a client '
'attached: each motion its own wait (split), a step and a unit each, not one a pass')
exit_session(nine, pane)
assert win.close() == 0, win.said()[-800:]
nine.socket.close()
finally:
for tm in terms:
tm.close()
for w in windows:
if w.p.poll() is None:
w.p.kill()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def idle_session(binary, gui_binary, surface, pdf, secs):
"""One session (`surface`: a window's on the test surface; a window's
offscreen with no test mode, `loop`: the loop a real window runs, asleep
until an event or its deadline; or a terminal's with its own terminal),
a text and, with `pdf`, a PDF, one terminal client attached, nobody
typing for `secs`: the session's boundaries and the units the client
took over its whole life, and the CPU each spent in the idle seconds
(ticks of 10 ms)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ci-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(60)))
stats = root / 'session.stats'
started, terms, windows = [], [], []
try:
if surface == 'window':
win = Window(root, 'win', [gui_binary, '--9p=idle', str(notes)], dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats)))
windows.append(win)
started.append(win.pid)
elif surface == 'loop':
started.append(subprocess.Popen([gui_binary, '--9p=idle', str(notes)], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True,
env=dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats), SDL_VIDEO_DRIVER='offscreen')).pid)
else:
ts = Term(30, 100)
terms.append(ts)
started.append(ts.spawn([binary, '--tty', '--9p=idle', str(notes)], dict(env, PARDES_REPLICA_STATS=str(stats))).pid)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-idle.sock').exists, timeout=30)
nine = Client(root / 'pardes-9p-idle.sock')
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
started.append(session)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists, timeout=30)
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
if pdf:
doc = root / 'design.pdf'
shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc)
nine.write(f'/pane/{pane}/look', f'{doc}\n'.encode())
wait_for('the PDF shown', lambda: any(row.split()[1] == b'pdf' for row in nine.read('/index').splitlines()), timeout=30)
tc = Term(24, 80)
terms.append(tc)
c = tc.spawn([binary, f'--attach={sock}:idle'], dict(env, PARDES_REPLICA_STATS=str(root / 'c.stats')))
started.append(c.pid)
wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30)
# Its join and the frames after it over.
time.sleep(1.5)
cpu = (cpu_ticks(session), cpu_ticks(c.pid))
time.sleep(secs)
cpu = (cpu_ticks(session) - cpu[0], cpu_ticks(c.pid) - cpu[1])
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
line = checks(root / 'c.stats')[-1].split()
units = int(line[line.index('units') + 1])
exit_session(nine, pane)
wait_for('the session ended', lambda: not alive(session), timeout=60)
nine.socket.close()
return int(session_stats(stats)[0]['boundaries']), units, cpu
finally:
for t in terms:
t.close()
for w in windows:
if w.p.poll() is None:
w.p.kill()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def client_idle(binary, gui_binary, secs=5):
"""An idle session sends nothing (2026-11-24: a PDF in a window's session
with a client attached stepped the session ~700 times a second, nobody
typing, each step a unit every client replayed): a session showing a
text and a PDF, one terminal client, nobody typing for `secs`, takes at
most the steps the same session with the text alone takes, plus the
PDF's own opening (its page drawn, its views told: `opening`). On the
test surface the window's loop polls its feed every 16 ms, a step and a
unit each (the text alone's count is that rate); a window's own loop
(`loop`: offscreen, no test mode) and a terminal's session step for
nothing. The PDF's addon (`<prefix>/lib/pardes/addons/pdf.so`, `zig
build addons`) beside each binary."""
for b in (binary, gui_binary):
lib = Path(b).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so'
assert lib.exists(), f'no {lib}: the PDF is this test\'s subject (zig build install addons into that prefix)'
opening = 40
flooded = []
for surface in ('window', 'loop', 'tty'):
text = idle_session(binary, gui_binary, surface, False, secs)
shown = idle_session(binary, gui_binary, surface, True, secs)
print(f'daemon: a {surface}\'s session idle {secs} s, a terminal client attached: '
f'text alone {text[0]} boundaries, the client {text[1]} units, CPU {text[2][0] * 10}/{text[2][1] * 10} ms; '
f'with a PDF {shown[0]} boundaries, {shown[1]} units, CPU {shown[2][0] * 10}/{shown[2][1] * 10} ms (session/client)')
if shown[0] > text[0] + opening or shown[1] > text[1] + opening:
flooded.append(f'{surface}: {shown[0]} boundaries and {shown[1]} units against the text alone\'s {text[0]} and {text[1]}')
assert not flooded, (f'a session showing a PDF, a client attached, nobody typing for {secs} s, steps with nothing to do, '
f'a unit every client replays: {"; ".join(flooded)}')
def client_resize_real(binary, gui_binary):
"""A client window resized by a real compositor (driftwm's `msg resize`,
the configures a drag sends: 30 sizes in a second) while it shows a PDF:
no SDL assertion (on main every frame drawn larger than the target it
is drawn into placed the page's scissor past it: `SDL_SetGPUScissor`'s
release assertion, whose dialog blocks the window's thread: the window
frozen at its old size, cut, and nothing opened after shows in it), it
takes the last size, it posts a size a configure at most and is rolled
back as often at most (on main the session's own window sized the
client's view to its own size, the client posted its own again, on and
on: 425 to 1308 inputs, 228 rollbacks, its frames drawn at the session
window's size, cut). Real windows: the
caller's display and runtime directory reach the compositor; the
session's runtime directory is the test's own; skipped without driftwm."""
real_runtime = os.environ.get('XDG_RUNTIME_DIR', '')
wayland = os.environ.get('WAYLAND_DISPLAY') or 'wayland-1'
display = wayland if wayland.startswith('/') else os.path.join(real_runtime, wayland)
lib = Path(binary).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so'
if not shutil.which('driftwm') or not os.path.exists(display) or not lib.exists():
print('daemon: client resize on a real compositor: skipped (no driftwm, display or pdf.so)')
return
drift_env = dict(os.environ, XDG_RUNTIME_DIR=real_runtime, WAYLAND_DISPLAY=wayland)
def drift(*args):
out = subprocess.run(['driftwm', 'msg', '--json', *map(str, args)], env=drift_env, capture_output=True, text=True, timeout=10)
return json.loads(out.stdout) if out.stdout.strip() else {}
def window_of(pid):
state = drift('state')['Ok']['State']
return next((w for w in state['windows'] if w.get('pid') == pid), None)
def away(pid, x, y):
"""The window moved far from the desktop user's view, and kept
there: driftwm places a window again when it maps, after a move made
before (it came back beside the user's view, 2026-11-24)."""
wid = window_of(pid)['id']
still = 0
for _ in range(300):
if window_of(pid)['position'] != [x, y]:
drift('move', '--id', wid, x, y)
still = 0
else:
still += 1
if still == 40:
return wid
time.sleep(0.05)
raise AssertionError(('a test window would not stay away from the desktop user\'s view', window_of(pid)))
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='cr-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', SDL_AUDIODRIVER='dummy')
env.pop('XDG_DATA_HOME', None)
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
doc = root / 'design.pdf'
shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc)
started = []
try:
state = drift('state')['Ok']['State']
focused = next((w['id'] for w in state['windows'] if w.get('is_focused')), None)
# The session a window of its own, as a desktop's is, its daemon on;
# a terminal with output in it beside the PDF.
sess = subprocess.Popen([gui_binary, '--9p=files', str(notes), '--geometry=1120x760'],
env=dict(env, PARDES_DAEMON='on', WAYLAND_DISPLAY=display, SDL_VIDEO_DRIVER='wayland', SDL_ASSERT='ignore'),
cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=open(root / 's.err', 'w'),
start_new_session=True)
started.append(sess.pid)
wait_for('the session\'s window', lambda: (window_of(sess.pid) or {}).get('id'), timeout=30)
away(sess.pid, 59400, -18000)
if focused is not None:
drift('focus', '--id', focused)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists, timeout=30)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists, timeout=30)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
nine.write(f'/pane/{pane}/exec', b'Term\n')
shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines()
if row.split()[1] == b'term'), None))
wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body'))
nine.write(f'/pane/{shell}/pty/data', b'seq 1 400\r')
nine.write(f'/pane/{pane}/look', f'{doc}\n'.encode())
wait_for('the PDF pane', lambda: any(row.split()[1] == b'pdf' for row in nine.read('/index').splitlines()))
err = root / 'w.err'
stats = root / 'w.stats'
# SDL's assertion counted on stderr, never its dialog on the desktop.
w = subprocess.Popen([gui_binary, f'--attach={sock}:files', '--geometry=900x600'],
env=dict(env, WAYLAND_DISPLAY=display, SDL_VIDEO_DRIVER='wayland', SDL_ASSERT='ignore',
PARDES_REPLICA_STATS=str(stats), SDL_EVENT_LOGGING='2'),
cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=open(err, 'w'), start_new_session=True)
started.append(w.pid)
wait_for('the client\'s window', lambda: (window_of(w.pid) or {}).get('id'), timeout=30)
# Far from where the desktop's user looks, the focus given back.
wid = away(w.pid, 62000, -18000)
if focused is not None:
drift('focus', '--id', focused)
time.sleep(3)
steps = 30
t0 = time.monotonic()
for i in range(steps):
time.sleep(max(0, t0 + i / 30 - time.monotonic()))
last = (900 + 9 * (i + 1), 600 + 5 * (i + 1))
drift('resize', '--id', wid, *last)
time.sleep(3)
size = window_of(w.pid)['size']
said = err.read_text(errors='replace')
w.send_signal(signal.SIGTERM)
w.wait(timeout=15)
line = checks(stats)[-1].split() if checks(stats) else []
sent = int(line[line.index('inputs') + 1]) if 'inputs' in line else -1
# SDL's default handler's words, and pardes's own (gui.zig sdlAssertion).
asserted = said.count('Assertion failure') + said.count('SDL assertion: ')
# A pointer that crossed the window (one sliding under it as it was
# moved away) is motion's, --client-motion's: not counted here.
motions = said.count('SDL_EVENT_MOUSE_MOTION')
sent -= motions
# Its own inputs rolled back by the session's units between them.
rollbacks = int(line[line.index('foreign') + 1]) if 'foreign' in line else -1
print(f'daemon: a client window resized {steps} times in a second by the compositor: {asserted} SDL assertions, '
f'its size {size} (asked {list(last)}), {sent} inputs besides {motions} pointer motions, {rollbacks} rollbacks')
assert asserted == 0, ('a client window drew past its target while resized', said[-600:])
assert abs(size[0] - last[0]) <= 2 and abs(size[1] - last[1]) <= 40, ('the client window did not take the last size', size, last)
# A size a configure at most (the window's own, compared with what it
# posted last: none after the last).
assert sent <= steps, ('a client window resized posted its size again and again', sent)
assert 0 <= rollbacks <= steps + motions, ('a client window resized was rolled back again and again', rollbacks)
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
finally:
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def joins(path):
"""A replica client's joins (PARDES_REPLICA_STATS, a line a link): how
many blobs each listed, how many it held already from the core it left
and from disk, and the KB it was sent."""
out = []
for line in checks(path):
words = line.split()
if 'blobs' not in words:
continue
got = {words[i]: int(words[i + 1]) for i in range(0, len(words) - 1, 2) if words[i + 1].isdigit()}
out.append(got)
return out
def cache_file(cache):
"""The blob cache (a far client's, XDG_CACHE_HOME/pardes/cache.xitdb)."""
return cache / 'pardes' / 'cache.xitdb'
def cached(cache):
"""The blob cache's size in bytes, 0 with none."""
f = cache_file(cache)
return f.stat().st_size if f.exists() else 0
def far(binary):
"""Far replica clients (PARDES_REPLICA_FAR, as through ssh) of a
detached session and their blob cache: the first one is sent every
blob and keeps them; a second on the same machine, and one put off the
session's state that joins again, are sent none they hold, from disk
and from the core they leave; one started after the first ended gets
what it made from disk; one after the cache was cut short by hand (a
file that is no database: started afresh), and one with the cache full,
are sent what they lack. Every client's digest is the session's once
quiet."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch))
cache = root / 'cache'
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
big = root / 'big.txt'
big.write_text(''.join(f'{i:06d} the quick brown fox jumps over the lazy dog {i * 7919 % 10007}\n' for i in range(20000)))
started = []
terms = []
def client(name, extra=None):
t = Term(24, 90)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'],
dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'),
PARDES_REPLICA_STATS=str(root / f'{name}.stats'), **(extra or {})))
started.append(c.pid)
wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
# Its frame's request answered before a key goes: an answer behind
# an Esc, in one read, is taken as Alt with it.
time.sleep(.3)
return t, c
def texts():
return b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
if row.split()[1] == b'text')
def typed(name, t, words):
seen = len(checks(root / f'{name}.check'))
os.write(t.master, b'O' + words)
wait_for(f'client {name}\'s keys in the session\'s text', lambda: words in texts())
time.sleep(.2)
os.write(t.master, b'\x1b')
wait_for(f'client {name} out of insert mode', lambda: normal_again(t))
wait_for(f'client {name} agrees once quiet', lambda: agreed(root / f'{name}.check', seen))
def detach(name, t, c):
os.write(t.master, b' sD')
wait_for(f'client {name} let go', lambda: c.poll() is not None, timeout=20)
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
nine.write(f'/pane/{pane}/exec', f'Look {big}\n'.encode())
nine.write(f'/pane/{pane}/exec', b'Edit 3a/ an edit the session made /\n')
# A: the first, its cache empty: every blob sent, and kept.
ta, a = client('a')
typed('a', ta, b'from-A')
# The notes and the big file, a megabyte and more between them.
wait_for('client A\'s blobs on disk', lambda: cached(cache) > 1 << 20)
time.sleep(.5)
# B: a second client on this machine, and put off the session's
# state once quiet: its first join from disk, its rejoin from the
# core it left.
tb, b = client('b', {'PARDES_TEST_DIVERGE': '1'})
os.write(tb.master, b'jj')
time.sleep(.5)
os.write(ta.master, b'jj')
wait_for('client B diverged and joined again', lambda: b'joined again' in tb.text(), timeout=30)
typed('b', tb, b'from-B')
typed('a', ta, b'again-A')
detach('b', tb, b)
detach('a', ta, a)
a_joins, b_joins = joins(root / 'a.stats'), joins(root / 'b.stats')
assert len(a_joins) == 1 and len(b_joins) == 2, (a_joins, b_joins)
assert a_joins[0]['from_disk'] == 0 and a_joins[0]['from_memory'] == 0 and a_joins[0]['sent_kb'] > 100, a_joins
assert b_joins[0]['from_disk'] >= b_joins[0]['blobs'] - 2 and b_joins[0]['sent_kb'] < a_joins[0]['sent_kb'], b_joins
assert b_joins[1]['from_memory'] >= b_joins[1]['blobs'] - 1 and b_joins[1]['sent_kb'] < 64, b_joins
# C: a client started again after them: what they made since they
# joined is on disk too (Have.keep at their end).
tc, c = client('c')
typed('c', tc, b'from-C')
detach('c', tc, c)
c_join = joins(root / 'c.stats')[0]
assert c_join['from_disk'] >= c_join['blobs'] - 1 and c_join['sent_kb'] < 64, c_join
# D: the cache cut short by hand: no database, started afresh, every
# blob sent again.
whole = cache_file(cache).read_bytes()
cache_file(cache).write_bytes(whole[:len(whole) // 2])
td, d = client('d')
typed('d', td, b'from-D')
detach('d', td, d)
d_join = joins(root / 'd.stats')[0]
assert d_join['from_disk'] == 0 and d_join['sent_kb'] > 100, d_join
# E: the cache full (D's, past a 1 MiB cap): the oldest go at its end,
# the file compacted, under its cap but for xitdb's own few KB.
before_e = cached(cache)
assert before_e > 1 << 20, before_e
te, e = client('e', {'PARDES_BLOB_CACHE_MB': '1'})
typed('e', te, b'from-E')
detach('e', te, e)
assert cached(cache) <= (1 << 20) + (64 << 10), cached(cache)
tf, f = client('f', {'PARDES_BLOB_CACHE_MB': '1'})
typed('f', tf, b'from-F')
detach('f', tf, f)
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
# Through ssh (a stand-in forwarding as `ssh -L` does, its socket
# bound 0.5 s before it listens: the client dials until it answers):
# a client refused and one detached each end their ssh and its
# socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
def forwarded():
return [q for q in processes(root) if alive(q) and any(b'pardes-ssh-' in a for a in cmdline(q))] or list(root.glob('pardes-ssh-*'))
for name in ('nobody', 'files'):
ts = Term(24, 90)
terms.append(ts)
sc = ts.spawn([binary, f'--attach=box:{name}'], senv)
started.append(sc.pid)
if name == 'files':
wait_for('the client through ssh\'s first frame', lambda: b'line 3 of the notes' in ts.text(), timeout=30)
time.sleep(.3)
os.write(ts.master, b' sD')
wait_for(f'the client through ssh ends ({name})', lambda: sc.poll() is not None, timeout=30)
# Its words are read off its terminal by a thread of the Term's:
# the process can be gone before they are in `text()`.
if name == 'nobody':
wait_for('the refusal said through ssh', lambda: b"no session called 'nobody'" in ts.text(), timeout=5)
wait_for(f'its ssh and socket gone ({name})', lambda: not forwarded(), timeout=10)
body = texts()
for words in (b'from-A', b'from-B', b'again-A', b'from-C', b'from-D', b'from-E', b'from-F'):
assert words in body, words
print('daemon: far clients: the first sent {} KB; a second from disk ({} of {} blobs), its rejoin from memory '
'({} of {}); one started again from disk ({} of {}); after the cache was spoilt by hand sent {} KB; with '
'the cache full it stayed under its cap; every digest agreed ({} checks)'.format(
a_joins[0]['sent_kb'], b_joins[0]['from_disk'], b_joins[0]['blobs'], b_joins[1]['from_memory'],
b_joins[1]['blobs'], c_join['from_disk'], c_join['blobs'], d_join['sent_kb'],
sum(len(checks(root / f'{n}.check')) for n in 'abcdef')))
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
finally:
for t in terms:
t.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def far_flood(binary):
"""A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py:
200 ms each way, 20 KB/s) while the session's shell runs `yes`. Its
terminal is the pty's bytes in the session's units, so the flood queues
for it: it falls behind, past replica.behind_max_ms its link is let go
(`Link.lags`), and it joins again from a dump, saying so on its notice
line ("joined again: N s behind") until a key. Once `yes` ends it agrees
with the session, and its keys after go in. The shape is asserted, not
the times: a link ended before its last (a line of
PARDES_REPLICA_STATS a link), the notice, the agreement."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started = []
terms = []
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')),
cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
nine.write(f'/pane/{pane}/exec', b'Term\n')
shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines()
if row.split()[1] == b'term'), None))
wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body'))
relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'),
str(root / 'relay.sock'), str(sock), '--delay', '200', '--rate', '0.02'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
started.append(relay.pid)
wait_for('the relay', (root / 'relay.sock').exists)
check = root / 'f.check'
stats = root / 'f.stats'
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'],
dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats)))
started.append(c.pid)
wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60)
links = sockets(c.pid)
nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r')
wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60)
ended_at = time.monotonic()
seen = len(checks(check))
wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120)
# Queued behind the flood, let go for its lag, joined again from a
# dump: a link of its ended (its stats line), and its notice says why.
assert joins(stats), ('no link of the far client ended under the flood', checks(stats))
# Fallen behind, a far client dials again (core/replica.zig
# `Link.backHere`: the second road until bounded flight): a new
# connection, not what the old one holds for it read through; each
# join's time and the KB it was sent; the flood's end to its agreement.
same = sockets(c.pid) == links
print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again '
f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); '
f'agreed {time.monotonic() - ended_at:.1f} s after yes ended')
assert not same, ('the far client behind dialled again: another connection', links, sockets(c.pid))
wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30)
os.write(t.master, b'echo from-far\r')
wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30)
seen = len(checks(check))
wait_for('the far client agrees after its keys', lambda: agreed(check, seen), timeout=60)
# Its keys go to the shell: its terminal hangs up instead.
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` was let go for its lag and '
f'joined again ({len(joins(stats))} links), agreed once it ended ({len(checks(check))} checks) and its keys went in')
relay.kill()
relay.wait()
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
except BaseException:
# Its evidence kept, the root going: the far client's checks and
# stats, its terminal, and where each process's threads wait.
kept = Path(tempfile.mkdtemp(prefix='fl-kept-', dir=scratch))
for f in ('f.check', 'f.stats'):
if (root / f).exists():
shutil.copy(root / f, kept)
for i, term in enumerate(terms):
(kept / f'term-{i}.out').write_bytes(term.text())
with open(kept / 'threads', 'w') as out:
for pid in started:
out.write(f'{pid} {cmdline(pid)[:3]} alive={alive(pid)}\n')
for task in sorted(Path(f'/proc/{pid}/task').glob('*')) if procfs and alive(pid) else []:
try:
out.write(f' {task.name} {(task / "comm").read_text().strip()} {(task / "wchan").read_text()}\n')
except OSError:
pass
print(f'far flood: kept {kept}', file=sys.stderr)
raise
finally:
for term in terms:
term.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def by_hash(binary):
"""A file over the wire's 16 MiB bound opened while clients are
attached (its read was one unit, dropped: the client joined again, a
Debug session panicked): it goes by its hash, a client on this machine
reading it itself and a far one sent it once, kept on disk; a far client
that joins after is sent nothing of it."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch))
cache = root / 'cache'
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
big = root / 'big.txt'
with open(big, 'wb') as f:
for i in range(17 << 14):
f.write(b'%08d %s\n' % (i, os.urandom(27).hex().encode()[:54]))
started, terms = [], []
def client(name, far):
t = Term(24, 90)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'],
dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats'),
**({'PARDES_REPLICA_FAR': '1'} if far else {})))
started.append(c.pid)
wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
time.sleep(.3)
return t, c
def read(pid):
return next(int(line.split()[1]) for line in open(f'/proc/{pid}/io') if line.startswith('rchar'))
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
# Each reply waited for as long as the opens it answers take: the
# 17 MiB file's Look took 1.6-6.6 s in a Debug build at a load of
# 35 (ninep.py's 5 s is a reply's whole wait).
nine = Client(root / 'pardes-9p-files.sock', timeout=60)
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
(ta, a), (tf, f) = client('a', False), client('f', True)
seen = {n: len(checks(root / f'{n}.check')) for n in 'af'}
was = {c.pid: read(c.pid) for c in (a, f)}
nine.write(f'/pane/{pane}/exec', f'Look {big}\n'.encode())
for n in 'af':
wait_for(f'client {n} agrees with the big file open', lambda: agreed(root / f'{n}.check', seen[n] + 1), timeout=60)
assert sess.poll() is None and a.poll() is None and f.poll() is None
assert not any(b'joined again' in t.text() for t in (ta, tf))
size = big.stat().st_size
# This machine's read it from disk; the far one was sent it, zstd.
got = {c.pid: read(c.pid) - was[c.pid] for c in (a, f)}
assert size <= got[a.pid] < size + (512 << 10), (size, got)
assert got[f.pid] < size, (size, got)
tg, g = client('g', True)
os.write(tg.master, b' sD')
wait_for('client G let go', lambda: g.poll() is not None, timeout=20)
g_join = joins(root / 'g.stats')[0]
assert g_join['from_disk'] == g_join['blobs'] and g_join['sent_kb'] == 0, g_join
print(f'daemon: a {size >> 20} MiB file opened under two clients went by its hash: the one on this machine read '
f'it itself, the far one was sent {got[f.pid] >> 10} KB and kept it; a far client that joined after was '
f'sent none of its {g_join["blobs"]} blobs')
for t, c in ((ta, a), (tf, f)):
os.write(t.master, b' sD')
wait_for('a client let go', lambda: c.poll() is not None, timeout=20)
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
finally:
for t in terms:
t.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def games(binary, libs, secs=10):
"""The games (PA_PLAIN kinds: snake, life) run in the clients that show
them, from `libs` (zig build addon-test's <prefix>/lib): a client's keys
into one apply at once (none stopped), the snake steps under a client's
focus, and snake and life focused in two clients while a third types
text agree with the session throughout, rollbacks and all. Then a kind
that breaks its promise (test/liar.zig, its tick reads the clock): its
client finds it, joins again once, says why, and agrees from then on."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'data' / 'pardes' / 'addons').mkdir(parents=True)
for name in ('snake', 'life', 'liar'):
shutil.copy(Path(libs) / f'lib{name}.so', root / 'data' / 'pardes' / 'addons' / f'{name}.so')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started, terms = [], []
def client(name):
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'],
dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats')))
started.append(c.pid)
# Its frame: the notes, or what the third client typed into them.
wait_for(f'client {name}\'s first frame', lambda: b'of the notes' in t.text() or b'typed by c' in t.text(), timeout=30)
time.sleep(.3)
return t, c
def kind_pane(word):
return next((int(r.split()[0]) for r in nine.read('/index').splitlines() if r.split()[1] == word), None)
def steps(pane):
return int(re.search(rb'steps (\d+)', nine.read(f'/pane/{pane}/body')).group(1))
def opened(t, word):
# In this client's view: its key the last input, the session's
# live view is its own when the word runs.
os.write(t.master, b'j')
time.sleep(.5)
nine.write(f'/pane/{text}/exec', word.capitalize() + b'\n')
return wait_for(f'a {word} pane', lambda: kind_pane(word))
def leave(name, t, c):
c.send_signal(signal.SIGHUP)
c.wait(timeout=20)
line = (root / f'{name}.stats').read_text().split()
got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
assert not [l for l in checks(root / f'{name}.check') if l.startswith('differ')], name
return got
try:
sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
nine = Client(root / 'pardes-9p-files.sock')
text = kind_pane(b'text')
(tc, c), (ta, a) = client('c'), client('a')
snake = opened(ta, b'snake')
tb, b = client('b')
life = opened(tb, b'life')
os.write(ta.master, b'r')
time.sleep(.3)
s0 = steps(snake)
time.sleep(.6)
assert steps(snake) > s0, 'the snake steps under a client\'s focus'
rnd = random.Random(7)
end, n = time.monotonic() + secs, 0
while time.monotonic() < end:
os.write(ta.master, bytes([rnd.choice(b'hjkl')]) if n % 40 else b'r')
os.write(tb.master, bytes([rnd.choice(b'hjkl ')]))
os.write(tc.master, b'Atyped by c %d\x1b' % n)
n += 1
time.sleep(rnd.uniform(.02, .12))
for name in 'abc':
wait_for(f'client {name} agrees once quiet', lambda: agreed(root / f'{name}.check', 0), timeout=30)
assert not any(b'joined again' in t.text() for t in (ta, tb, tc))
got = {name: leave(name, t, cl) for name, t, cl in (('a', ta, a), ('b', tb, b), ('c', tc, c))}
for name in 'ab':
assert got[name]['stopped'] == '0' and got[name]['mispredicted'] == '0', (name, got[name])
# The liar: caught at a tick, its client joined again once, and agrees.
td, d = client('d')
opened(td, b'liar')
wait_for('client D caught the liar', lambda: b'joined again' in td.text(), timeout=30)
assert b'liar: its state after tick' in td.text(), td.text()[-600:]
seen = len(checks(root / 'd.check'))
os.write(td.master, b'j')
wait_for('client D agrees after it', lambda: agreed(root / 'd.check', seen), timeout=30)
assert td.text().count(b'joined again') == 1 and d.poll() is None
print(f'daemon: games in clients, {secs:.0f} s: snake and life focused in two clients, keys stopped {got["a"]["stopped"]} and '
f'{got["b"]["stopped"]} of {got["a"]["inputs"]} and {got["b"]["inputs"]}, rollbacks {got["a"]["foreign"]}, {got["b"]["foreign"]}, '
f'{got["c"]["foreign"]} (the third typing text), every digest agreed; a kind whose tick reads the clock was caught and its '
f'client joined again once')
exit_session(nine, text)
sess.wait(timeout=60)
nine.socket.close()
finally:
for t in terms:
t.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def far_find(binary):
"""A far client types a query into a Find over 40,000 names: each key
scores the names again a slice at a time (core/Names.zig `rescore`),
the client's guess of the key first. The slice is a count, the same on
both sides, so no guess is wrong (a slice the clock ended was the
client's clock's verdict, which the session's own contradicted)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
tree = root / 'tree'
for d in range(200):
(tree / f'module_{d}').mkdir(parents=True)
for f in range(200):
(tree / f'module_{d}' / f'replica_{f}.zig').touch()
notes = tree / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started, terms = [], []
try:
sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists)
nine = Client(root / 'pardes-9p-find.sock')
text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'],
dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats')))
started.append(c.pid)
wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
time.sleep(.3)
# SPC f f: the Find, typed into, its names walked on the session's worker.
os.write(t.master, b' ff')
time.sleep(3)
wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60)
query = b'module_19/replica_3'
for ch in query:
os.write(t.master, bytes([ch]))
time.sleep(.15)
seen = len(checks(root / 'q.check'))
wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60)
c.send_signal(signal.SIGHUP)
c.wait(timeout=20)
line = (root / 'q.stats').read_text().split()
got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs '
f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once')
assert got['mispredicted'] == '0', got
exit_session(nine, text)
sess.wait(timeout=60)
nine.socket.close()
finally:
for term in terms:
term.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def restore_client(binary):
"""A Restore while a client is attached: the client is told and joins
the restored session again by itself (P44, as at an Upgrade), saying
nothing on its screen; its keys reach the replacement core (the
session's: its tape adopts it, its options keep none) and it agrees with
it, as does a client attached after. A 9P connection is the old core's:
cut, dialled again."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
started, terms = [], []
try:
sess = subprocess.Popen([binary, '--detach=back', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-back.sock').exists)
nine = Client(root / 'pardes-9p-back.sock')
text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
def client(name):
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'],
dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check')))
started.append(c.pid)
wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
time.sleep(.3)
return t, c
ta, ca = client('a')
nine.write(f'/pane/{text}/exec', b'Dump\n')
nine.write(f'/pane/{text}/exec', b'Restore\n')
def cut():
try:
nine.read('/index')
return False
except (OSError, EOFError):
return True
wait_for('the 9P connection cut at the Restore', cut, timeout=30)
nine.socket.close()
nine = reconnect(root / 'pardes-9p-back.sock')
text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
if row.split()[1] == b'text')
# Client a, joined again by itself: its keys in the restored core.
os.write(ta.master, b'Oa after the restore\x1b')
wait_for('client a\'s keys in the restored session', lambda: b'a after the restore' in texts(), timeout=30)
assert ca.poll() is None, 'client a ended at the Restore'
seen = len(checks(root / 'a.check'))
wait_for('client a agrees once quiet', lambda: agreed(root / 'a.check', seen), timeout=60)
assert b'joined again' not in ta.text(), ('a notice left on client a\'s screen', ta.text())
tr, cr = client('r')
os.write(tr.master, b'Or after the restore\x1b')
wait_for('client r\'s keys in the restored session', lambda: b'r after the restore' in texts(), timeout=30)
seen = len(checks(root / 'r.check'))
wait_for('client r agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
assert ca.poll() is None and cr.poll() is None, 'a client ended'
print(f'daemon: a Restore with a client attached: it joined again by itself, saying nothing, its keys in the restored session and agreeing ({len(checks(root / "a.check"))} checks); the 9P connection cut; one attached after agreed ({len(checks(root / "r.check"))} checks)')
exit_session(nine, text)
sess.wait(timeout=60)
nine.socket.close()
finally:
for term in terms:
term.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def far_joins(sock, session, binary, n):
"""`n` far joins of one session in a row, each read whole (its blobs
asked for by none, its zstd frames unpacked) and answering a ping, then
gone: the session's fds and threads as they were, its RSS within a
bound. Each join made zstd contexts through the C heap, whose release
builds named a new allocator at every malloc and aborted at the 65th
(the box's session, after 15 far joins, 2026-10-30)."""
from compression import zstd
build = semantics(binary)
def join():
r = Replica(sock, timeout=30)
name = session.encode()
r.send(0x01, struct.pack('<HQH', Replica.WIRE, build, len(name)) + name + b'\xff')
r.send(0x06, b'\x01')
tag, body = r.read()
assert tag == 0x01, (tag, body)
pid, k = struct.unpack_from('<IH', body)
blobs, = struct.unpack_from('<I', body, len(body) - 4)
if blobs:
r.send(0x07, bytes((blobs + 7) // 8))
r.send(0x03, struct.pack('<Q', 7))
d, inner = zstd.ZstdDecompressor(), b''
while True:
tag, body = r.read()
assert tag == 0x09, tag
inner += d.decompress(body)
while d.eof:
rest, d = d.unused_data, zstd.ZstdDecompressor()
inner += d.decompress(rest) if rest else b''
while len(inner) >= 5:
t, m = struct.unpack_from('<BI', inner)
if len(inner) < 5 + m:
break
payload, inner = inner[5:5 + m], inner[5 + m:]
if t == 0x03:
assert payload == struct.pack('<Q', 7), payload
r.send(0x02, b'')
r.close()
return pid
def threads(pid):
return len(os.listdir(f'/proc/{pid}/task')) if procfs else int(ps('-o', 'nlwp=', '-p', str(pid)))
def rss_kb(pid):
if procfs:
return next(int(line.split()[1]) for line in open(f'/proc/{pid}/status') if line.startswith('VmRSS:'))
return int(ps('-o', 'rss=', '-p', str(pid)))
pid = join()
time.sleep(.5)
before = fds(pid), threads(pid), rss_kb(pid)
t = time.monotonic()
for _ in range(n):
assert join() == pid
wait_for('the far joins\' fds and threads let go', lambda: (fds(pid), threads(pid)) == before[:2], timeout=10)
grown = rss_kb(pid) - before[2]
assert grown < 64 << 10, (before, grown)
print(f'daemon: {n} far joins of one session in {time.monotonic() - t:.1f} s: its fds and threads as they were '
f'({before[0]}, {before[1]}), its RSS {grown:+d} KB')
def terminals(client):
return [int(row.split()[0]) for row in client.read('/index').splitlines() if row.split()[1] == b'term']
def cpu_ticks(pid):
stat = open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()
return int(stat[11]) + int(stat[12])
def killed_session(binary):
"""A terminal's session killed outright (KILL, as the OOM killer does):
the job its terminal waits on ends with it, and says nothing of its own
(no trace): the own path's stub dead of the same signal, as a job is
(daemon.zig `stubWait`, which aborted re-raising a KILL); a pair's
client let go of its session, 1."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
t = Term(30, 100)
try:
c = t.spawn([binary, '--9p=k', str(notes)], env)
sock = root / 'pardes-9p-k.sock'
wait_for('the socket', sock.exists)
with Client(sock) as nine:
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
os.kill(session, signal.SIGKILL)
code = c.wait(timeout=30)
said = t.last()
assert b'panic' not in said and b'unreachable' not in said, said[-1500:]
assert code == (1 if WITH_PAIR else -signal.SIGKILL), (code, said[-600:])
print(f'killed session: its terminal\'s job ended {code} with it, no trace')
finally:
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
t.close()
shutil.rmtree(root, ignore_errors=True)
def kitty_image(binary, secs=5):
"""A plain attach watching a terminal in which a program
shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it
agrees with its session and does not join again (it joined again ~3.3
times a second: the tag said ` petscii:on` on the session's side only)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ri-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
rgb = bytes((x * 30) % 256 for x in range(8 * 8 * 3))
(root / 'kitty.sh').write_text("printf '\\033_Ga=T,f=24,s=8,v=8,c=10,r=4;%s\\033\\\\'\nprintf '\\nKITTY\\n'\n"
% __import__('base64').b64encode(rgb).decode())
started, terms = [], []
try:
term = Term()
terms.append(term)
stub = term.spawn([binary, '--tty', '--9p=img'], env)
started.append(stub.pid)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-img.sock').exists)
nine = Client(root / 'pardes-9p-img.sock')
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
started.append(session)
shell = terminals(nine)[0]
nine.write(f'/pane/{shell}/exec', b'Detach\n')
assert stub.wait(timeout=10) == 0, stub.returncode
t = Term(30, 100)
terms.append(t)
c = t.spawn([binary, 'attach', 'img'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check')))
started.append(c.pid)
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
wait_for('the client agrees', lambda: agreed(root / 'c.check', 0), timeout=30)
nine.write(f'/pane/{shell}/pty/data', f'clear; sh {root}/kitty.sh\r'.encode())
wait_for('KITTY in the session\'s body', lambda: b'KITTY' in nine.read(f'/pane/{shell}/body'), timeout=30)
wait_for('KITTY in the client\'s terminal', lambda: b'KITTY' in t.text(), timeout=30)
mark, seen = len(t.text()), len(checks(root / 'c.check'))
cpu = (cpu_ticks(session), cpu_ticks(c.pid))
time.sleep(secs)
cpu = [(cpu_ticks(p) - was) * 1000 // os.sysconf('SC_CLK_TCK') for p, was in zip((session, c.pid), cpu)]
again = t.text()[mark:].count(b'joined again')
said = checks(root / 'c.check')[seen:]
tag = nine.read(f'/pane/{shell}/tag')
print(f'kitty image: over {secs} s the client joined again {again} times ({again / secs:.1f}/s), its checks '
f'{len(said)} ({sum(s.startswith("differ") for s in said)} differ), CPU ms session {cpu[0]} client {cpu[1]}, '
f'{len(t.text()) - mark} bytes to its terminal; the session\'s tag {tag[:60]!r}')
assert again == 0 and c.poll() is None, (again, said[-3:])
assert agreed(root / 'c.check', seen), said
exit_session(nine, shell)
nine.socket.close()
wait_for('the client ended with its session', lambda: c.poll() is not None, timeout=20)
print('kitty image: a plain client watching a kitty image agreed and never joined again')
finally:
for t in terms:
t.close()
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def main(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
daemon_sock = root / 'pardes-daemon.sock'
started = []
try:
term = Term()
stub = term.spawn([binary, '--tty', '--9p=work'], env)
started.append(stub.pid)
sock = root / 'pardes-9p-work.sock'
wait_for('the session\'s 9P socket', sock.exists)
client = Client(sock)
status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())
session = int(status['pid'])
started.append(session)
assert session != stub.pid, 'the session is forked off its stub'
assert daemon_sock.exists(), list(root.iterdir())
daemons = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']]
assert len(daemons) == 1, [cmdline(p) for p in processes(root)]
daemon = daemons[0]
started.append(daemon)
replicas(root, binary, session, daemon)
clients(binary)
far(binary)
by_hash(binary)
launch(binary)
pair(binary)
pair_rows(binary)
pair_back(binary)
attach_upgrading(binary)
kept_views(binary)
pair_upgrade_views(binary)
manage(binary)
relink(binary)
answer_late(binary)
kitty_image(binary)
shell = terminals(client)[0]
shell_pid = pid_in(client, shell)
started.append(shell_pid)
# Detach in the terminal it was born with: the stub ends (exit 0,
# its words), the terminal put back; the session runs on detached,
# for good: every attach after it is a client.
client.write(f'/pane/{shell}/exec', b'Detach\n')
assert stub.wait(timeout=10) == 0, stub.returncode
# The stub's last words are in its terminal before it ends, but
# this side's reader may not have them yet.
wait_for('the stub says it detached', lambda: b'detached from \'work\', which is still running; come back with `pardes attach work`' in term.text())
assert b'\x1b[?1049l' in term.text(), 'the terminal is put back'
term.close()
assert alive(session) and alive(shell_pid)
assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached'
def attach(term, argv, typed):
"""A client: its own process, drawn, listed by --ps under the
session, detached still, and its keys in the shell."""
c = term.spawn(argv, env)
started.append(c.pid)
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {c.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
assert f'session work {session} {listed_as("detached")}' in listed, listed
os.write(term.master, f'echo {typed}\r'.encode())
wait_for('its keys in the shell', lambda: typed.encode() in client.read(f'/pane/{shell}/body'))
return c
def let_go(how, c, term):
"""Detach in it (its view the live one: it typed last), or its
terminal closed: it ends; the session and its shell run on."""
if how == 'detach':
client.write(f'/pane/{shell}/exec', b'Detach\n')
assert c.wait(timeout=10) == 0, c.returncode
wait_for('the client says it detached', lambda: b"detached from 'work', which is still running" in term.text())
else:
term.close()
c.wait(timeout=10)
if how == 'detach':
term.close()
assert alive(session) and alive(shell_pid)
baseline = None
for cycle in range(cycles):
term = Term(30, 100)
c = attach(term, [binary, '--attach=work'] if cycle % 2 else [binary, 'attach'], f'cycle-{cycle}')
now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root)))
if baseline is None:
baseline = now
assert now == baseline, (cycle, now, baseline)
let_go('detach' if cycle % 2 else 'close', c, term)
print(f'daemon: a Detach in its own terminal, then {cycles} attaches as clients (Detach in each, or its terminal closed), '
f'fds/sockets/processes level: {baseline}')
# Two clients at once, both listed by --ps, both typed into and
# drawn; the second let go by a Detach in it, or its terminal
# closed, and the first draws on.
term = Term(30, 100)
first = attach(term, [binary, 'attach', 'work'], 'first-in')
for how in ('detach', 'close'):
term2 = Term(40, 120)
second = attach(term2, [binary, 'attach', 'work'], f'two-typed-{how}')
os.write(term.master, f'echo one-typed-{how}\r'.encode())
wait_for('the first terminal\'s keys in the shell', lambda: f'one-typed-{how}'.encode() in client.read(f'/pane/{shell}/body'))
# (Words no line before has a letter of in the same place: a
# terminal is sent the cells that changed.)
drawn = f'{how.upper()}BOTHDRAWN'
seen = len(term.text())
run(client, shell, f'echo {drawn}\n'.encode())
wait_for('the first terminal drawn', lambda: drawn.encode() in term.text()[seen:])
wait_for('the second terminal drawn', lambda: drawn.encode() in term2.text())
assert first.poll() is None and second.poll() is None
# Its view the live one: it typed last.
os.write(term2.master, f'echo two-last-{how}\r'.encode())
wait_for('the second terminal\'s keys in the shell', lambda: f'two-last-{how}'.encode() in client.read(f'/pane/{shell}/body'))
let_go(how, second, term2)
wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
drawn = f'{how.upper()}FIRSTON'
seen = len(term.text())
run(client, shell, f'echo {drawn}\n'.encode())
wait_for('the first terminal drawn on', lambda: drawn.encode() in term.text()[seen:])
assert first.poll() is None, 'the first client stays'
now = (fds(session), fds(daemon), len(list(root.iterdir())), len([p for p in processes(root) if alive(p)]))
assert now[:3] == baseline[:3], (how, now, baseline)
print('daemon: two clients at once, each in --ps, both typed into and drawn; the second detached, then closed; the first drew on')
stub = first
# Killed outright: its shells live on, their masters the daemon's,
# and a replica client of it hears so at once, in words (one froze
# 20 s and then said only that there was no such session).
tr = Term(24, 90)
rc = tr.spawn([binary, f'--attach={root / "pardes-replica.sock"}:work'], env)
started.append(rc.pid)
wait_for('the replica client\'s first frame', lambda: len(tr.text()) > 2000, timeout=30)
os.kill(session, signal.SIGKILL)
killed = time.monotonic()
wait_for('the replica client ended with its session', lambda: rc.poll() is not None, timeout=10)
assert time.monotonic() - killed < 2, time.monotonic() - killed
# Its words are in its terminal before it ends, but this side's
# reader may not have them yet.
wait_for('the replica client says it was let go', lambda: b'let this client go' in tr.text())
tr.close()
stub.wait(timeout=10)
client.socket.close()
term.close()
wait_for('the killed session gone', lambda: not alive(session))
time.sleep(.3)
assert alive(shell_pid), 'a killed session\'s shell is not hung up'
assert alive(daemon)
# Started from a shell, which leads the terminal's session and
# outlives the stub, as a terminal's shell does (on FreeBSD the
# leader's exit revokes the terminal for every process).
term = Term()
stub_pid = root / 'stub.pid'
shell = term.spawn(['sh', '-c', '"$@" & echo $! > "$0"; wait; exec sleep 600',
str(stub_pid), binary, '--tty', '--9p=fresh'], env)
started.append(shell.pid)
sock = root / 'pardes-9p-fresh.sock'
wait_for('the second session', sock.exists)
stub = int(stub_pid.read_text())
started.append(stub)
client = Client(sock)
status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())
session = int(status['pid'])
started.append(session)
# Its stub killed outright, the terminal left open: the session
# (the stub's child) takes that as the terminal's end and detaches.
wait_for('the second session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
drawn = len(term.text())
os.kill(stub, signal.SIGKILL)
wait_for('the stub gone', lambda: not alive(stub))
wait_for('the session detached from its killed stub', lambda: sized(client))
assert b'\x1b[?1049l' in term.last()[drawn:], 'the terminal is put back'
assert alive(session)
shell.kill()
shell.wait(timeout=10)
term.close()
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before)
pane = adopted.pop()
assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted')
# Attached again: a client. (After the runs: a pty/run under a
# client puts it off the session's state, and it joins again; one
# that tries as the session ends says it could not.)
term = Term()
stub = term.spawn([binary, 'attach', 'fresh'], env)
started.append(stub.pid)
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {stub.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
# (Under the variable the killed stub was the pair's client: a loss,
# the session still a pair's, P36.)
assert f'session fresh {session} {"(tty)" if WITH_PAIR else listed_as("detached")}' in listed, listed
print('daemon: a session whose stub was killed outright detached, and was attached again, as a client')
# The end: the session quits, its shells hang up, its client and
# the daemon go.
exit_session(client, pane)
assert stub.wait(timeout=10) == 0, stub.returncode
assert b'let this client go' not in term.last(), term.last()[-300:]
client.socket.close()
term.close()
wait_for('the adopted shell hung up', lambda: not alive(shell_pid))
wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
left = [p for p in processes(root) if alive(p)]
assert not left, [cmdline(p) for p in left]
sockets = [p.name for p in root.iterdir() if p.is_socket()]
assert not sockets, sockets
print('daemon: nothing left behind')
finally:
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def sized(client):
"""Whether the session takes a `size`: only with no window or terminal."""
try:
client.write('/ctl', b'size 100 30\n')
return True
except OSError:
return False
def gui(binary, cycles):
"""A window's Detach closes it and keeps the process, detached for good:
`pardes-gui attach` is a window client of it, a process of its own,
and so is a terminal's `pardes attach`. Test mode: hidden windows,
offscreen, the session's stdin the test feed."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch))
env = base_env()
(root / 'caps').mkdir()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'),
SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on', TERM='xterm-256color')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
feed_r, feed_w = os.pipe()
proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
os.close(feed_r)
def listed():
return subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode()
try:
sock = root / 'pardes-9p-win.sock'
wait_for('the window session', sock.exists, timeout=20)
client = Client(sock)
shell = terminals(client)[0]
# The window's own process, or under the variable its child (a
# pair: the window a client of it).
session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
assert not sized(client), 'a window owns the size'
# With its window: another window is a client of the session (its
# own process, its captures its own), listed by --ps; closed, it
# ends alone.
second = Window(root, 'second', [binary, '--attach=win'], env)
wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20)
assert f'client {second.pid} ' in listed(), listed()
second.close()
# (a pair's own window is a client too: the second's pid is what goes)
wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in listed())
assert not sized(client), 'the first window stays'
assert alive(session)
print('daemon: a second window on a window session a client of it (in --ps), closed alone')
# Detached: the window closed, the process on; every attach after it
# a window client, the session detached still.
client.write(f'/pane/{shell}/exec', b'Detach\n')
wait_for('the window closed', lambda: sized(client))
assert alive(session), 'the session carries on with no window'
assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
baseline = None
for cycle in range(cycles):
w = Window(root, f'w{cycle}', [binary, 'attach'] if cycle % 2 else [binary, '--attach=win'], env)
wait_for('the client window drawn', lambda: (root / f'w{cycle}' / 'latest.ppm').exists(), timeout=20)
wait_for('the client in --ps', lambda: f'client {w.pid} ' in listed())
assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
now = (fds(proc.pid), len(processes(root)))
baseline = baseline or now
assert now == baseline, (cycle, now, baseline)
w.close()
wait_for('the client gone from --ps', lambda: 'client ' not in listed())
print(f'daemon: a window Detach, then {cycles} window attaches as clients, fds/processes level: {baseline}')
# A terminal's client of the window's session, by its name alone. A
# name nobody has is refused in words.
term = Term()
tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), 'attach', 'win'], env)
wait_for('the window session drawn in the terminal', lambda: b'\x1b[?1049h' in term.text())
time.sleep(1)
assert tty_attach.poll() is None, term.text()[-400:]
tty_attach.terminate()
tty_attach.wait(timeout=10)
term.close()
assert alive(session)
print('daemon: a terminal attached to a window session by name, as a client')
nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr
# Detached and told to end: it ends.
client.write(f'/pane/{shell}/exec', b'Exit\n')
wait_for('the session ended', lambda: not alive(session))
client.socket.close()
wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5)
print('daemon: window session ended, nothing left behind')
finally:
os.close(feed_w)
for pid in [proc.pid] + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def gui_pair(gui_binary):
"""PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
FILE` is a window client and a session with no SDL, the `pardes` beside
it exec'd in a child (a window's session needs SDL for its wake, a
terminal's binary none): the session the window's child, in a session
of its own, listed detached with the window its client; the file in
the window's first frame, keys in. The window's close ends the session,
its last client (a CLOSE); the window killed leaves it running (a LOSS),
and with no daemon the session ends with its last link. Test mode:
hidden windows, offscreen."""
binary = gui_binary.replace('pardes-gui', 'pardes')
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
windows = []
def listed():
return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
def started(name, e):
w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
windows.append(w)
sock = root / f'pardes-9p-{name}.sock'
wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
return w, nine, session, pane
try:
w, nine, session, pane = started('gp', env)
wait_for('the window listed its client', lambda: f'session gp {session} (gui)' in listed()
and f'client {w.pid} ' in listed())
w.keys(b'Ofrom-the-window\x1b')
wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
# The close button (the test feed's word for it): its last client
# closed, the session ends.
w.p.stdin.write(b'\x1b]777;close\x07')
w.p.stdin.flush()
assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
wait_for('the session ended with its window', lambda: not alive(session), timeout=20)
nine.socket.close()
print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
'setsid, listed detached with the window); drawn, typed; the window closed ended both')
w, nine, session, pane = started('gl', env)
wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
os.kill(w.pid, signal.SIGKILL)
w.p.wait(timeout=10)
wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
assert alive(session) and f'session gl {session} (gui)' in listed(), listed()
nine.socket.close()
assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
print('pair window: the window killed: the session runs on, listed (a loss); killed by name')
# Kept from birth (`new --detach`): its window client's close leaves it.
out = subprocess.run([binary, 'new', '--detach=gk', str(notes)], env=env, cwd=root, capture_output=True,
timeout=30, stdin=subprocess.DEVNULL)
assert out.returncode == 0, out
with Client(root / 'pardes-9p-gk.sock') as kn:
gk = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
assert f'session gk {gk} (tty, kept)' in listed(), listed()
w = Window(root, 'gkw', [gui_binary, 'attach', 'gk'], env)
windows.append(w)
wait_for('the window client listed', lambda: f'client {w.pid} ' in listed(), timeout=30)
w.p.stdin.write(b'\x1b]777;close\x07')
w.p.stdin.flush()
assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
assert alive(gk) and f'session gk {gk} (tty, kept)' in listed(), listed()
assert subprocess.run([binary, 'kill', 'gk'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(gk), timeout=30)
print('pair window: a `new --detach` session (kept): its window client closed, it runs on')
w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
nine.socket.close()
os.kill(w.pid, signal.SIGKILL)
w.p.wait(timeout=10)
wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
finally:
for w in windows:
if w.p.poll() is None:
w.p.kill()
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
return '\n'.join(cells[i:i + shown['cols']] for i in range(0, len(cells), shown['cols']))
def reconnect(sock, timeout=20):
"""The session's 9P again, once its upgraded process listens."""
return wait_for('the upgraded session\'s 9P', lambda: dial(sock), timeout=timeout)
def dial(sock):
try:
return Client(sock)
except (OSError, EOFError): # mid-exec: refused, or cut after the accept
return None
def saying(sock, words, timeout=30):
"""A connection to the session once its screen shows `words`: dialled
afresh each look, since the process it talks to may exec meanwhile."""
last = ['']
def look():
c = dial(sock)
if c is None:
return None
try:
last[0] = screen_text(c)
if words in last[0]:
return c
except (OSError, EOFError):
pass
c.socket.close()
return None
try:
return wait_for(f'the session saying {words!r}', look, timeout=timeout)
except TimeoutError:
raise TimeoutError(f'the session saying {words!r}; it shows:\n{last[0]}')
def exe_of(pid):
"""What /proc says the process runs: (its path, whether that file is the
one at the path now). FreeBSD's procstat names the path alone."""
if not procfs:
rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines()
return (rows[-1].split()[-1] if len(rows) > 1 else ''), None
try:
link = os.readlink(f'/proc/{pid}/exe')
except OSError: # gone, or a zombie: it runs nothing
return '', False
try:
same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino
except OSError:
same = False
return link, same
def entered_again(text, mark):
"""The blink of a client exec'd at an Upgrade: its terminal's screen
left at or after `mark` (the text's length before the Upgrade: when the
reader had read all the old client wrote, the leave is its very next
byte) and entered again. What was drawn since that enter, or None."""
enter, leave = text.rfind(b'\x1b[?1049h'), text.rfind(b'\x1b[?1049l')
return text[enter:] if enter > leave >= mark else None
def on_build(proc, binary):
"""Whether the test's child `proc` runs `binary` now (exe_of); one that
ended says so with its status at once, not as a wait run out."""
assert proc.poll() is None, f'pid {proc.pid} ended ({proc.returncode}) before it ran {binary}'
return exe_of(proc.pid) == (str(binary), True)
def ppid(pid):
if not procfs:
return int(ps('-o', 'ppid=', '-p', str(pid)))
return int(open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[1])
def where_waits(pid):
"""A process's state, a line each thread (its name, state, kernel wait
channel and the syscall it is in): alive or not, and blocked where."""
if not alive(pid):
return f'{pid}: gone\n'
rows = [f'{pid}: alive, {b" ".join(cmdline(pid)).decode(errors="replace")[:300]}']
try:
for tid in sorted(os.listdir(f'/proc/{pid}/task'), key=int):
t = f'/proc/{pid}/task/{tid}'
row = []
for leaf in ('comm', 'wchan', 'syscall'):
try:
row.append(open(f'{t}/{leaf}').read().strip().split(' ')[0])
except OSError:
row.append('?')
state = open(f'{t}/stat').read().rsplit(')', 1)[1].split()[0]
rows.append(f' {tid} {row[0]} {state} wchan {row[1]} syscall {row[2]}')
except OSError:
pass
return '\n'.join(rows + [f' fd {link}' for link in links(pid)]) + '\n'
def keep_evidence(label, root, env, binary, sock, pids, clients):
"""What a failed step leaves for its reader, in a directory the run's
cleanup does not remove (.scratch/daemon/kept/<label>-<time>-<pid>):
each client's terminal text, check file and stats, and its process
(alive, and where each thread waits); the session's screen and /log
over 9P (dialled with its timeout: a session that does not answer says
so), `pardes --ps`, the crash file, and the session's and daemon's
processes. `clients`: (name, Term, Popen, check, stats). Its path."""
out = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'kept' / f'{label}-{time.strftime("%Y%m%d-%H%M%S")}-{os.getpid()}'
out.mkdir(parents=True, exist_ok=True)
for name, term, proc, check, stats in clients:
(out / f'{name}.tty').write_bytes(term.text())
for f, leaf in ((check, 'check'), (stats, 'stats')):
if f.exists():
shutil.copyfile(f, out / f'{name}.{leaf}')
(out / f'{name}.proc').write_text(f'returncode {proc.poll()}\n' + where_waits(proc.pid))
c = dial(sock)
for leaf, read in (('screen', lambda: screen_text(c).encode()), ('log', lambda: c.read('/log'))):
try:
(out / f'session.{leaf}').write_bytes(read() if c else b'its 9P did not answer\n')
except (OSError, EOFError) as err:
(out / f'session.{leaf}').write_text(f'not read: {err!r}\n')
if c:
c.socket.close()
try:
listed = subprocess.run([str(binary), '--ps'], env=env, capture_output=True, timeout=10)
(out / 'ps').write_bytes(listed.stdout + listed.stderr)
except subprocess.TimeoutExpired:
(out / 'ps').write_text('pardes --ps did not answer in 10 s\n')
crashes = root / 'config' / 'pardes' / 'crashes'
if crashes.exists():
shutil.copyfile(crashes, out / 'crashes')
(out / 'processes').write_text(''.join(f'{what}: {where_waits(pid)}' for what, pid in pids))
return out
def install(binary, at):
"""As `zig build` and install(1) put a build in place: a new file
renamed over the old, which a process running it keeps, deleted."""
tmp = at.with_name(at.name + '.new')
if procfs:
subprocess.run(['cp', '--reflink=auto', os.fspath(binary), os.fspath(tmp)], check=True)
else:
shutil.copyfile(binary, tmp)
os.chmod(tmp, 0o755)
os.replace(tmp, at)
def upgrades(old, new):
"""Upgrade (docs/next-daemon.md, phase 6): a tui session with an unsaved
edit, a shell running `sleep 1000; echo done` and two terminals (two
views) moved onto another build installed at the path it started from,
the daemon with it; then a build that refuses the dump, which falls back
to the running one, and one that refuses it everywhere, which starts
afresh with the shells adopted and the dump kept."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtu-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'bin').mkdir()
binary = root / 'bin' / 'pardes'
install(old, binary)
notes = root / 'notes.txt'
notes.write_text('one\ntwo\n')
started = []
try:
term = Term()
stub = term.spawn([str(binary), '--tty', '--9p=work'], env)
started.append(stub.pid)
sock = root / 'pardes-9p-work.sock'
wait_for('the session\'s 9P socket', sock.exists)
client = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
started.append(session)
daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0]
started.append(daemon)
shell = terminals(client)[0]
shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
client.write(f'/pane/{text}/body', b'unsaved\n')
assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n'
# A file of a jj repository with its `Changes` layer shown (a build
# of wire 31: ghost rows, a view's bit; wire 34: the pane's read-only
# lines): shown again after the Upgrade.
layered = None
if shutil.which('jj'):
repo = root / 'repo'
repo.mkdir()
jj = ['jj', '--config=user.name=t', '--config=user.email=t@t', '--quiet']
subprocess.run(jj + ['git', 'init'], cwd=repo, env=env, check=True, capture_output=True)
(repo / 'l.txt').write_text('kept-one\ngone-line-xyzzy\nkept-two\n')
subprocess.run(jj + ['commit', '-m', 'one'], cwd=repo, env=env, check=True, capture_output=True)
(repo / 'l.txt').write_text('kept-one\nkept-two\n')
# Committed: pardes never snapshots the working copy.
subprocess.run(jj + ['commit', '-m', 'two'], cwd=repo, env=env, check=True, capture_output=True)
client.write(f'/pane/{shell}/look', f'{repo / "l.txt"}\n'.encode())
layered = int(client.read('/look'))
client.write(f'/pane/{layered}/exec', b'Changes @-\n')
wait_for('the layer drawn', lambda: 'gone-line-xyzzy' in screen_text(client), timeout=30)
client.write(f'/pane/{shell}/pty/data', b'sleep 1000; echo done-after-upgrade\r')
sleeper = wait_for('the sleep', lambda: [p for p in processes(root) if cmdline(p)[:2] == [b'sleep', b'1000']])[0]
# A second terminal: a view of its own (an older build's), or a client.
term2 = Term(30, 100)
stub2 = term2.spawn([str(binary), '--attach=work'], env)
started.append(stub2.pid)
wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text())
old_build = semantics(old)
replica = Replica(root / 'pardes-replica.sock')
assert replica.hello('work', old_build)[0] == 'welcome'
# A replica client of the old build: let go at the upgrade, it dials
# again and is told to upgrade too.
term3 = Term(24, 90)
stale = term3.spawn([str(old), f'--attach={root / "pardes-replica.sock"}:work'], env)
started.append(stale.pid)
wait_for('the old build\'s client drawn', lambda: b'\x1b[?1049h' in term3.text() and b'one' in term3.text())
before = len(term.text()), len(term2.text())
install(new, binary)
assert not procfs or exe_of(session)[1] is False, 'the session runs the old build, deleted'
# Come back to the terminal: the newer build is said.
os.write(term.master, b'\x1b[I')
wait_for('the newer build said', lambda: 'a newer pardes is installed' in screen_text(client))
fds_before = fds(session), fds(daemon)
state_before = state_fds(session)
rcs = sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*'))
t = time.monotonic()
client.write('/ctl', b'Upgrade\n')
client.socket.close()
new_build = semantics(new)
assert new_build != old_build
if procfs:
wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
else:
wait_for('the session registered as the new build',
lambda: Replica(root / 'pardes-replica.sock').hello('work', new_build)[0] == 'welcome', timeout=30)
client = reconnect(sock)
took = time.monotonic() - t
assert int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) == session
if procfs:
wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True))
else:
wait_for('the daemon exec\'d again', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(daemon)))
assert alive(daemon) and stub.poll() is None
# A replica of the old build is told why it is let go, after what it
# was sent (units, terminals).
tag, body = replica.read()
while tag in (0x05, 0x06, 0x07):
tag, body = replica.read()
assert tag == 0x02 and b'upgrading to another build' in body, (tag, body)
replica.close()
stale.wait(timeout=30)
# (Across a change of the replica protocol, it says that instead.)
said = term3.last()
assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:]
term3.close()
print('upgrade: a replica client of the old build was let go, dialled again and was told to upgrade too')
# The old image's prompt files swept, the new one's made.
wait_for('the prompt files level', lambda: len(list(Path('/tmp').glob(f'pardes-osc133-*-{session}-*'))) == len(rcs))
assert sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) != rcs or not rcs
# Nothing kept that was not: the old binary let go, every fd back.
# (The replicas' connections are two fewer; the state file's one
# more after a build that opened Recent's file for each use, and
# only one: a session holds it once.)
# The second terminal: a replica client, its connection let go at
# the exec (one fewer), or a view of its own an older build kept,
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
# (A client of a build that execs at an Upgrade comes back: its
# connection is the session's again.)
gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
# (Under the variable a pair's session of a build that keeps its
# client's terminal, P48, lets it go: close-on-exec, not carried;
# such a build's put-back turns the in-band resize off.)
gone += 1 if WITH_PAIR and b'\x1b[?2048l\x1b[0m' in Path(old).read_bytes() else 0
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
except TimeoutError:
raise AssertionError(('fds', level(), (fds(session), fds(daemon)), links(session)))
# The edit and its undo.
assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n'
assert any(row.split()[0] == str(text).encode() and row.split()[2] == b'1' for row in client.read('/index').splitlines()), client.read('/index')
client.write(f'/pane/{text}/exec', b'Undo\n')
assert client.read(f'/pane/{text}/body') == b'one\ntwo\n', client.read(f'/pane/{text}/body')
# The layer shown before it: shown, its line drawn, the file's text
# (9P's body) without it.
if layered is not None:
assert client.read(f'/pane/{layered}/body') == b'kept-one\nkept-two\n', client.read(f'/pane/{layered}/body')
wait_for('the layer drawn again', lambda: 'gone-line-xyzzy' in screen_text(client), timeout=30)
print('upgrade: a file\'s Changes layer shown on the old build shown on the new, its line drawn, 9P\'s body the file\'s text without it')
# The shell, its job and its pty: the same, the session's still.
assert alive(shell_pid) and ppid(shell_pid) == session and alive(sleeper)
# Both terminals drawn again, each its own view.
wait_for('the first terminal redrawn', lambda: b'\x1b[?1049h' in term.text()[before[0]:])
# The second: a client again; a replica client of the old build let
# go and told to upgrade too, as the third; or, a view of an older
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
(stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
or b'run the same pardes at both ends' in term2.text())),
timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# Two clients' views kept at the Upgrade, with the time (views.away),
# whose clients never come back (the raw replica, the old build's):
# each its client's for 30 s, and the session's views all taken.
# The first join waits as long as its refusal says.
first = None
if keeps_views(old):
said = first = Replica(root / 'pardes-replica.sock').hello('work', new_build)
kept = re.search(r'one is kept (\d+) s more', said[1]) if said[0] == 'refused' else None
if kept:
time.sleep(int(kept.group(1)) + .5)
print(f'upgrade: two views kept for clients that never came back; the join waited {kept.group(1)} s for one, as its refusal said')
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
assert said == ('welcome', session, 'work'), (said, 'the join before it', first)
said = Replica(root / 'pardes-replica.sock').hello('work', old_build)
assert said[0] == 'refused' and 'another build' in said[1], said
os.kill(sleeper, signal.SIGTERM)
wait_for('the shell carrying on', lambda: b'done-after-upgrade\n' in client.read(f'/pane/{shell}/body'))
print(f'upgrade: session {session}, its daemon {daemon}, shell {shell_pid} and its terminal on the new build (a second one an older build kept let go, or a client again) '
f'(the word to its 9P again: {took * 1000:.0f} ms); the edit, its undo and the job kept')
# A build that cannot load the dump: back to the one running (a copy
# of it kept open from /proc/self/exe; FreeBSD keeps none).
refuser = root / 'refuser'
def refusing(how):
refuser.write_text('#!/bin/sh\n# A pardes whose load refuses the dump (upgrade.zig).\n'
f'case "$1" in --upgraded=*) PARDES_TEST_UPGRADE_REFUSE={how} exec {new} "$@";; esac\n'
f'exec {new} "$@"\n')
refuser.chmod(0o755)
install(refuser, binary)
if procfs:
running = os.stat(f'/proc/{session}/exe').st_ino
# A replica client of the build running: let go at the upgrade,
# it joins again once the session is back, says so, and agrees.
term4 = Term(24, 90)
again = term4.spawn([str(new), f'--attach={root / "pardes-replica.sock"}:work'],
dict(env, PARDES_REPLICA_CHECK=str(root / 'e.check'), PARDES_REPLICA_STATS=str(root / 'e.stats')))
started.append(again.pid)
wait_for('the client of the build running drawn', lambda: b'\x1b[?1049h' in term4.text() and b'one' in term4.text())
# A second, and each a pane of its own in its own view: the
# Upgrade's rejoin gives each its own view back, its pane in it,
# not a new one (a copy of the session's, without it).
term5 = Term(30, 100)
again5 = term5.spawn([str(new), f'--attach={root / "pardes-replica.sock"}:work'],
dict(env, PARDES_REPLICA_CHECK=str(root / 'f.check'), PARDES_REPLICA_STATS=str(root / 'f.stats')))
started.append(again5.pid)
wait_for('the second client of the build running drawn', lambda: b'\x1b[?1049h' in term5.text() and b'one' in term5.text())
owners = ((term4, root / 'e.check'), (term5, root / 'f.check'))
mine = []
for t, check in owners:
made_live(t, check)
shown = view_panes(client)
client.write('/exec', b'New\n')
mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(client) - shown).pop())
refusing('1')
t0 = time.monotonic()
client.write(f'/pane/{shell}/exec', b'Upgrade\n')
client.socket.close()
client = saying(sock, 'it goes on as')
back = time.monotonic() - t0
joined = {}
def rejoined():
for t, check in owners:
if check not in joined and b'joined again: the session is upgrading' in t.text():
joined[check] = time.monotonic() - t0
return len(joined) == len(owners)
try:
wait_for('the clients joined again', rejoined, timeout=30)
except TimeoutError:
raise TimeoutError(f'the client joined again: not {[c.stem for _, c in owners if c not in joined]} '
f'{time.monotonic() - t0:.1f} s after the Upgrade, the session back at {back:.1f} s') from None
assert again.poll() is None and again5.poll() is None
# The session's news: each client's own screen says it (a long
# message shows its end), not only the view whose input came
# last before the Upgrade's step.
wait_for("each client's own screen saying the Upgrade's outcome", lambda: all(b'it goes on as' in t.text() for t, _ in owners), timeout=15)
for (t, check), pane, theirs in zip(owners, mine, reversed(mine)):
in_own_view('its own view again', lambda: made_live(t, check), client, pane, theirs)
for c, t in ((again, term4), (again5, term5)):
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
t.close()
print(f'upgrade: two replica clients of the build running joined again after the upgrade ({back:.1f} s the session back, '
f'the clients {" and ".join(f"{joined[c]:.1f}" for _, c in owners)} s), said so and agreed, each in its own view again, its own pane in it')
assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran'
assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None
assert client.read(f'/pane/{text}/body') == b'one\ntwo\n'
assert (pid := pid_in(client, shell)) == shell_pid, (pid, shell_pid)
print('upgrade: a build that refused the dump fell back to the one running; the shell ran on')
# One that refuses it everywhere: a fresh session, the shells adopted.
refusing('all')
client.write(f'/pane/{shell}/exec', b'Upgrade\n')
client.socket.close()
client = saying(sock, 'brings the rest back')
# The dump stays in the state file, under its label (a second
# upgrade of one pid is `upgrade-<pid>-2`).
kept = client.read('/dumps').decode()
assert any(line.split()[0].startswith(f'upgrade-{session}') for line in kept.splitlines()), kept
assert alive(shell_pid) and ppid(shell_pid) == session, ('the shell under the fresh session', shell_pid, alive(shell_pid) and ppid(shell_pid), session)
pids = {p: pid_in(client, p) for p in terminals(client)}
adopted = [p for p, pid in pids.items() if pid == shell_pid]
assert adopted, ('the shell is a pane of the fresh session', shell_pid, pids, client.read('/index'))
print(f'upgrade: a build that refused it everywhere started afresh, shell {shell_pid} adopted, the dump kept')
# The daemon, three times upgraded, still holds the shell's master:
# the session killed outright, another adopts it.
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
try:
stub2.wait(timeout=30)
except subprocess.TimeoutExpired:
raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
wait_for('the killed session gone', lambda: not alive(session))
time.sleep(.3)
assert alive(shell_pid) and alive(daemon)
term = Term()
stub = term.spawn([str(binary), '--tty', '--9p=again'], env)
started.append(stub.pid)
sock = root / 'pardes-9p-again.sock'
wait_for('the next session', sock.exists)
client = Client(sock)
again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
started.append(again)
# A build before daemon.zig's `kept` waited for the hello's answer
# (the new-to-old run) refused an Adopt before its reader of the
# daemon ran (after its first frame), or within 2 s of a slow `ok`:
# it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
[str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop()
assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted')
exit_session(client, pane)
stub.wait(timeout=10)
client.socket.close()
term.close()
wait_for('the shell hung up', lambda: not alive(shell_pid))
wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
left = [p for p in processes(root) if alive(p)]
assert not left, [cmdline(p) for p in left]
print('upgrade: nothing left behind')
except (TimeoutError, AssertionError, subprocess.TimeoutExpired) as err:
# What each terminal and its process say, and the session's, kept
# (keep_evidence): the clients of the build running by their check
# files' names.
at = locals()
terms = [(name, at[t], at[p], root / f'{name}.check', root / f'{name}.stats')
for name, t, p in (('first', 'term', 'stub'), ('second', 'term2', 'stub2'), ('stale', 'term3', 'stale'),
('e', 'term4', 'again'), ('f', 'term5', 'again5'))
if t in at and hasattr(at.get(p), 'poll')]
kept = keep_evidence('upgrade', root, env, binary, root / 'pardes-9p-work.sock',
[(w, at[w]) for w in ('session', 'daemon') if isinstance(at.get(w), int)], terms)
raise type(err)(f'{err} (kept: {kept})') from None
finally:
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
def knows_size(gui_binary):
"""Whether a build's window exec'd at an Upgrade comes back the size
it had (PARDES_JOIN_SIZE: client.zig `execAgain`)."""
return b'PARDES_JOIN_SIZE' in Path(gui_binary).read_bytes()
def keeps_views(binary):
"""Whether a build keeps its clients' views at an Upgrade with the time
each was kept (View.away_ns), so that the build after holds them."""
return b'away_ns' in Path(binary).read_bytes()
def redials_far(binary):
"""Whether a build's far client whose link an Upgrade cuts with no last
word dials again (core/replica.zig `cutListed`'s `far`) rather than take
it for its session's end: the change that made it gave the window its
size at its exec too (PARDES_JOIN_SIZE), the string that says so."""
return b'PARDES_JOIN_SIZE' in Path(binary).read_bytes()
def knows_exec(binary):
"""Whether a build's client execs the build at its start path at an
Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
def upgrade_clients(old, new):
"""Upgrade with near clients (the last step's design, 1.4): a session
(`new --detach`) with a terminal client and a window client attached,
each in its own view with a pane of its own there, onto another build installed at the path all three were
started from. A client of a build that execs (its start path holding
another file than the one it runs, the session another build than its
own) comes back on the build at its start path, the same process, for
its view: the terminal's leaves its screen and enters it again (the
blink), the window is a new one; in ITS view when that build joins for
a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
of a build before it is let go and told to upgrade too. The session's
shell alive throughout; nothing left behind."""
old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'bin').mkdir()
binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
install(old, binary)
install(old_gui, gui_binary)
terms = []
procs = []
def still(check, key):
"""Its view the live one (made_live's, for either client)."""
seen = len(checks(check))
key(b'gg')
wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
try:
out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
assert out.returncode == 0, out
sock = root / 'pardes-9p-up.sock'
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
shell = terminals(nine)[0]
shell_pid = pid_in(nine, shell)
t = Term(30, 100)
terms.append(t)
tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
procs.append(tc)
wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
procs.append(w.p)
wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
tkey = lambda b: os.write(t.master, b) # noqa: E731
# Each client's view live in turn, a pane of its own made there (New).
owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
mine = []
for key, check in owners:
still(check, key)
shown = view_panes(nine)
nine.write('/exec', b'New\n')
mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
still(check, key)
assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
install(new, binary)
install(new_gui, gui_binary)
mark = len(t.text())
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
nine = reconnect(sock)
if not knows_exec(old):
# A build before the exec: let go, dialled again for 20 s, told.
assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
said = t.text()[mark:] + w.said().encode()
assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
else:
wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
# The blink: its screen left, and entered again.
wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30)
assert tc.poll() is None and w.p.poll() is None
for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
if knows_exec(new):
in_own_view('its own view again', lambda: still(check, key), nine, pane, theirs)
else:
still(check, key)
print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
assert alive(shell_pid) and ppid(shell_pid) == session
for p in procs:
if p.poll() is None:
p.terminate()
p.wait(timeout=20)
nine.socket.close()
assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
print('upgrade with clients: the shell ran on throughout; nothing left behind')
finally:
for p in procs:
if p.poll() is None:
p.kill()
for p in processes(root):
try:
os.kill(p, signal.SIGKILL)
except OSError:
pass
for t in terms:
t.close()
shutil.rmtree(root, ignore_errors=True)
def frame_size(ppm):
"""A window's capture's width and height in pixels (its P6 header)."""
return tuple(int(n) for n in ppm.read_bytes()[:32].split()[1:3])
def gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, resized since its start, a client window, an unsaved edit
and a shell's job, onto another build; its new window the size the old
one had when its record names it (upgrade.zig `Record.size`), the
default when an older build's names none."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch))
env = base_env()
display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0'))
if not display.is_absolute():
display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display
caps = root / 'caps'
caps.mkdir()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(caps),
SDL_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on')
(root / 'config' / 'pardes').mkdir(parents=True)
(root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
(root / 'bin').mkdir()
binary = root / 'bin' / 'pardes-gui'
install(old, binary)
notes = root / 'notes.txt'
notes.write_text('one\ntwo\n')
feed_r, feed_w = os.pipe()
proc = subprocess.Popen([str(binary), '--9p=win'], env=env, cwd=root, stdin=feed_r,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
os.close(feed_r)
started = [proc.pid]
try:
sock = root / 'pardes-9p-win.sock'
wait_for('the window session', sock.exists, timeout=20)
client = Client(sock)
daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0]
started.append(daemon)
shell = terminals(client)[0]
shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
client.write(f'/pane/{text}/body', b'unsaved\n')
client.write(f'/pane/{shell}/pty/data', b'sleep 1000; echo done-after-upgrade\r')
sleeper = wait_for('the sleep', lambda: [p for p in processes(root) if cmdline(p)[:2] == [b'sleep', b'1000']])[0]
# A second window: a replica client of the session (its own
# process, its captures its own), as window_clients' second.
second = Window(root, 'second', [str(binary), '--attach=win'], env)
started.append(second.pid)
frames = [caps / 'latest.ppm', root / 'second' / 'latest.ppm']
wait_for('both windows drawn', lambda: all(f.exists() for f in frames), timeout=20)
# The window resized by hand since its start (the test feed's
# in-band resize, CSI 48;rows;cols t, as a user's drag).
start = frame_size(frames[0])
os.write(feed_w, b'\x1b[48;30;100t')
wait_for('the window resized', lambda: frame_size(frames[0]) != start)
sized = frame_size(frames[0])
install(new, binary)
time.sleep(.05)
mark = time.time()
client.write(f'/pane/{shell}/exec', b'Upgrade\n')
client.socket.close()
wait_for('the session on the new build', lambda: exe_of(proc.pid) == (str(binary), True), timeout=30)
exec_at = time.time()
client = reconnect(sock)
assert proc.poll() is None
wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True))
assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n'
client.write(f'/pane/{text}/exec', b'Undo\n')
assert client.read(f'/pane/{text}/body') == b'one\ntwo\n'
assert alive(shell_pid) and ppid(shell_pid) == proc.pid and alive(sleeper)
wait_for('the window drawn again', lambda: frames[0].stat().st_mtime > mark)
if knows_exec(old):
# The second, a client of a build that execs: the same process,
# on the build at its start path (upgrade_clients checks its
# view; here that it is carried and not let go).
wait_for('the second window on the new build', lambda: exe_of(second.pid) == (str(binary), True), timeout=30)
assert second.p.poll() is None
second.p.terminate()
second.p.wait(timeout=30)
else:
# The second, a client of a build before the exec: let go and
# told to upgrade too.
second.p.wait(timeout=30)
said = second.err.read_bytes()
assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:]
# The new build's window (a frame captured since the exec) the size
# the old one had at the Upgrade, not the one it started at, when
# the old build's record (the new process's command line) names it;
# an older build's names none: the default.
wait_for('a frame of the new build\'s window', lambda: frames[0].stat().st_mtime > exec_at)
record = next((a for a in cmdline(proc.pid) if a.startswith(b'--upgraded=')), b'')
size = re.search(rb'\nsize (\S+)\n', record)
back = frame_size(frames[0])
assert back == (sized if size else start), ('the window back the size it had' if size else 'the default', back, sized, start, record)
print(f'upgrade: the window resized from {start[0]}x{start[1]} to {sized[0]}x{sized[1]} pixels came back '
+ (f'that size (its record: size {size[1].decode()})' if size else 'at the default (the old build\'s record names no size)'))
said = Replica(root / 'pardes-replica.sock').hello('win', semantics(new))
assert said == ('welcome', proc.pid, 'win'), said
os.kill(sleeper, signal.SIGTERM)
wait_for('the shell carrying on', lambda: b'done-after-upgrade\n' in client.read(f'/pane/{shell}/body'))
print(f'upgrade: window session {proc.pid}, its daemon, shell {shell_pid} and its window on the new build, '
'a client window of the old build let go and told to upgrade too; the edit, its undo and the job kept')
client.write(f'/pane/{shell}/exec', b'Exit\n')
proc.wait(timeout=10)
client.socket.close()
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=5)
print('upgrade: window session ended, nothing left behind')
finally:
os.close(feed_w)
for pid in started + processes(root):
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
shutil.rmtree(root, ignore_errors=True)
if __name__ == '__main__':
WITH_PAIR = sys.argv[1:2] == ['--with-pair']
if WITH_PAIR:
del sys.argv[1]
# A session's state file is its HOME's, never the user's: the dumps a
# test makes there would push the user's out.
os.environ.pop('XDG_DATA_HOME', None)
if sys.argv[1:3] == ['--upgrade', '--gui']:
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
old, new = Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()
upgrades(old, new)
if knows_exec(old):
pair_exec_reaps(old, new)
if redials_far(old):
far_exec(old, new)
else:
print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)')
# A reinstall of the new build before the pair's first look: the
# new build's own, whatever the old one does.
pair_exec_reaps(new, new, early=True)
# With a pardes-gui beside each: the clients carried too.
if all(a.with_name('pardes-gui').exists() for a in (old, new)):
upgrade_clients(old, new)
if knows_exec(old):
if knows_size(old.with_name('pardes-gui')):
pair_window_geometry(old.with_name('pardes-gui'), new.with_name('pardes-gui'))
else:
print('pair window geometry: skipped: the old build\'s window passes no size at its exec (no PARDES_JOIN_SIZE)')
elif sys.argv[1:2] == ['--upgrade-clients']:
upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
elif sys.argv[1:2] == ['--launch']:
launch(sys.argv[2])
elif sys.argv[1:2] == ['--pair']:
pair(sys.argv[2])
pair_rows(sys.argv[2])
pair_back(sys.argv[2])
attach_upgrading(sys.argv[2], dump=False)
pair_upgrade_views(sys.argv[2])
elif sys.argv[1:2] == ['--pair-back']:
pair_back(sys.argv[2])
elif sys.argv[1:2] == ['--attach-upgrading']:
attach_upgrading(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
far(sys.argv[2])
far_flood(sys.argv[2])
by_hash(sys.argv[2])
far_find(sys.argv[2])
elif sys.argv[1:2] == ['--far-flood']:
far_flood(sys.argv[2])
elif sys.argv[1:2] == ['--far-find']:
far_find(sys.argv[2])
elif sys.argv[1:2] == ['--kitty-image']:
kitty_image(sys.argv[2])
elif sys.argv[1:2] == ['--restore']:
restore_client(sys.argv[2])
elif sys.argv[1:2] == ['--window-clients']:
window_clients(sys.argv[2], sys.argv[3])
pdf_window(sys.argv[2], sys.argv[3])
client_motion(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--client-motion']:
client_motion(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--client-resize-real']:
client_resize_real(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--client-idle']:
client_idle(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
elif sys.argv[1:2] == ['--pair-gui']:
gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
killed_session(sys.argv[1])
|