Source file state.ml
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
open Core_kernel
open Import
open Types.Kind
type status =
| Stabilizing
| Running_on_update_handlers
| Not_stabilizing
| Stabilize_previously_raised of Raised_exn.t
[@@deriving sexp_of]
module Node_update = On_update_handler.Node_update
module Run_on_update_handlers = struct
type t = T : 'a Node.t * 'a Node_update.t -> t [@@deriving sexp_of]
let invariant (T (node, _node_update) as t) =
Invariant.invariant [%here] t [%sexp_of: t] (fun () -> Node.invariant ignore node)
;;
end
module Only_in_debug = struct
type t =
{ mutable currently_running_node : Node.Packed.t option
; mutable expert_nodes_created_by_current_node : Node.Packed.t list
}
[@@deriving fields, sexp_of]
let invariant t =
Invariant.invariant [%here] t [%sexp_of: t] (fun () ->
Fields.iter
~currently_running_node:ignore
~expert_nodes_created_by_current_node:ignore)
;;
let create () =
{ currently_running_node = None; expert_nodes_created_by_current_node = [] }
;;
end
module Packed_weak_hashtbl = struct
type t = T : (_, _) Weak_hashtbl.t -> t [@@deriving sexp_of]
end
type t =
{ mutable status : status
; bind_lhs_change_should_invalidate_rhs : bool
;
mutable stabilization_num : Stabilization_num.t
; mutable current_scope : Scope.t
; recompute_heap : Recompute_heap.t
; adjust_heights_heap : Adjust_heights_heap.t
;
propagate_invalidity : Node.Packed.t Stack.t
;
mutable num_active_observers : int
;
mutable all_observers : Internal_observer.Packed.t Uopt.t
;
finalized_observers : Internal_observer.Packed.t Thread_safe_queue.t
;
new_observers : Internal_observer.Packed.t Stack.t
;
disallowed_observers : Internal_observer.Packed.t Stack.t
;
set_during_stabilization : Var.Packed.t Stack.t
;
handle_after_stabilization : Node.Packed.t Stack.t
; run_on_update_handlers : Run_on_update_handlers.t Stack.t
; mutable only_in_debug : Only_in_debug.t
; weak_hashtbls : Packed_weak_hashtbl.t Thread_safe_queue.t
;
mutable num_nodes_became_necessary : int
; mutable num_nodes_became_unnecessary : int
; mutable num_nodes_changed : int
; mutable num_nodes_created : int
; mutable num_nodes_invalidated : int
; mutable num_nodes_recomputed : int
; mutable num_nodes_recomputed_directly_because_one_child : int
; mutable num_nodes_recomputed_directly_because_min_height : int
; mutable num_var_sets : int
}
[@@deriving fields, sexp_of]
module Clock = struct
type t = Types.Clock.t =
{
timing_wheel : Alarm_value.t Timing_wheel.t
; now : Time_ns.t Var.t
; handle_fired : Alarm.t -> unit
; mutable fired_alarm_values : Alarm_value.t Uopt.t
}
[@@deriving fields, sexp_of]
let invariant t =
Invariant.invariant [%here] t [%sexp_of: t] (fun () ->
let check f = Invariant.check_field t f in
Fields.iter
~now:
(check (fun (now : _ Var.t) ->
assert (Time_ns.equal now.value (Timing_wheel.now t.timing_wheel))))
~handle_fired:ignore
~fired_alarm_values:
(check (fun fired_alarm_values -> assert (Uopt.is_none fired_alarm_values)))
~timing_wheel:(check (Timing_wheel.invariant Alarm_value.invariant)))
;;
end
let now (clock : Clock.t) = clock.now.value
let timing_wheel_length (clock : Clock.t) = Timing_wheel.length clock.timing_wheel
let num_stabilizes t = Stabilization_num.to_int t.stabilization_num
let max_height_allowed t = Adjust_heights_heap.max_height_allowed t.adjust_heights_heap
let max_height_seen t = Adjust_heights_heap.max_height_seen t.adjust_heights_heap
let iter_observers t ~f =
let r = ref t.all_observers in
while Uopt.is_some !r do
let observer = Uopt.unsafe_value !r in
r := Internal_observer.Packed.next_in_all observer;
f observer
done
;;
let directly_observed t =
let r : Node.Packed.t list ref = ref [] in
iter_observers t ~f:(fun (T internal_observer) ->
r := T internal_observer.observing :: !r);
!r
;;
let save_dot t file = Node.Packed.save_dot file (directly_observed t)
let iter_observer_descendants t ~f =
Node.Packed.iter_descendants (directly_observed t) ~f
;;
module Stats = struct
type t =
{ max_num_parents : int
; percentage_of_nodes_by_num_parents : (int * Percent.t) list
}
[@@deriving sexp]
end
let stats t =
let max_num_parents = ref (-1) in
let num_necessary_nodes = ref 0 in
iter_observer_descendants t ~f:(fun (T node) ->
incr num_necessary_nodes;
max_num_parents := Int.max !max_num_parents node.num_parents);
let max_num_parents = !max_num_parents in
let num_nodes_by_num_parents = Array.create ~len:(max_num_parents + 1) 0 in
iter_observer_descendants t ~f:(fun (T node) ->
let num_parents = node.num_parents in
num_nodes_by_num_parents.(num_parents)
<- num_nodes_by_num_parents.(num_parents) + 1);
let percentage_of_nodes_by_num_parents =
Array.foldi num_nodes_by_num_parents ~init:[] ~f:(fun i ac num_nodes ->
if num_nodes = 0
then ac
else (i, Percent.of_mult (float num_nodes /. float !num_necessary_nodes)) :: ac)
|> List.rev
in
{ Stats.max_num_parents; percentage_of_nodes_by_num_parents }
;;
let am_stabilizing t =
match t.status with
| Running_on_update_handlers | Stabilizing -> true
| Not_stabilizing -> false
| Stabilize_previously_raised raised_exn ->
failwiths
"cannot call am_stabilizing -- stabilize previously raised"
raised_exn
[%sexp_of: Raised_exn.t]
;;
let invariant t =
match t.status with
| Stabilize_previously_raised _ -> ()
| Running_on_update_handlers | Stabilizing | Not_stabilizing ->
Invariant.invariant [%here] t [%sexp_of: t] (fun () ->
let check f = Invariant.check_field t f in
iter_observers t ~f:(fun (T internal_observer) ->
(match internal_observer.state with
| In_use | Disallowed -> ()
| Created | Unlinked ->
failwiths
"member of all_observers with unexpected state"
internal_observer
[%sexp_of: _ Internal_observer.t]);
Internal_observer.invariant ignore internal_observer);
iter_observer_descendants t ~f:(fun (T node) ->
Node.invariant ignore node;
if not (am_stabilizing t) then assert (Uopt.is_none node.old_value_opt);
assert (
node.height <= Adjust_heights_heap.max_height_seen t.adjust_heights_heap));
assert (
Adjust_heights_heap.max_height_allowed t.adjust_heights_heap
= Recompute_heap.max_height_allowed t.recompute_heap);
Fields.iter
~status:ignore
~bind_lhs_change_should_invalidate_rhs:ignore
~stabilization_num:(check Stabilization_num.invariant)
~current_scope:
(check (fun current_scope -> assert (phys_equal current_scope Scope.top)))
~recompute_heap:(check Recompute_heap.invariant)
~adjust_heights_heap:
(check (fun adjust_heights_heap ->
assert (Adjust_heights_heap.length adjust_heights_heap = 0);
Adjust_heights_heap.invariant adjust_heights_heap))
~propagate_invalidity:
(check (fun propagate_invalidity ->
assert (Stack.is_empty propagate_invalidity)))
~num_active_observers:
(check (fun num_active_observers -> assert (num_active_observers >= 0)))
~all_observers:ignore
~finalized_observers:ignore
~new_observers:
(check
(Stack.invariant (fun packed ->
Internal_observer.Packed.invariant packed;
let (T internal_observer) = packed in
match internal_observer.state with
| Created | Unlinked -> ()
| In_use | Disallowed -> assert false)))
~disallowed_observers:
(check
(Stack.invariant (fun packed ->
Internal_observer.Packed.invariant packed;
let (T internal_observer) = packed in
match internal_observer.state with
| Disallowed -> ()
| Created | In_use | Unlinked -> assert false)))
~set_during_stabilization:
(check (fun set_during_stabilization ->
match t.status with
| Stabilize_previously_raised _ -> assert false
| Running_on_update_handlers | Not_stabilizing ->
assert (Stack.is_empty set_during_stabilization)
| Stabilizing ->
Stack.invariant
(fun (Var.Packed.T var) ->
assert (Uopt.is_some var.value_set_during_stabilization))
set_during_stabilization))
~handle_after_stabilization:(check (Stack.invariant Node.Packed.invariant))
~run_on_update_handlers:
(check (Stack.invariant Run_on_update_handlers.invariant))
~only_in_debug:(check Only_in_debug.invariant)
~weak_hashtbls:ignore
~num_nodes_became_necessary:ignore
~num_nodes_became_unnecessary:ignore
~num_nodes_changed:ignore
~num_nodes_created:ignore
~num_nodes_invalidated:ignore
~num_nodes_recomputed:ignore
~num_nodes_recomputed_directly_because_one_child:ignore
~num_nodes_recomputed_directly_because_min_height:ignore
~num_var_sets:ignore)
;;
let ensure_not_stabilizing t ~name ~allow_in_update_handler =
match t.status with
| Not_stabilizing -> ()
| Running_on_update_handlers ->
if not allow_in_update_handler
then (
let backtrace = Backtrace.get () in
failwiths
(sprintf "cannot %s during on-update handlers" name)
backtrace
[%sexp_of: Backtrace.t])
| Stabilize_previously_raised raised_exn ->
let backtrace = Backtrace.get () in
failwiths
(sprintf "cannot %s -- stabilize previously raised" name)
(raised_exn, backtrace)
[%sexp_of: Raised_exn.t * Backtrace.t]
| Stabilizing ->
let backtrace = Backtrace.get () in
failwiths
(sprintf "cannot %s during stabilization" name)
backtrace
[%sexp_of: Backtrace.t]
;;
let set_height t node height =
Adjust_heights_heap.set_height t.adjust_heights_heap node height
;;
let set_max_height_allowed t height =
ensure_not_stabilizing t ~name:"set_max_height_allowed" ~allow_in_update_handler:true;
Adjust_heights_heap.set_max_height_allowed t.adjust_heights_heap height;
Recompute_heap.set_max_height_allowed t.recompute_heap height
;;
let handle_after_stabilization : type a. t -> a Node.t -> unit =
fun t node ->
if not node.is_in_handle_after_stabilization
then (
node.is_in_handle_after_stabilization <- true;
Stack.push t.handle_after_stabilization (T node))
;;
let rec remove_children : type a. t -> a Node.t -> unit =
fun t parent ->
Node.iteri_children parent ~f:(fun child_index (T child) ->
remove_child t ~child ~parent ~child_index)
and remove_child
: type a b. t -> child:b Node.t -> parent:a Node.t -> child_index:int -> unit
=
fun t ~child ~parent ~child_index ->
Node.remove_parent ~child ~parent ~child_index;
check_if_unnecessary t child
and check_if_unnecessary : type a. t -> a Node.t -> unit =
fun t node -> if not (Node.is_necessary node) then became_unnecessary t node
and became_unnecessary : type a. t -> a Node.t -> unit =
fun t node ->
t.num_nodes_became_unnecessary <- t.num_nodes_became_unnecessary + 1;
if node.num_on_update_handlers > 0 then handle_after_stabilization t node;
node.height <- -1;
remove_children t node;
(match node.kind with
| Unordered_array_fold u -> Unordered_array_fold.force_full_compute u
| Expert p -> Expert.observability_change p ~is_now_observable:false
| _ -> ());
if debug then assert (not (Node.needs_to_be_computed node));
if Node.is_in_recompute_heap node then Recompute_heap.remove t.recompute_heap node
;;
let remove_alarm (clock : Clock.t) alarm =
if Timing_wheel.mem clock.timing_wheel alarm
then Timing_wheel.remove clock.timing_wheel alarm
;;
let rec invalidate_node : type a. t -> a Node.t -> unit =
fun t node ->
if Node.is_valid node
then (
if node.num_on_update_handlers > 0 then handle_after_stabilization t node;
node.value_opt <- Uopt.none;
if debug then assert (Uopt.is_none node.old_value_opt);
node.changed_at <- t.stabilization_num;
node.recomputed_at <- t.stabilization_num;
t.num_nodes_invalidated <- t.num_nodes_invalidated + 1;
if Node.is_necessary node
then (
remove_children t node;
node.height <- Scope.height node.created_in + 1);
(match node.kind with
| At at -> remove_alarm at.clock at.alarm
| At_intervals at_intervals -> remove_alarm at_intervals.clock at_intervals.alarm
| Bind_main bind -> invalidate_nodes_created_on_rhs t bind.all_nodes_created_on_rhs
| Step_function { alarm; clock; _ } -> remove_alarm clock alarm
| _ -> ());
Node.set_kind node Invalid;
for index = 0 to node.num_parents - 1 do
Stack.push t.propagate_invalidity (Node.get_parent node ~index)
done;
if debug then assert (not (Node.needs_to_be_computed node));
if Node.is_in_recompute_heap node then Recompute_heap.remove t.recompute_heap node)
and invalidate_nodes_created_on_rhs t node =
let r = ref node in
while Uopt.is_some !r do
let (T node_on_rhs) = Uopt.unsafe_value !r in
r := node_on_rhs.next_node_in_same_scope;
node_on_rhs.next_node_in_same_scope <- Uopt.none;
invalidate_node t node_on_rhs
done
;;
let rescope_nodes_created_on_rhs _t (first_node_on_rhs : Node.Packed.t Uopt.t) ~new_scope
=
let r = ref first_node_on_rhs in
while Uopt.is_some !r do
let (T node_on_rhs) = Uopt.unsafe_value !r in
r := node_on_rhs.next_node_in_same_scope;
node_on_rhs.next_node_in_same_scope <- Uopt.none;
node_on_rhs.created_in <- new_scope;
Scope.add_node new_scope node_on_rhs
done
;;
let propagate_invalidity t =
while not (Stack.is_empty t.propagate_invalidity) do
let (T node) = Stack.pop_exn t.propagate_invalidity in
if Node.is_valid node
then
if Node.should_be_invalidated node
then invalidate_node t node
else (
if debug then assert (Node.needs_to_be_computed node);
(match node.kind with
| Expert expert ->
Expert.incr_invalid_children expert
| kind ->
if debug
then (
match kind with
| Bind_main _ | If_then_else _ | Join_main _ -> ()
| _ ->
assert false ));
if not (Node.is_in_recompute_heap node)
then Recompute_heap.add t.recompute_heap node)
done
;;
let rec add_parent_without_adjusting_heights
: type a b. t -> child:a Node.t -> parent:b Node.t -> child_index:int -> unit
=
fun t ~child ~parent ~child_index ->
if debug then assert (Node.is_necessary parent);
let was_necessary = Node.is_necessary child in
Node.add_parent ~child ~parent ~child_index;
if not (Node.is_valid child) then Stack.push t.propagate_invalidity (T parent);
if not was_necessary then became_necessary t child;
match parent.kind with
| Expert e -> Expert.run_edge_callback e ~child_index
| _ -> ()
and became_necessary : type a. t -> a Node.t -> unit =
fun t node ->
if Node.is_valid node && not (Scope.is_necessary node.created_in)
then
failwiths
"Trying to make a node necessary whose defining bind is not necessary"
node
[%sexp_of: _ Node.t];
t.num_nodes_became_necessary <- t.num_nodes_became_necessary + 1;
if node.num_on_update_handlers > 0 then handle_after_stabilization t node;
set_height t node (Scope.height node.created_in + 1);
Node.iteri_children node ~f:(fun child_index (T child) ->
add_parent_without_adjusting_heights t ~child ~parent:node ~child_index;
if debug then assert (child.height >= 0);
if child.height >= node.height then set_height t node (child.height + 1));
if debug then assert (not (Node.is_in_recompute_heap node));
if debug then assert (Node.is_necessary node);
if Node.is_stale node then Recompute_heap.add t.recompute_heap node;
match node.kind with
| Expert p -> Expert.observability_change p ~is_now_observable:true
| _ -> ()
;;
let became_necessary t node =
became_necessary t node;
propagate_invalidity t
;;
let add_parent t ~child ~parent ~child_index =
if debug then assert (Node.is_necessary parent);
add_parent_without_adjusting_heights t ~child ~parent ~child_index;
if child.height >= parent.height
then
Adjust_heights_heap.adjust_heights
t.adjust_heights_heap
t.recompute_heap
~child
~parent;
propagate_invalidity t;
if debug then assert (Node.is_necessary parent);
if (not (Node.is_in_recompute_heap parent))
&& (Stabilization_num.is_none parent.recomputed_at
|| Node.edge_is_stale ~child ~parent)
then Recompute_heap.add t.recompute_heap parent
;;
let run_with_scope t scope ~f =
let saved = t.current_scope in
t.current_scope <- scope;
try
let v = f () in
t.current_scope <- saved;
v
with
| exn ->
t.current_scope <- saved;
raise exn
;;
let within_scope t scope ~f =
if not (Scope.is_valid scope)
then failwiths "attempt to run within an invalid scope" t [%sexp_of: t];
run_with_scope t scope ~f
;;
let change_child
: type a b.
t
-> parent:a Node.t
-> old_child:b Node.t Uopt.t
-> new_child:b Node.t
-> child_index:int
-> unit
=
fun t ~parent ~old_child ~new_child ~child_index ->
if Uopt.is_none old_child
then add_parent t ~child:new_child ~parent ~child_index
else (
let old_child = Uopt.unsafe_value old_child in
if not (phys_equal old_child new_child)
then (
Node.remove_parent ~child:old_child ~parent ~child_index;
old_child.force_necessary <- true;
add_parent t ~child:new_child ~parent ~child_index;
old_child.force_necessary <- false;
check_if_unnecessary t old_child))
;;
let add_alarm clock ~at alarm_value =
if debug then assert (Time_ns.( > ) at (now clock));
Timing_wheel.add clock.timing_wheel ~at alarm_value
;;
let rec recompute : type a. t -> a Node.t -> unit =
fun t (node : a Node.t) ->
if debug
then (
t.only_in_debug.currently_running_node <- Some (T node);
t.only_in_debug.expert_nodes_created_by_current_node <- []);
t.num_nodes_recomputed <- t.num_nodes_recomputed + 1;
node.recomputed_at <- t.stabilization_num;
match node.kind with
| Array_fold array_fold -> maybe_change_value t node (Array_fold.compute array_fold)
| At { at; clock; _ } ->
if debug then assert (Time_ns.( > ) at (now clock));
maybe_change_value t node Before
| At_intervals _ -> maybe_change_value t node ()
| Bind_lhs_change
({ main
; f
; lhs
; rhs_scope
; rhs = old_rhs
; all_nodes_created_on_rhs = old_all_nodes_created_on_rhs
; _
} as bind) ->
bind.all_nodes_created_on_rhs <- Uopt.none;
let rhs = run_with_scope t rhs_scope ~f:(fun () -> f (Node.value_exn lhs)) in
bind.rhs <- Uopt.some rhs;
node.changed_at <- t.stabilization_num;
change_child
t
~parent:main
~old_child:old_rhs
~new_child:rhs
~child_index:Kind.bind_rhs_child_index;
if Uopt.is_some old_rhs
then (
if t.bind_lhs_change_should_invalidate_rhs
then invalidate_nodes_created_on_rhs t old_all_nodes_created_on_rhs
else
rescope_nodes_created_on_rhs
t
old_all_nodes_created_on_rhs
~new_scope:main.created_in;
propagate_invalidity t);
if debug then assert (Node.is_valid node);
maybe_change_value t node ()
| Bind_main { rhs; _ } -> copy_child t ~parent:node ~child:(Uopt.value_exn rhs)
| Const a -> maybe_change_value t node a
| Freeze { child; only_freeze_when; _ } ->
let value = Node.value_exn child in
if only_freeze_when value
then (
remove_children t node;
Node.set_kind node (Const value);
if Node.is_necessary node then set_height t node 0 else became_unnecessary t node);
maybe_change_value t node value
| If_test_change ({ main; current_branch; test; then_; else_; _ } as if_then_else) ->
let desired_branch = if Node.value_exn test then then_ else else_ in
if_then_else.current_branch <- Uopt.some desired_branch;
node.changed_at <- t.stabilization_num;
change_child
t
~parent:main
~old_child:current_branch
~new_child:desired_branch
~child_index:Kind.if_branch_child_index;
maybe_change_value t node ()
| If_then_else { current_branch; _ } ->
copy_child t ~parent:node ~child:(Uopt.value_exn current_branch)
| Invalid ->
assert false
| Join_lhs_change ({ lhs; main; rhs = old_rhs; _ } as join) ->
let rhs = Node.value_exn lhs in
join.rhs <- Uopt.some rhs;
node.changed_at <- t.stabilization_num;
change_child
t
~parent:main
~old_child:old_rhs
~new_child:rhs
~child_index:Kind.join_rhs_child_index;
maybe_change_value t node ()
| Join_main { rhs; _ } -> copy_child t ~parent:node ~child:(Uopt.value_exn rhs)
| Map (f, n1) -> maybe_change_value t node (f (Node.value_exn n1))
| Snapshot { at; before; clock; _ } ->
if debug then assert (Time_ns.( > ) at (now clock));
maybe_change_value t node before
| Step_function ({ child; clock; _ } as step_function_node) ->
if Uopt.is_some child
then (
let child = Uopt.value_exn child in
if Stabilization_num.compare
child.changed_at
step_function_node.extracted_step_function_from_child_at
> 0
then (
step_function_node.extracted_step_function_from_child_at <- child.changed_at;
remove_alarm clock step_function_node.alarm;
let step_function = Node.value_exn child in
step_function_node.value <- Uopt.some (Step_function.init step_function);
step_function_node.upcoming_steps <- Step_function.steps step_function;
if Node.is_const child
then (
remove_children t node;
step_function_node.child <- Uopt.none;
set_height t node (Scope.height node.created_in + 1))));
Step_function_node.advance step_function_node ~to_:(now clock);
let step_function_value = Uopt.value_exn step_function_node.value in
(match Sequence.hd step_function_node.upcoming_steps with
| None -> if Uopt.is_none child then Node.set_kind node (Const step_function_value)
| Some (at, _) ->
step_function_node.alarm <- add_alarm clock ~at step_function_node.alarm_value);
maybe_change_value t node step_function_value
| Unordered_array_fold u -> maybe_change_value t node (Unordered_array_fold.compute u)
| Uninitialized -> assert false
| Var var -> maybe_change_value t node var.value
| Map2 (f, n1, n2) ->
maybe_change_value t node (f (Node.value_exn n1) (Node.value_exn n2))
| Map3 (f, n1, n2, n3) ->
maybe_change_value
t
node
(f (Node.value_exn n1) (Node.value_exn n2) (Node.value_exn n3))
| Map4 (f, n1, n2, n3, n4) ->
maybe_change_value
t
node
(f (Node.value_exn n1) (Node.value_exn n2) (Node.value_exn n3) (Node.value_exn n4))
| Map5 (f, n1, n2, n3, n4, n5) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5))
| Map6 (f, n1, n2, n3, n4, n5, n6) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6))
| Map7 (f, n1, n2, n3, n4, n5, n6, n7) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7))
| Map8 (f, n1, n2, n3, n4, n5, n6, n7, n8) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8))
| Map9 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9))
| Map10 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10))
| Map11 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10)
(Node.value_exn n11))
| Map12 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10)
(Node.value_exn n11)
(Node.value_exn n12))
| Map13 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10)
(Node.value_exn n11)
(Node.value_exn n12)
(Node.value_exn n13))
| Map14 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10)
(Node.value_exn n11)
(Node.value_exn n12)
(Node.value_exn n13)
(Node.value_exn n14))
| Map15 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15) ->
maybe_change_value
t
node
(f
(Node.value_exn n1)
(Node.value_exn n2)
(Node.value_exn n3)
(Node.value_exn n4)
(Node.value_exn n5)
(Node.value_exn n6)
(Node.value_exn n7)
(Node.value_exn n8)
(Node.value_exn n9)
(Node.value_exn n10)
(Node.value_exn n11)
(Node.value_exn n12)
(Node.value_exn n13)
(Node.value_exn n14)
(Node.value_exn n15))
| Expert expert ->
(match Expert.before_main_computation expert with
| `Invalid ->
invalidate_node t node;
propagate_invalidity t
| `Ok -> maybe_change_value t node (expert.f ()))
and copy_child : type a. t -> parent:a Node.t -> child:a Node.t -> unit =
fun t ~parent ~child ->
if Node.is_valid child
then maybe_change_value t parent (Node.value_exn child)
else (
invalidate_node t parent;
propagate_invalidity t)
and maybe_change_value : type a. t -> a Node.t -> a -> unit =
fun t (node : _ Node.t) new_value ->
let old_value_opt = node.value_opt in
if Uopt.is_none old_value_opt
|| not
(Cutoff.should_cutoff
node.cutoff
~old_value:(Uopt.unsafe_value old_value_opt)
~new_value)
then (
node.value_opt <- Uopt.some new_value;
node.changed_at <- t.stabilization_num;
t.num_nodes_changed <- t.num_nodes_changed + 1;
if node.num_on_update_handlers > 0
then (
node.old_value_opt <- old_value_opt;
handle_after_stabilization t node);
if node.num_parents >= 1
then (
for parent_index = 1 to node.num_parents - 1 do
let (T parent) = Uopt.value_exn node.parent1_and_beyond.(parent_index - 1) in
(match parent.kind with
| Expert expert ->
let child_index = node.my_child_index_in_parent_at_index.(parent_index) in
Expert.run_edge_callback ~child_index expert
| Unordered_array_fold u ->
Unordered_array_fold.child_changed
u
~child:node
~child_index:node.my_child_index_in_parent_at_index.(parent_index)
~old_value_opt
~new_value
| _ -> ());
if debug then assert (Node.needs_to_be_computed parent);
if not (Node.is_in_recompute_heap parent)
then Recompute_heap.add t.recompute_heap parent
done;
let (T parent) = Uopt.value_exn node.parent0 in
(match parent.kind with
| Expert p ->
let child_index = node.my_child_index_in_parent_at_index.(0) in
Expert.run_edge_callback ~child_index p
| Unordered_array_fold u ->
Unordered_array_fold.child_changed
u
~child:node
~child_index:node.my_child_index_in_parent_at_index.(0)
~old_value_opt
~new_value
| _ -> ());
if debug then assert (Node.needs_to_be_computed parent);
if not (Node.is_in_recompute_heap parent)
then (
let can_recompute_now =
match parent.kind with
| Uninitialized -> assert false
| At _ -> assert false
| At_intervals _ -> assert false
| Const _ | Invalid | Snapshot _ | Var _ -> assert false
| Array_fold _
| Map2 _
| Map3 _
| Map4 _
| Map5 _
| Map6 _
| Map7 _
| Map8 _
| Map9 _
| Map10 _
| Map11 _
| Map12 _
| Map13 _
| Map14 _
| Map15 _
| Unordered_array_fold _
| Expert _ -> false
| Bind_lhs_change _ -> node.height > Scope.height parent.created_in
| Freeze _ -> node.height > Scope.height parent.created_in
| If_test_change _ -> node.height > Scope.height parent.created_in
| Join_lhs_change _ -> node.height > Scope.height parent.created_in
| Map _ -> node.height > Scope.height parent.created_in
| Step_function _ -> node.height > Scope.height parent.created_in
| Bind_main b -> node.height > b.lhs_change.height
| If_then_else i -> node.height > i.test_change.height
| Join_main j -> node.height > j.lhs_change.height
in
if can_recompute_now
then (
t.num_nodes_recomputed_directly_because_one_child
<- t.num_nodes_recomputed_directly_because_one_child + 1;
recompute t parent)
else if parent.height <= Recompute_heap.min_height t.recompute_heap
then (
t.num_nodes_recomputed_directly_because_min_height
<- t.num_nodes_recomputed_directly_because_min_height + 1;
recompute t parent)
else (
if debug then assert (Node.needs_to_be_computed parent);
if debug then assert (not (Node.is_in_recompute_heap parent));
Recompute_heap.add t.recompute_heap parent))));
if debug then invariant t
;;
let recompute_everything_that_is_necessary t =
let module R = Recompute_heap in
let r = t.recompute_heap in
while R.length r > 0 do
let (T node) = R.remove_min r in
if debug && not (Node.needs_to_be_computed node)
then
failwiths
"node unexpectedly does not need to be computed"
node
[%sexp_of: _ Node.t];
recompute t node
done;
if debug
then (
t.only_in_debug.currently_running_node <- None;
t.only_in_debug.expert_nodes_created_by_current_node <- [])
;;
let unlink_disallowed_observers t =
while Stack.length t.disallowed_observers > 0 do
let packed = Stack.pop_exn t.disallowed_observers in
let module Packed = Internal_observer.Packed in
let (T internal_observer) = packed in
if debug
then
assert (
match internal_observer.state with
| Disallowed -> true
| _ -> false);
internal_observer.state <- Unlinked;
let (T all_observers) = Uopt.value_exn t.all_observers in
if Internal_observer.same internal_observer all_observers
then t.all_observers <- internal_observer.next_in_all;
Internal_observer.unlink internal_observer;
check_if_unnecessary t internal_observer.observing
done
;;
let disallow_future_use t (internal_observer : _ Internal_observer.t) =
match internal_observer.state with
| Disallowed | Unlinked -> ()
| Created ->
t.num_active_observers <- t.num_active_observers - 1;
internal_observer.state <- Unlinked;
internal_observer.on_update_handlers <- []
| In_use ->
t.num_active_observers <- t.num_active_observers - 1;
internal_observer.state <- Disallowed;
Stack.push t.disallowed_observers (T internal_observer)
;;
let disallow_finalized_observers t =
while Thread_safe_queue.length t.finalized_observers > 0 do
let (T internal_observer) = Thread_safe_queue.dequeue_exn t.finalized_observers in
if List.is_empty internal_observer.on_update_handlers
then disallow_future_use t internal_observer
done
;;
let observer_finalizer t =
stage (fun observer ->
let internal_observer = !observer in
Thread_safe_queue.enqueue t.finalized_observers (T internal_observer))
;;
let create_observer ?(should_finalize = true) t observing =
let internal_observer : _ Internal_observer.t =
{ state = Created
; observing
; on_update_handlers = []
; prev_in_all = Uopt.none
; next_in_all = Uopt.none
; prev_in_observing = Uopt.none
; next_in_observing = Uopt.none
}
in
Stack.push t.new_observers (T internal_observer);
let observer = ref internal_observer in
if should_finalize
then Gc.Expert.add_finalizer_exn observer (unstage (observer_finalizer t));
t.num_active_observers <- t.num_active_observers + 1;
observer
;;
let add_new_observers t =
while Stack.length t.new_observers > 0 do
let packed = Stack.pop_exn t.new_observers in
let module Packed = Internal_observer.Packed in
let (T internal_observer) = packed in
match internal_observer.state with
| In_use | Disallowed -> assert false
| Unlinked -> ()
| Created ->
internal_observer.state <- In_use;
let old_all_observers = t.all_observers in
if Uopt.is_some old_all_observers
then (
internal_observer.next_in_all <- old_all_observers;
Packed.set_prev_in_all (Uopt.unsafe_value old_all_observers) (Uopt.some packed));
t.all_observers <- Uopt.some packed;
let observing = internal_observer.observing in
let was_necessary = Node.is_necessary observing in
observing.num_on_update_handlers
<- observing.num_on_update_handlers
+ List.length internal_observer.on_update_handlers;
let old_observers = observing.observers in
if Uopt.is_some old_observers
then (
internal_observer.next_in_observing <- old_observers;
(Uopt.unsafe_value old_observers).prev_in_observing
<- Uopt.some internal_observer);
observing.observers <- Uopt.some internal_observer;
handle_after_stabilization t observing;
if debug then assert (Node.is_necessary observing);
if not was_necessary then became_necessary t observing
done
;;
let observer_value_exn t observer =
match t.status with
| Not_stabilizing | Running_on_update_handlers -> Observer.value_exn observer
| Stabilize_previously_raised raised_exn ->
failwiths
"Observer.value_exn called after stabilize previously raised"
raised_exn
[%sexp_of: Raised_exn.t]
| Stabilizing ->
failwiths
"Observer.value_exn called during stabilization"
observer
[%sexp_of: _ Observer.t]
;;
let observer_value t observer =
try Ok (observer_value_exn t observer) with
| exn -> Error (Error.of_exn exn)
;;
let node_on_update (type a) t (node : a Node.t) ~f =
Node.on_update node (On_update_handler.create f ~at:t.stabilization_num);
handle_after_stabilization t node
;;
let observer_on_update_exn (type a) t (observer : a Observer.t) ~f =
Observer.on_update_exn observer (On_update_handler.create f ~at:t.stabilization_num);
handle_after_stabilization t (Observer.observing observer)
;;
let set_var_while_not_stabilizing t (var : _ Var.t) value =
t.num_var_sets <- t.num_var_sets + 1;
var.value <- value;
if Stabilization_num.compare var.set_at t.stabilization_num < 0
then (
var.set_at <- t.stabilization_num;
let watch = var.watch in
if debug then assert (Node.is_stale watch);
if Node.is_necessary watch && not (Node.is_in_recompute_heap watch)
then Recompute_heap.add t.recompute_heap watch)
;;
let set_var t var value =
match t.status with
| Running_on_update_handlers | Not_stabilizing ->
set_var_while_not_stabilizing t var value
| Stabilize_previously_raised raised_exn ->
failwiths
"cannot set var -- stabilization previously raised"
raised_exn
[%sexp_of: Raised_exn.t]
| Stabilizing ->
if Uopt.is_none var.value_set_during_stabilization
then Stack.push t.set_during_stabilization (T var);
var.value_set_during_stabilization <- Uopt.some value
;;
let reclaim_space_in_weak_hashtbls t =
while Thread_safe_queue.length t.weak_hashtbls > 0 do
let (T weak_hashtbl) = Thread_safe_queue.dequeue_exn t.weak_hashtbls in
Weak_hashtbl.reclaim_space_for_keys_with_unused_data weak_hashtbl
done
;;
let stabilize t =
ensure_not_stabilizing t ~name:"stabilize" ~allow_in_update_handler:false;
try
t.status <- Stabilizing;
disallow_finalized_observers t;
add_new_observers t;
unlink_disallowed_observers t;
if debug then invariant t;
recompute_everything_that_is_necessary t;
t.stabilization_num <- Stabilization_num.add1 t.stabilization_num;
while not (Stack.is_empty t.set_during_stabilization) do
let (T var) = Stack.pop_exn t.set_during_stabilization in
let value = Uopt.value_exn var.value_set_during_stabilization in
var.value_set_during_stabilization <- Uopt.none;
set_var_while_not_stabilizing t var value
done;
while not (Stack.is_empty t.handle_after_stabilization) do
let (T node) = Stack.pop_exn t.handle_after_stabilization in
node.is_in_handle_after_stabilization <- false;
let old_value = node.old_value_opt in
node.old_value_opt <- Uopt.none;
let node_update : _ Node_update.t =
if not (Node.is_valid node)
then Invalidated
else if not (Node.is_necessary node)
then Unnecessary
else (
let new_value = Uopt.value_exn node.value_opt in
if Uopt.is_none old_value
then Necessary new_value
else Changed (Uopt.unsafe_value old_value, new_value))
in
Stack.push t.run_on_update_handlers (T (node, node_update))
done;
t.status <- Running_on_update_handlers;
let now = t.stabilization_num in
while not (Stack.is_empty t.run_on_update_handlers) do
let (T (node, node_update)) = Stack.pop_exn t.run_on_update_handlers in
Node.run_on_update_handlers node node_update ~now
done;
t.status <- Not_stabilizing;
reclaim_space_in_weak_hashtbls t
with
| exn ->
t.status <- Stabilize_previously_raised (Raised_exn.create exn);
raise exn
;;
let create_node_in t created_in kind =
t.num_nodes_created <- t.num_nodes_created + 1;
Node.create created_in kind
;;
let create_node t kind = create_node_in t t.current_scope kind
let create_node_top t kind = create_node_in t Scope.top kind
let create_var ?(use_current_scope = false) t value =
let scope = if use_current_scope then t.current_scope else Scope.top in
let watch = create_node_in t scope Uninitialized in
let var =
{ Var.value
; value_set_during_stabilization = Uopt.none
; set_at = t.stabilization_num
; watch
}
in
Node.set_kind watch (Var var);
var
;;
let const t a = create_node t (Const a)
let map t n ~f = create_node t (Map (f, n))
let map2 t n1 n2 ~f = create_node t (Map2 (f, n1, n2))
let map3 t n1 n2 n3 ~f = create_node t (Map3 (f, n1, n2, n3))
let map4 t n1 n2 n3 n4 ~f = create_node t (Map4 (f, n1, n2, n3, n4))
let map5 t n1 n2 n3 n4 n5 ~f = create_node t (Map5 (f, n1, n2, n3, n4, n5))
let map6 t n1 n2 n3 n4 n5 n6 ~f = create_node t (Map6 (f, n1, n2, n3, n4, n5, n6))
let map7 t n1 n2 n3 n4 n5 n6 n7 ~f = create_node t (Map7 (f, n1, n2, n3, n4, n5, n6, n7))
let map8 t n1 n2 n3 n4 n5 n6 n7 n8 ~f =
create_node t (Map8 (f, n1, n2, n3, n4, n5, n6, n7, n8))
;;
let map9 t n1 n2 n3 n4 n5 n6 n7 n8 n9 ~f =
create_node t (Map9 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9))
;;
let map10 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 ~f =
create_node t (Map10 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10))
;;
let map11 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 ~f =
create_node t (Map11 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11))
;;
let map12 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 ~f =
create_node t (Map12 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12))
;;
let map13 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 ~f =
create_node t (Map13 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13))
;;
let map14 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 ~f =
create_node t (Map14 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14))
;;
let map15 t n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 ~f =
create_node
t
(Map15 (f, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15))
;;
let preserve_cutoff ~(input : _ Node.t) ~output =
Node.set_cutoff
output
(Cutoff.create (fun ~old_value:_ ~new_value:_ ->
Stabilization_num.equal input.changed_at output.changed_at))
;;
let depend_on t input ~depend_on =
let output = map2 t input depend_on ~f:(fun a _ -> a) in
preserve_cutoff ~input ~output;
output
;;
let necessary_if_alive t input =
let observer = create_observer t input in
let output =
map t input ~f:(fun a ->
Gc.keep_alive observer;
a)
in
preserve_cutoff ~input ~output;
output
;;
let bind t lhs ~f =
let lhs_change = create_node t Uninitialized in
let main = create_node t Uninitialized in
let bind =
{ Bind.main
; f
; lhs
; lhs_change
; rhs = Uopt.none
; rhs_scope = Scope.top
; all_nodes_created_on_rhs = Uopt.none
}
in
Node.set_cutoff lhs_change Cutoff.never;
bind.rhs_scope <- Bind bind;
Node.set_kind lhs_change (Bind_lhs_change bind);
Node.set_kind main (Bind_main bind);
main
;;
let bind2 t n1 n2 ~f =
bind t (map2 t n1 n2 ~f:(fun v1 v2 -> v1, v2)) ~f:(fun (v1, v2) -> f v1 v2)
;;
let bind3 t n1 n2 n3 ~f =
bind
t
(map3 t n1 n2 n3 ~f:(fun v1 v2 v3 -> v1, v2, v3))
~f:(fun (v1, v2, v3) -> f v1 v2 v3)
;;
let bind4 t n1 n2 n3 n4 ~f =
bind
t
(map4 t n1 n2 n3 n4 ~f:(fun v1 v2 v3 v4 -> v1, v2, v3, v4))
~f:(fun (v1, v2, v3, v4) -> f v1 v2 v3 v4)
;;
let join t lhs =
let lhs_change = create_node t Uninitialized in
let main = create_node t Uninitialized in
let join = { Join.lhs; lhs_change; rhs = Uopt.none; main } in
Node.set_cutoff lhs_change Cutoff.never;
Node.set_kind lhs_change (Join_lhs_change join);
Node.set_kind main (Join_main join);
main
;;
let if_ t test ~then_ ~else_ =
let test_change = create_node t Uninitialized in
let main = create_node t Uninitialized in
let if_then_else =
{ If_then_else.test; then_; else_; test_change; main; current_branch = Uopt.none }
in
Node.set_cutoff test_change Cutoff.never;
Node.set_kind test_change (If_test_change if_then_else);
Node.set_kind main (If_then_else if_then_else);
main
;;
let lazy_from_fun t ~f =
let scope = t.current_scope in
Lazy.from_fun (fun () -> within_scope t scope ~f)
;;
let default_hash_table_initial_size = 4
let memoize_fun_by_key
?(initial_size = default_hash_table_initial_size)
t
hashable
project_key
f
=
let scope = t.current_scope in
let table = Hashtbl.create hashable ~size:initial_size in
stage (fun a ->
let key = project_key a in
match Hashtbl.find table key with
| Some b -> b
| None ->
let b = within_scope t scope ~f:(fun () -> f a) in
Hashtbl.add_exn table ~key ~data:b;
b)
;;
let array_fold t children ~init ~f =
if Array.length children = 0
then const t init
else create_node t (Array_fold { init; f; children })
;;
let all t ts = array_fold t (Array.of_list_rev ts) ~init:[] ~f:(fun ac a -> a :: ac)
module Unordered_array_fold_update = Unordered_array_fold.Update
let unordered_array_fold
?(full_compute_every_n_changes = Int.max_value)
t
children
~init
~f
~update
=
if Array.length children = 0
then const t init
else if full_compute_every_n_changes <= 0
then
failwiths
"unordered_array_fold got non-positive full_compute_every_n_changes"
full_compute_every_n_changes
[%sexp_of: int]
else (
let main = create_node t Uninitialized in
Node.set_kind
main
(Unordered_array_fold
(Unordered_array_fold.create
~init
~f
~update
~full_compute_every_n_changes
~children
~main));
main)
;;
let opt_unordered_array_fold ?full_compute_every_n_changes t ts ~init ~f ~f_inverse =
let f (accum, num_invalid) x =
match x with
| None -> accum, num_invalid + 1
| Some x -> f accum x, num_invalid
in
let f_inverse (accum, num_invalid) x =
match x with
| None -> accum, num_invalid - 1
| Some x -> f_inverse accum x, num_invalid
in
map
t
(unordered_array_fold
t
ts
~init:(init, 0)
~f
~update:(F_inverse f_inverse)
?full_compute_every_n_changes)
~f:(fun (accum, num_invalid) -> if num_invalid = 0 then Some accum else None)
;;
let at_least_k_of t nodes ~k =
let bool_to_int b = if b then 1 else 0 in
map
t
~f:(fun i -> i >= k)
(unordered_array_fold
t
nodes
~init:0
~f:(fun num_true b -> num_true + bool_to_int b)
~update:(F_inverse (fun num_true b -> num_true - bool_to_int b)))
;;
let exists t nodes = at_least_k_of t nodes ~k:1
let for_all t nodes = at_least_k_of t nodes ~k:(Array.length nodes)
let sum ?full_compute_every_n_changes t nodes ~zero ~add ~sub =
unordered_array_fold
t
nodes
~init:zero
~f:add
~update:(F_inverse sub)
?full_compute_every_n_changes
;;
let opt_sum ?full_compute_every_n_changes t nodes ~zero ~add ~sub =
opt_unordered_array_fold
t
nodes
~init:zero
~f:add
~f_inverse:sub
?full_compute_every_n_changes
;;
let sum_int t nodes = sum t nodes ~zero:0 ~add:( + ) ~sub:( - )
let sum_float t nodes =
sum
t
nodes
~zero:0.
~add:( +. )
~sub:( -. )
~full_compute_every_n_changes:(Array.length nodes)
;;
let set_freeze t (node : _ Node.t) ~child ~only_freeze_when =
if debug then assert (Scope.is_top node.created_in);
let was_necessary = Node.is_necessary node in
Node.set_kind node (Freeze { main = node; child; only_freeze_when });
if was_necessary
then add_parent t ~child ~parent:node ~child_index:Kind.freeze_child_index
else became_necessary t node
;;
let freeze t child ~only_freeze_when =
let node = create_node_top t Uninitialized in
set_freeze t node ~child ~only_freeze_when;
node
;;
let at t clock time =
if Time_ns.( <= ) time (now clock)
then const t Before_or_after.After
else (
let main = create_node t Uninitialized in
let at = { At.at = time; main; alarm = Alarm.null; clock } in
Node.set_kind main (At at);
at.alarm <- add_alarm clock ~at:time (Alarm_value.create (At at));
main)
;;
let after t clock span = at t clock (Time_ns.add (now clock) span)
let next_interval_alarm_strict (clock : Clock.t) ~base ~interval =
let after = now clock in
let at = Time_ns.next_multiple ~base ~after ~interval ~can_equal_after:false () in
if debug then assert (Time_ns.( > ) at after);
at
;;
let at_intervals t (clock : Clock.t) interval =
if Time_ns.Span.( < ) interval (Timing_wheel.alarm_precision clock.timing_wheel)
then
failwiths "at_intervals got too small interval" interval [%sexp_of: Time_ns.Span.t];
let main = create_node t Uninitialized in
let base = now clock in
let at_intervals = { At_intervals.main; base; interval; alarm = Alarm.null; clock } in
Node.set_kind main (At_intervals at_intervals);
Node.set_cutoff main Cutoff.never;
at_intervals.alarm
<- add_alarm
clock
~at:(next_interval_alarm_strict clock ~base ~interval)
(Alarm_value.create (At_intervals at_intervals));
main
;;
let snapshot t clock value_at ~at ~before =
if Time_ns.( <= ) at (now clock)
then
if Time_ns.( < ) at (now clock)
then Or_error.error "cannot take snapshot in the past" at [%sexp_of: Time_ns.t]
else Ok (freeze t value_at ~only_freeze_when:(Fn.const true))
else (
let main = create_node_top t Uninitialized in
let snapshot = { Snapshot.main; at; before; value_at; clock } in
Node.set_kind main (Snapshot snapshot);
ignore (add_alarm clock ~at (Alarm_value.create (Snapshot snapshot)) : Alarm.t);
Ok main)
;;
let incremental_step_function t clock child =
let main = create_node t Uninitialized in
let step_function_node =
{ Step_function_node.main
; value = Uopt.none
; child = Uopt.some child
; extracted_step_function_from_child_at = Stabilization_num.none
; upcoming_steps = Sequence.empty
; alarm = Alarm.null
; alarm_value = Obj.magic None
; clock
}
in
step_function_node.alarm_value <- Alarm_value.create (Step_function step_function_node);
Node.set_kind main (Step_function step_function_node);
main
;;
let make_stale t (node : _ Node.t) =
node.recomputed_at <- Stabilization_num.none;
if Node.needs_to_be_computed node && not (Node.is_in_recompute_heap node)
then Recompute_heap.add t.recompute_heap node
;;
let advance_clock t (clock : Clock.t) ~to_ =
ensure_not_stabilizing t ~name:"advance_clock" ~allow_in_update_handler:true;
if debug then invariant t;
if Time_ns.( > ) to_ (now clock)
then (
set_var_while_not_stabilizing t clock.now to_;
Timing_wheel.advance_clock clock.timing_wheel ~to_ ~handle_fired:clock.handle_fired;
Timing_wheel.fire_past_alarms clock.timing_wheel ~handle_fired:clock.handle_fired;
while Uopt.is_some clock.fired_alarm_values do
let alarm_value = Uopt.unsafe_value clock.fired_alarm_values in
clock.fired_alarm_values <- alarm_value.next_fired;
alarm_value.next_fired <- Uopt.none;
match alarm_value.action with
| At { main; _ } ->
if Node.is_valid main
then (
Node.set_kind main (Const After);
make_stale t main)
| At_intervals ({ main; base; interval; _ } as at_intervals) ->
if Node.is_valid main
then (
at_intervals.alarm
<- add_alarm
clock
~at:(next_interval_alarm_strict clock ~base ~interval)
alarm_value;
make_stale t main)
| Snapshot { main; value_at; _ } ->
if debug then assert (Node.is_valid main);
set_freeze t main ~child:value_at ~only_freeze_when:(fun _ -> true);
make_stale t main
| Step_function { main; _ } -> if Node.is_valid main then make_stale t main
done;
if debug then invariant t)
;;
let create_clock t ~timing_wheel_config ~start =
let timing_wheel = Timing_wheel.create ~config:timing_wheel_config ~start in
let rec clock : Clock.t =
{ now = create_var t start
; handle_fired
; fired_alarm_values = Uopt.none
; timing_wheel
}
and handle_fired alarm =
let alarm_value = Timing_wheel.Alarm.value clock.timing_wheel alarm in
alarm_value.next_fired <- clock.fired_alarm_values;
clock.fired_alarm_values <- Uopt.some alarm_value
in
clock
;;
let create (module Config : Config.Incremental_config) ~max_height_allowed =
let adjust_heights_heap = Adjust_heights_heap.create ~max_height_allowed in
let recompute_heap = Recompute_heap.create ~max_height_allowed in
let t =
{ status = Not_stabilizing
; bind_lhs_change_should_invalidate_rhs =
Config.bind_lhs_change_should_invalidate_rhs
; stabilization_num = Stabilization_num.zero
; current_scope = Scope.top
; adjust_heights_heap
; recompute_heap
; propagate_invalidity = Stack.create ()
; num_active_observers = 0
; all_observers = Uopt.none
; finalized_observers = Thread_safe_queue.create ()
; disallowed_observers = Stack.create ()
; new_observers = Stack.create ()
; set_during_stabilization = Stack.create ()
; handle_after_stabilization = Stack.create ()
; run_on_update_handlers = Stack.create ()
; only_in_debug = Only_in_debug.create ()
; weak_hashtbls = Thread_safe_queue.create ()
; num_nodes_became_necessary = 0
; num_nodes_became_unnecessary = 0
; num_nodes_changed = 0
; num_nodes_invalidated = 0
; num_nodes_created = 0
; num_nodes_recomputed = 0
; num_nodes_recomputed_directly_because_one_child = 0
; num_nodes_recomputed_directly_because_min_height = 0
; num_var_sets = 0
}
in
t
;;
let weak_memoize_fun_by_key
?(initial_size = default_hash_table_initial_size)
t
hashable
project_key
f
=
let scope = t.current_scope in
let table = Weak_hashtbl.create ~size:initial_size hashable in
let packed = Packed_weak_hashtbl.T table in
Weak_hashtbl.set_run_when_unused_data table ~thread_safe_f:(fun () ->
Thread_safe_queue.enqueue t.weak_hashtbls packed);
stage (fun a ->
let key = project_key a in
match Weak_hashtbl.find table key with
| Some b -> b
| None ->
let b = within_scope t scope ~f:(fun () -> f a) in
Weak_hashtbl.add_exn table ~key ~data:b;
b)
;;
module Expert = struct
let expert_kind_of_node (node : _ Node.t) =
match node.kind with
| Expert e -> Uopt.some e
| Invalid -> Uopt.none
| kind -> raise_s [%sexp "unexpected kind for expert node", (kind : _ Kind.t)]
;;
let create state ~on_observability_change f =
let e = Expert.create ~f ~on_observability_change in
let node = create_node state (Expert e) in
if debug
then
if Option.is_some state.only_in_debug.currently_running_node
then
state.only_in_debug.expert_nodes_created_by_current_node
<- T node :: state.only_in_debug.expert_nodes_created_by_current_node;
node
;;
let currently_running_node_exn state name =
match state.only_in_debug.currently_running_node with
| None ->
raise_s [%sexp ("can only call " ^ name ^ " during stabilization" : string)]
| Some current -> current
;;
let assert_currently_running_node_is_child state node name =
let (T current) = currently_running_node_exn state name in
if not (Node.has_child node ~child:current)
then
raise_s
[%sexp
("can only call " ^ name ^ " on parent nodes" : string)
, ~~(node.kind : _ Kind.t)
, ~~(current.kind : _ Kind.t)]
;;
let assert_currently_running_node_is_parent state node name =
let (T current) = currently_running_node_exn state name in
if not (Node.has_parent ~parent:current node)
then
raise_s
[%sexp
("can only call " ^ name ^ " on children nodes" : string)
, ~~(node.kind : _ Kind.t)
, ~~(current.kind : _ Kind.t)]
;;
let make_stale state node =
let e_opt = expert_kind_of_node node in
if Uopt.is_some e_opt
then (
if debug then assert_currently_running_node_is_child state node "make_stale";
let e = Uopt.unsafe_value e_opt in
match Expert.make_stale e with
| `Already_stale -> ()
| `Ok ->
if Node.is_necessary node && not (Node.is_in_recompute_heap node)
then Recompute_heap.add state.recompute_heap node)
;;
let invalidate state node =
if debug then assert_currently_running_node_is_child state node "invalidate";
invalidate_node state node;
propagate_invalidity state
;;
let add_dependency state node (dep : _ Expert.edge) =
let e_opt = expert_kind_of_node node in
if Uopt.is_some e_opt
then (
if debug
then
if am_stabilizing state
&& not
(List.mem
~equal:phys_equal
state.only_in_debug.expert_nodes_created_by_current_node
(T node))
then assert_currently_running_node_is_child state node "add_dependency";
let e = Uopt.unsafe_value e_opt in
let new_child_index = Expert.add_child_edge e (E dep) in
if Node.is_necessary node
then (
add_parent state ~child:dep.child ~parent:node ~child_index:new_child_index;
if debug then assert (Node.needs_to_be_computed node);
if not (Node.is_in_recompute_heap node)
then Recompute_heap.add state.recompute_heap node))
;;
let remove_dependency state node (edge : _ Expert.edge) =
let e_opt = expert_kind_of_node node in
if Uopt.is_some e_opt
then (
if debug then assert_currently_running_node_is_child state node "remove_dependency";
let e = Uopt.unsafe_value e_opt in
assert (Node.is_necessary node);
let edge_index = Uopt.value_exn edge.index in
let (E last_edge) = Expert.last_child_edge_exn e in
let last_edge_index = Uopt.value_exn last_edge.index in
if edge_index <> last_edge_index
then (
Node.swap_children_except_in_kind
node
~child1:edge.child
~child_index1:edge_index
~child2:last_edge.child
~child_index2:last_edge_index;
Expert.swap_children e ~child_index1:edge_index ~child_index2:last_edge_index;
if debug then Node.invariant ignore node);
Expert.remove_last_child_edge_exn e;
remove_child state ~child:edge.child ~parent:node ~child_index:last_edge_index;
if debug then assert (Node.needs_to_be_computed node);
if not (Node.is_in_recompute_heap node)
then Recompute_heap.add state.recompute_heap node;
if not (Node.is_valid edge.child) then Expert.decr_invalid_children e)
;;
end