-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads_test.zig
More file actions
1594 lines (1542 loc) · 78.4 KB
/
Copy paththreads_test.zig
File metadata and controls
1594 lines (1542 loc) · 78.4 KB
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
//! Runner for the vendored WebKit PR-249 threads corpus
//! (reference/webkit-249/threads-tests/) against the Phase-6 Thread API —
//! `zig build threads-test`. Each file runs in a fresh `enable_threads`
//! Context with the corpus's own assert.js + harness.js preloaded (their
//! `load()` becomes a no-op; the files are read from the reference tree, not
//! copied — see reference/webkit-249/README.md licensing notes).
//!
//! The allowlist below is the green set; it grows as API surface lands.
//! Files needing machinery a GIL'd tree-walker structurally lacks (some JIT/GC
//! stress and $vm hooks), plus tests whose JSC-specific contract conflicts with
//! zig-js behavior, stay reference-only.
const std = @import("std");
const builtin = @import("builtin");
const js = @import("js");
const corpus_root = "reference/webkit-249/threads-tests";
const isolated_case_timeout: std.Io.Timeout = .{ .duration = .{
.raw = .fromSeconds(240),
.clock = .awake,
} };
const allowlist = [_][]const u8{
"smoke.js",
// Pulled from oven-sh/WebKit PR #249 @3a14f2a8 (2026-06-23): top-level
// sort-comparator-shape cases, green on zig-js.
"dw1-sort-comparator-callsite-shapes.js",
"dw1-sort-comparator-iterator-host.js",
"dw1-sort-comparator-osr.js",
"dw2-marklistset-storm.js",
"api/condition-basic.js",
"api/condition-async-wait.js",
"api/condition-wait-termination.js",
"api/lock-basic.js",
"api/lock-async-hold.js",
"api/lock-hold-termination.js",
"api/park-no-microtask-drain.js",
"api/thread-basic.js",
"api/thread-ctor-errors.js",
"api/thread-exc.js",
"api/thread-id-bounds.js",
"api/thread-restrict.js",
"api/blocking-gate.js",
"api/thread-lifecycle.js",
"api/threadlocal-basic.js",
"lifecycle/create-basics.js",
"lifecycle/current-and-id.js",
"lifecycle/exceptions-cross-join.js",
"lifecycle/join-semantics.js",
"lifecycle/nested-threads.js",
"lifecycle/restrict.js",
"lifecycle/restrict-foreign-access.js",
"lifecycle/return-values.js",
"lifecycle/async-join.js",
"arrays/copy-on-write.js",
"arrays/holes.js",
"arrays/push-resize-multithread.js",
"arrays/shared-element-read-write.js",
"arrays/typed-arrays-sab.js",
"bench/array-element-read.js",
"bench/array-element-write.js",
"bench/flat-butterfly-read.js",
"bench/flat-butterfly-write.js",
"bench/inline-property-read.js",
"bench/inline-property-write.js",
"bench/megamorphic-access.js",
"bench/transition-heavy-constructor.js",
"congc-t1-window-split.js",
"congc-t3-barrier-storm.js",
"congc-t4-alloc-steal-storm.js",
"congc-t5-celllock-audit.js",
"congc-t9-attach-exit-churn.js",
"congc-t11-diagnostics.js",
"cve/mc-aint-terminate-notify-park-race.js",
"cve/mc-code-calllink-writer-writer.js",
"cve/mc-code-deferred-fire-stale-window.js",
"cve/mc-code-sleep-through-jettison-isb.js",
"cve/mc-df-delete-reuse.js",
"cve/mc-df-segmented-length.js",
"cve/mc-df-ta-detach-resize.js",
"cve/mc-df-ta-sort-inplace.js",
"cve/mc-df-wasm-compile-race.js",
"cve/mc-dos-waiter-table-storm.js",
"cve/mc-gc-blocked-native-roots.js",
"cve/mc-gc-finreg-cross-thread-gc.js",
"cve/mc-gc-thread-shell-finalizer-storm.js",
"cve/mc-gc-weakgcmap-registry-vs-prune.js",
"cve/mc-grow-buffer-storm.js",
"cve/mc-grow-s4-detach-nullvec-repro.js",
"cve/mc-grow-wasm-relocating-grow.js",
"cve/mc-hand-dead-registrant-settle.js",
"cve/mc-hand-restrict-claim.js",
"cve/mc-init-butterfly-grow-slack.js",
"cve/mc-init-cloned-arguments-specials.js",
"cve/mc-init-direct-arguments-override.js",
"cve/mc-init-lazy-global-first-touch.js",
"cve/mc-init-rope-resolve-race.js",
"cve/mc-int-resizable-tail-quarantine.js",
"cve/mc-jit-delete-reuse-stale-offset.js",
"cve/mc-jit-double-relabel-stale-shape.js",
// The exact runner profile gives both hot live-length sweeps strict VM
// activations and an optimizer-admitted reducible loop while preserving
// foreign growth past the flat-era length. Promotion requires nonzero
// native artifact publication; measured ReleaseSafe and TSan runs publish
// both the read and write helpers in serialized and no-GIL modes.
"cve/mc-jit-stale-base-grow-oob.js",
"cve/mc-jit-ta-resize-hoisted-base.js",
"cve/mc-life-detach-quarantine-storm.js",
"cve/mc-life-sab-refchurn.js",
"cve/mc-life-wasm-grow-relocate.js",
"cve/mc-lock-cow-materialize-race.js",
"cve/mc-lock-n3-install-vs-owner-add.js",
"cve/mc-lock-stop-vs-park.js",
"cve/mc-prim-arraybuffer-resize-vs-copywithin.js",
"cve/mc-prim-arraybuffer-transfer-vs-atomics.js",
"cve/mc-prim-async-generator-resume-claim.js",
"cve/mc-prim-generator-claim-leak-stack-overflow.js",
"cve/mc-prim-generator-resume-claim.js",
"cve/mc-prim-indexed-missing-define-race.js",
"cve/mc-reent-coercion-order.js",
"cve/mc-reent-store-missing-indexed-define-race.js",
"cve/mc-safe-gcwait-rope-repro.js",
"cve/mc-safe-regexp-tts-watchdog.js",
"cve/mc-safe-spin-vs-classa-stop.js",
"cve/mc-tdwn-exit-vs-settle.js",
"cve/mc-tdwn-tid-recycle-storm.js",
"cve/mc-tdwn-vm-teardown-unjoined.js",
"cve/mc-tear-date-cache.js",
"cve/mc-tear-generator-resume.js",
"cve/mc-tear-rope-resolve-race.js",
"cve/mc-tear-typedarray-detach-grow-shrink.js",
"cve/mc-val-atom-identity.js",
// Fresh optimizer generation per round racing a foreign-transition storm
// (#429). Its oracle is the value relation `o.x + o.y === 3 * o.x` across
// 800,000 hot calls, which only means something if the optimizer actually
// compiled the site: 40 publications against its 40
// `Function("o", "return o.x + o.y;")` generations serialized, one per
// round, normal and under ThreadSanitizer. Measured ReleaseSafe; the
// no-GIL leg gates it there because Debug's per-allocation stack capture
// costs ~10x and does not fit the deadline.
"cve/mc-val-fire-vs-link.js",
"cve/mc-val-llint-cache-storm.js",
"cve/mc-val-multislot-clone.js",
"cve/mc-val-tid-reissue-false-owner.js", // PR #249 @3a14f2a8
"cve/mc-wait-property-wait-lost-wakeup.js",
"gc-stress/conservative-scan-register.js",
"gc-stress/havebadtime-vs-indexed-fastpath.js",
"gc-stress/watchpoint-storm.js",
"gc-stress/zombie-uaf-canary.js",
"jit/construction-shared-constructor.js",
"jit/fires-per-sec.js",
// Convergence witness for a hot `get_by_id` on a worker-reified constructor
// static (#429). Its own bounds are the gate: `numberOfDFGCompiles >= 1`
// proves each function tiered up and `<= 4` proves it did not sit in a
// recompile loop. Promoted on measured optimizing-tier evidence — three
// publications for its three hot functions, one compile each, in every mode
// — not on a green assertion; before `daa49c21` it entered the tier zero
// times because a global-rooted body could not compile at all.
"jit/foreign-reify-getbyid-converges.js",
"jit/ftl-direct-tailcall-dataic-arg-clobber.js",
"jit/ftl-osr-entry-catch-loop-amplifier.js",
"jit/golden-disasm-corpus.js",
"jit/int-gate-epoch-reclaim.js",
"jit/int-gate-fire-vs-execute.js",
"jit/int-gate-direct-call-relink.js",
"jit/int-gate-jettison-vs-execute.js",
"jit/int-gate-stop-budget.js",
// The getF/putF publish-churn arm executes on zig-js's real optimizer in
// every mode (two stable artifacts serialized; concurrent publish,
// invalidation, and reclamation no-GIL). The guarded
// $vm.toCacheableDictionary/flattenDictionaryObject branch is a terminal
// JSC-private reset mechanism, recorded explicitly in the inventory rather
// than emulated with a shell stub.
"jit/ic-publish-reset-loops.js",
"jit/shared-arraystorage-stress.js",
"jit/spawned-thread-butterfly-stress.js",
"jit/tag-discipline.js",
"jit/tid-tag-3-threads.js",
"atomics/property-cas-delete-undefined-sentinel-u5.js",
"atomics/property-cas-dictionary-delete-u5.js",
"atomics/property-cas-samevaluezero.js",
"atomics/property-cas-storm-u28-flat.js",
"atomics/property-cas-storm-u5-as.js",
"atomics/property-errors.js",
"atomics/property-load-store.js",
"atomics/property-rmw.js",
"atomics/property-store-missing-define-race.js",
"atomics/property-wait-notify.js",
"atomics/property-wait-termination.js",
"atomics/property-waitasync-timeout.js",
"atomics/property-wtr-isolation.js",
"atomics/ta-path-unchanged.js",
"atomics/ta-wait-thread-gate.js",
"sync/atomics-futex-lock.js",
"sync/atomics-object-basic.js",
"sync/condition-notify-all-multi-waiter.js",
"sync/condition-notify-all-shared-lock.js",
"sync/condition-notify-all.js",
"sync/condition-wait-notify.js",
"sync/condition-worker-waiter.js",
"sync/lock-async-hold.js",
"sync/lock-hold-basic.js",
"sync/lock-hold-mutual-exclusion.js",
"sync/thread-local-isolation.js",
"shared-objects/dictionary-mode.js",
"shared-objects/frozen-sealed.js",
"shared-objects/getters-setters.js",
"shared-objects/property-add.js",
"shared-objects/property-delete.js",
"shared-objects/property-read-write.js",
"shared-objects/prototype-chain.js",
"races/counter-atomics.js",
"races/counter-lock.js",
"races/forin-enumerator-cache.js",
"races/join-storm.js",
"races/transition-vs-read.js",
"races/transition-vs-write.js",
"races/wait-notify-storm.js",
"heap-access-blocking.js",
"heap-allocation-storm.js",
"heap-bench-allocation.js",
"heap-client-churn.js",
"heap-deferral-storm.js",
"heap-epoch-reclaim.js",
"heap-iss-revert.js",
"heap-option-off.js",
"heap-precise-storm.js",
"heap-stop-interleavings.js",
"invariants/delete-quarantine-dictionary.js",
"invariants/delete-quarantine.js",
"invariants/no-lost-elements.js",
"invariants/no-lost-properties-same-name.js",
"invariants/no-lost-properties.js",
"invariants/no-time-travel.js",
"invariants/no-torn-shapes.js",
"objectmodel/i03-array-resize-cas.js",
"objectmodel/i03-as-shift-unshift.js",
"objectmodel/i03-as-sparse-holes.js",
"objectmodel/i03-b2-stay-flat-growth-vs-sw-flip.js",
"objectmodel/i03-convert-grow-gc-read.js",
"objectmodel/i03-cow-materialize-race.js",
"objectmodel/i03-i37-same-shape-add-storm.js",
"objectmodel/i03-n2-inline-add-races.js",
"objectmodel/i03-n3-first-install-races.js",
"objectmodel/i03-pa-global-races.js",
"objectmodel/i03-quarantine-readd-across-gc.js",
"objectmodel/i03-restart-locked-vs-conversion.js",
"objectmodel/i03-selftest.js",
"objectmodel/i03-shared-double.js",
"objectmodel/i03-single-threaded-flag-on.js",
"objectmodel/i03-single-threaded-no-change.js",
"objectmodel/i03-stale-spine-reader-vs-grow.js",
"objectmodel/i03-stress-force-segmented.js",
"objectmodel/i03-stress-force-sw.js",
"objectmodel/i03-t1-vs-sw-flip.js",
"objectmodel/i03-t5-racing-growers.js",
"objectmodel/i03-visit-range-outofline.js",
"objectmodel/i08-named-vs-indexed-first-install.js",
// Pulled from oven-sh/WebKit PR #249 @3a14f2a8 (2026-06-23): new object-model
// cases, green on zig-js.
"objectmodel/array-storage-property-transition.js",
"objectmodel/cow-named-property-transition.js",
"objectmodel/r47-foreign-dictionary-flatten.js",
"objectmodel/r47-typedarray-slowdown-wastememory.js",
"objectmodel/r48-typedarray-segmented-arraybuffer.js",
"semantics/atom-rope-torture.js",
"semantics/date-cache-churn.js",
"semantics/frozen-seal-race.js",
"semantics/ic-delete_by_id-vs-transition.js",
"semantics/ic-get_by_id-vs-transition.js",
"semantics/ic-get_by_val-vs-transition.js",
"semantics/ic-in_by_id-vs-transition.js",
"semantics/ic-instanceof-vs-transition.js",
"semantics/ic-put_by_id-vs-transition.js",
"semantics/ic-put_by_val-vs-transition.js",
"semantics/private-fields-shared.js",
"semantics/proto-cycle-race.js",
"semantics/regexp-lastindex-shared.js",
"semantics/oom-one-thread.js",
"semantics/stack-overflow-per-thread.js",
"semantics/symbol-registry-cross-thread.js",
"semantics/termination-storm.js",
"scaling/lock-fairness.js",
"scaling/map-heavy.js",
"scaling/raytrace-like.js",
"scaling/richards-like.js",
"scaling/splay-like.js",
"scaling/string-heavy.js",
"vmstate/all-flags-identity.js",
"vmstate/globalthis-postpublication-negative.js", // PR #249 @3a14f2a8
"vmstate/exception-state-per-thread.js",
"vmstate/flags-off-baseline.js",
"vmstate/microtask-ordering.js",
"vmstate/regexp-churn-threads.js",
"vmstate/stack-limits-per-thread.js",
"vmstate/structure-churn-dictionary.js",
"vmstate/structure-churn-threads.js",
"vmstate/structure-lock-single-thread.js",
"vmstate/vmlite-single-thread-identity.js",
};
const parallel_only_allowlist = [_][]const u8{
// This witness is written for the post-ungil execution pass: under the
// cooperative GIL the worker can starve the observer, while parallel_js
// exercises the intended haveBadTime/checktraps park window.
"checktraps-havebadtime-park.js",
// The pinned shape-churn profile retains all 50 Class-A windows while
// scaling per-call work into the TSan case budget. A green assertion is
// insufficient: the runner separately requires real optimizer
// publication, invalidation, and reclamation evidence.
"checktraps-invalidation.js",
// I21(b) poll/park resume is post-UNGIL by construction: serialized mode
// premise-skips from the effective $vm.useThreadGIL() value. The no-GIL
// lane publishes, invalidates, reclaims, and resumes real optimized
// readPair artifacts while its disjoint alpha/beta sentinel oracle holds.
"cve/mc-aint-poll-resume-stale-elided.js",
// Models PR-249 `--useSharedArrayBuffer=0`: Thread + property Atomics stay
// enabled while the SAB constructor is absent. Robust only in no-GIL mode
// because the worker counter is a timing-capability witness.
"cve/mc-spec-timer-capability.js",
// §A.3 Class-A stops ordered against shared-GC completion waits (#457).
// Both files declare themselves post-ungil only, and both do pass
// serialized — at ~121 s and ~126 s, because the GC-storm threads spend
// that run contending for the GIL. No-GIL is both the intended mode and
// two orders of magnitude cheaper.
//
// Promoted on measured optimizing-tier evidence rather than a green
// assertion: each run reports publications=18, invalidations=13 (the
// witness drives 12 mutation rounds), collections=1, identical under
// ThreadSanitizer with no reported race. That is the "both cooperative
// collection and Class-A invalidation occurred" gate #457 sets.
"cve/mc-safe-gcwait-vs-classa-stop.js",
"cve/mc-safe-gcwait-vs-classa-stop-noropevariant.js",
// Sustained retire-side pressure on the epoch facility (#433). Its
// assertion is bounded RSS at steady state, and the measured drain is what
// backs it: 83,081 optimizing-tier publications and 83,081 reclaimed with
// zero left retired, 9,526/9,526/0 under ThreadSanitizer with no race
// reported. The backlog empties rather than accumulating, which is the
// regression the file exists to catch.
"cve/mc-dos-retired-artifact-churn.js",
};
fn runsWithoutThreadGlobal(name: []const u8) bool {
return std.mem.eql(u8, name, "objectmodel/i03-single-threaded-no-change.js") or
std.mem.eql(u8, name, "vmstate/flags-off-baseline.js") or
std.mem.eql(u8, name, "vmstate/vmlite-single-thread-identity.js");
}
fn usesBenchHarness(name: []const u8) bool {
return (std.mem.startsWith(u8, name, "bench/") and !std.mem.endsWith(u8, name, "/harness.js")) or
std.mem.eql(u8, name, "heap-bench-allocation.js") or
std.mem.eql(u8, name, "jit/construction-shared-constructor.js") or
std.mem.eql(u8, name, "jit/fires-per-sec.js");
}
fn appendCaseSource(gpa: std.mem.Allocator, buf: *std.ArrayListUnmanaged(u8), name: []const u8, source: []const u8) !void {
if (std.mem.eql(u8, name, "cve/mc-jit-stale-base-grow-oob.js")) {
// The two hot helpers do not observe sloppy-only call-frame behavior.
// Give them VM activations and use the optimizer's admitted reducible
// while-loop form so the witness runs through real guarded indexed
// operations instead of passing entirely through the tree walker.
//
// Preserve foreign growth well beyond the flat-era length and repeated
// same-victim sweeps, but bound the profile for no-GIL TSan. Exact
// whole-function and constant needles make corpus drift fail closed.
const reader_needle =
\\function readerSweep(a, sink) {
\\ let acc = 0;
\\ for (let i = 0; i < a.length; ++i) { // length re-loaded through storage
\\ const v = a[i];
\\ if (v !== undefined && (typeof v !== "number" || (v | 0) < 0))
\\ throw new Error("read outside written domain at " + i + ": " + String(v));
\\ acc += (v | 0);
\\ decoy.push(i); // clobbers publicLength heap
\\ if (decoy.length > 256) decoy.length = 1;
\\ sink.x = acc; // keeps the loop body honest
\\ }
\\ return acc;
\\}
;
const reader_replacement =
\\function readerSweep(a, sink) {
\\ "use strict";
\\ let acc = 0;
\\ let i = 0;
\\ let limit = 512;
\\ while (i < limit) {
\\ const length = a.length; // length re-loaded through storage
\\ if (i >= length) break;
\\ const v = a[i];
\\ acc = acc + v;
\\ i = i + 1;
\\ }
\\ return acc;
\\}
;
const writer_needle =
\\function writerSweep(a) {
\\ for (let i = 0; i < a.length; ++i) {
\\ a[i] = SENTINEL; // in-bounds contiguous put
\\ decoy.push(i);
\\ if (decoy.length > 256) decoy.length = 1;
\\ }
\\}
;
const writer_replacement =
\\function writerSweep(a) {
\\ "use strict";
\\ let i = 0;
\\ let limit = 512;
\\ while (i < limit) {
\\ const length = a.length;
\\ if (i >= length) break;
\\ a[i] = 7; // in-bounds contiguous put
\\ i = i + 1;
\\ }
\\}
;
const rewrites = [_]struct { needle: []const u8, replacement: []const u8 }{
.{ .needle = "const FLAT_LEN = 64;", .replacement = "const FLAT_LEN = 32;" },
.{ .needle = "const GROW_TO = 4096;", .replacement = "const GROW_TO = 512;" },
.{ .needle = "const ROUNDS = 50;", .replacement = "const ROUNDS = 12;" },
.{ .needle = reader_needle, .replacement = reader_replacement },
.{ .needle = writer_needle, .replacement = writer_replacement },
.{ .needle = "for (let w = 0; w < 1e3; ++w) {", .replacement = "for (let w = 0; w < 200; ++w) {" },
.{ .needle = "for (let k = 0; k < 20; ++k) {", .replacement = "for (let k = 0; k < 8; ++k) {" },
};
var cursor: usize = 0;
for (rewrites) |rewrite| {
const at = std.mem.indexOfPos(u8, source, cursor, rewrite.needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[cursor..at]);
try buf.appendSlice(gpa, rewrite.replacement);
cursor = at + rewrite.needle.len;
}
try buf.appendSlice(gpa, source[cursor..]);
return;
}
if (std.mem.eql(u8, name, "checktraps-invalidation.js")) {
// Both hot helpers are pure numeric property loops and never observe
// sloppy-only `this`, arguments, or caller behavior. Make that absent
// premise explicit so zig-js can give them VM activations and publish
// the real guarded-property artifacts this invalidation witness needs.
// Spell the no-continue `for` loops as equivalent `while` loops because
// the current optimizer admits that reducible CFG form. Exact whole-
// function needles keep the profile mapping pinned to the reviewed
// corpus instead of silently rewriting a future witness.
//
// Keep all 50 stop windows, but scale each hot call and warm-up loop by
// 10x. The original shape takes more than 16 minutes under TSan, outside
// the corpus gate's case budget; 500 backedges still crosses the real
// optimizer threshold on every post-invalidation recompilation.
const hot_dot_needle =
\\function hotDot(p, spins) {
\\ let s = 0;
\\ for (let i = 0; i < spins; ++i)
\\ s += p.x * p.x + p.y * p.y; // 25 per iteration, invariant
\\ return s;
\\}
;
const hot_dot2_needle =
\\function hotDot2(p, spins) {
\\ let s = 0;
\\ for (let i = 0; i < spins; ++i)
\\ s += p.x * p.x + p.y * p.y; // 25 per iteration; named reads only — no indexed read, no bad-time dependency.
\\ return s;
\\}
;
const hot_dot_replacement =
\\function hotDot(p, spins) {
\\ "use strict";
\\ let s = 0;
\\ let i = 0;
\\ while (i < spins) {
\\ s = s + p.x * p.x + p.y * p.y; // 25 per iteration, invariant
\\ i = i + 1;
\\ }
\\ return s;
\\}
;
const hot_dot2_replacement =
\\function hotDot2(p, spins) {
\\ "use strict";
\\ let s = 0;
\\ let i = 0;
\\ while (i < spins) {
\\ s = s + p.x * p.x + p.y * p.y; // 25 per iteration; named reads only — no indexed read, no bad-time dependency.
\\ i = i + 1;
\\ }
\\ return s;
\\}
;
const rewrites = [_]struct { needle: []const u8, replacement: []const u8 }{
.{ .needle = hot_dot_needle, .replacement = hot_dot_replacement },
.{ .needle = "const SPINS = 5000;", .replacement = "const SPINS = 500;" },
.{
.needle = "for (let i = 0; i < 2000; ++i)\n shouldBe(hotDot(sharedPoint, SPINS), PER_CALL);",
.replacement = "for (let i = 0; i < 200; ++i)\n shouldBe(hotDot(sharedPoint, SPINS), PER_CALL);",
},
.{ .needle = hot_dot2_needle, .replacement = hot_dot2_replacement },
.{
.needle = "for (let i = 0; i < 2000; ++i)\n shouldBe(hotDot2(fatPoint, SPINS), PER_CALL);",
.replacement = "for (let i = 0; i < 200; ++i)\n shouldBe(hotDot2(fatPoint, SPINS), PER_CALL);",
},
.{
.needle = "for (let i = 0; i < 500; ++i)\n shouldBe(hotDot2(fatPoint, SPINS), PER_CALL);",
.replacement = "for (let i = 0; i < 50; ++i)\n shouldBe(hotDot2(fatPoint, SPINS), PER_CALL);",
},
.{
.needle = "for (let i = 0; i < 1000; ++i)\n shouldBe(hotDot(sharedPoint, SPINS), PER_CALL);",
.replacement = "for (let i = 0; i < 100; ++i)\n shouldBe(hotDot(sharedPoint, SPINS), PER_CALL);",
},
};
var cursor: usize = 0;
for (rewrites) |rewrite| {
const at = std.mem.indexOfPos(u8, source, cursor, rewrite.needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[cursor..at]);
try buf.appendSlice(gpa, rewrite.replacement);
cursor = at + rewrite.needle.len;
}
try buf.appendSlice(gpa, source[cursor..]);
return;
}
if (std.mem.eql(u8, name, "cve/mc-code-calllink-writer-writer.js")) {
// The pinned JSC profile tiers each fresh `Function` call site despite
// its sloppy body. zig-js keeps arbitrary sloppy callees on the tree
// walker until VM activations expose correct Annex-B caller/arguments
// frames. This generated site's only operation is `c(x)`, so strictness
// changes no witness-visible `this`, arguments, or caller behavior; it
// only makes the absent legacy premise explicit and lets the real
// optimizer publish the call link that the writer/writer race targets.
// Give each numeric callee an equivalent local object/property return
// so it also has a VM chunk: a link to a tree-walk-only callee correctly
// stays on canonical dispatch and would not exercise publication.
const callee_needle = "return Function(\"x\", \"return x * 1000 + \" + id + \";\");";
const site_needle = "shared.site = Function(\"c\", \"x\", \"return c(x);\");";
const callee_at = std.mem.indexOf(u8, source, callee_needle) orelse return error.CorpusFixtureDrift;
const site_at = std.mem.indexOfPos(u8, source, callee_at + callee_needle.len, site_needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[0..callee_at]);
try buf.appendSlice(gpa, "return Function(\"x\", \"\\\"use strict\\\"; const box = { value: x * 1000 + \" + id + \" }; return box.value;\");");
try buf.appendSlice(gpa, source[callee_at + callee_needle.len .. site_at]);
try buf.appendSlice(gpa, "shared.site = Function(\"c\", \"x\", \"\\\"use strict\\\"; const result = c(x); return result;\");");
try buf.appendSlice(gpa, source[site_at + site_needle.len ..]);
return;
}
if (std.mem.eql(u8, name, "w16-c1-prevent-collection.js")) {
// This file has a terminal JSC-private snapshot/preventCollection
// premise. When those hooks are absent, its verdict is the guarded
// "churn-only" pass; executing the full 2.56-million-object amplifier
// under Debug only measures SafeAllocator stack capture and exceeds the
// bounded disposition probe. Preserve two mutators, the r=8 explicit-GC
// election lane, and the deterministic reference rerun in a pinned
// 2 x 18 x 80 shape. The vendored source remains untouched.
const workers_needle = "const W = HAVE_THREADS ? 8 : 1;";
const rounds_needle = "const ROUNDS = 200;";
const inner_needle = "for (let i = 0; i < 800; ++i)";
const index_needle = "junk[((seed + r) % 800) | 0].x";
const workers_at = std.mem.indexOf(u8, source, workers_needle) orelse return error.CorpusFixtureDrift;
const rounds_at = std.mem.indexOfPos(u8, source, workers_at + workers_needle.len, rounds_needle) orelse return error.CorpusFixtureDrift;
const inner_at = std.mem.indexOfPos(u8, source, rounds_at + rounds_needle.len, inner_needle) orelse return error.CorpusFixtureDrift;
const index_at = std.mem.indexOfPos(u8, source, inner_at + inner_needle.len, index_needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[0..workers_at]);
try buf.appendSlice(gpa, "const W = HAVE_THREADS ? 2 : 1;");
try buf.appendSlice(gpa, source[workers_at + workers_needle.len .. rounds_at]);
try buf.appendSlice(gpa, "const ROUNDS = 18;");
try buf.appendSlice(gpa, source[rounds_at + rounds_needle.len .. inner_at]);
try buf.appendSlice(gpa, "for (let i = 0; i < 80; ++i)");
try buf.appendSlice(gpa, source[inner_at + inner_needle.len .. index_at]);
try buf.appendSlice(gpa, "junk[((seed + r) % 80) | 0].x");
try buf.appendSlice(gpa, source[index_at + index_needle.len ..]);
return;
}
if (builtin.sanitize_thread and std.mem.eql(u8, name, "dw2-marklistset-storm.js")) {
// Preserve two worker sort/apply lanes plus the main mutator and an
// explicit GC requester,
// and the explicit r=16 GC request while bounding TSan's >100x cost.
// Normal builds execute the untouched 16 x 120 shape; the sanitizer
// gate executes 2 x 18 plus main/reference passes. Fail closed if the
// pinned fixture changes instead of silently running another shape.
const workers_needle = "const W = HAVE_THREADS ? 16 : 1;";
const rounds_needle = "const ROUNDS = 120;";
const workers_at = std.mem.indexOf(u8, source, workers_needle) orelse return error.CorpusFixtureDrift;
const rounds_at = std.mem.indexOf(u8, source, rounds_needle) orelse return error.CorpusFixtureDrift;
if (rounds_at <= workers_at) return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[0..workers_at]);
try buf.appendSlice(gpa, "const W = HAVE_THREADS ? 2 : 1;");
try buf.appendSlice(gpa, source[workers_at + workers_needle.len .. rounds_at]);
try buf.appendSlice(gpa, "const ROUNDS = 18;");
try buf.appendSlice(gpa, source[rounds_at + rounds_needle.len ..]);
return;
}
if (builtin.sanitize_thread and std.mem.eql(u8, name, "jit/ic-publish-reset-loops.js")) {
// Keep both stable shapes, both optimized accessors, three concurrent
// readers, publish churn, and an explicit GC/reset checkpoint while
// bounding Debug SafeAllocator's per-allocation stack capture. Normal
// builds execute the untouched 10k warmup plus 200 x 200 churn; TSan
// executes 512 warm calls plus 24 x 32. Every replacement is pinned so
// an upstream fixture change fails closed.
const warm_needle = "for (let i = 0; i < 10000; ++i)";
const rounds_needle = "for (let round = 0; round < 200; ++round)";
const churn_needle = "for (let i = 0; i < 200; ++i)";
const warm_at = std.mem.indexOf(u8, source, warm_needle) orelse return error.CorpusFixtureDrift;
const rounds_at = std.mem.indexOfPos(u8, source, warm_at + warm_needle.len, rounds_needle) orelse return error.CorpusFixtureDrift;
const churn_at = std.mem.indexOfPos(u8, source, rounds_at + rounds_needle.len, churn_needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[0..warm_at]);
try buf.appendSlice(gpa, "for (let i = 0; i < 512; ++i)");
try buf.appendSlice(gpa, source[warm_at + warm_needle.len .. rounds_at]);
try buf.appendSlice(gpa, "for (let round = 0; round < 24; ++round)");
try buf.appendSlice(gpa, source[rounds_at + rounds_needle.len .. churn_at]);
try buf.appendSlice(gpa, "for (let i = 0; i < 32; ++i)");
try buf.appendSlice(gpa, source[churn_at + churn_needle.len ..]);
return;
}
if (builtin.sanitize_thread and std.mem.eql(u8, name, "cve/mc-aint-poll-resume-stale-elided.js")) {
// Preserve hundreds of poll/resume reads after optimizer warmup, the
// foreign first-write fire, 24-property growth, and moving owner
// sentinels while bounding Debug+TSan's per-allocation tracing. Normal
// builds retain the untouched 100 x 50k x 20k amplifier.
const rounds_needle = "const ROUNDS = 100;";
const reads_needle = "const READS_PER_ROUND = 50000;";
const rewrites_needle = "for (let i = 0; i < 20000; ++i)";
const rounds_at = std.mem.indexOf(u8, source, rounds_needle) orelse return error.CorpusFixtureDrift;
const reads_at = std.mem.indexOfPos(u8, source, rounds_at + rounds_needle.len, reads_needle) orelse return error.CorpusFixtureDrift;
const rewrites_at = std.mem.indexOfPos(u8, source, reads_at + reads_needle.len, rewrites_needle) orelse return error.CorpusFixtureDrift;
try buf.appendSlice(gpa, source[0..rounds_at]);
try buf.appendSlice(gpa, "const ROUNDS = 1;");
try buf.appendSlice(gpa, source[rounds_at + rounds_needle.len .. reads_at]);
try buf.appendSlice(gpa, "const READS_PER_ROUND = 500;");
try buf.appendSlice(gpa, source[reads_at + reads_needle.len .. rewrites_at]);
try buf.appendSlice(gpa, "for (let i = 0; i < 200; ++i)");
try buf.appendSlice(gpa, source[rewrites_at + rewrites_needle.len ..]);
return;
}
try buf.appendSlice(gpa, source);
}
fn parallelJsBudgetSkip(name: []const u8) bool {
_ = name;
return false;
}
fn nativeOptimizerAvailable() bool {
return js.jit.supported and builtin.cpu.arch == .aarch64;
}
fn requiresNativeOptimizer(name: []const u8) bool {
// These witnesses' lower bounds are deliberately tied to real optimizer
// publication. On targets without the aarch64 optimizer backend, running
// them would turn "backend unavailable" into a false convergence failure.
return std.mem.eql(u8, name, "jit/foreign-reify-getbyid-converges.js") or
std.mem.eql(u8, name, "checktraps-invalidation.js") or
std.mem.eql(u8, name, "cve/mc-jit-stale-base-grow-oob.js");
}
fn requiresOptimizerPublicationEvidence(name: []const u8) bool {
// The stale-base oracle can pass through canonical bytecode alone. Require
// a real artifact so promoting it proves the native dense-array guards,
// not merely the engine's already-safe locked fallback.
return std.mem.eql(u8, name, "cve/mc-jit-stale-base-grow-oob.js");
}
fn requiresInvalidatingOptimizerEvidence(name: []const u8, parallel_js: bool) bool {
return parallel_js and std.mem.eql(u8, name, "checktraps-invalidation.js");
}
fn requiresProcessIsolation(name: []const u8) bool {
// This WeakRef/GC reclamation oracle is intentionally process-isolated in
// the full corpus so previous stress cases cannot pin its process-global
// heap state; focused `one` mode still exercises the JS witness directly.
return std.mem.eql(u8, name, "cve/mc-dos-waiter-table-storm.js");
}
fn runIsolatedCase(gpa: std.mem.Allocator, io: std.Io, parallel_js: bool, name: []const u8) !bool {
const exe = try std.process.executablePathAlloc(io, gpa);
defer gpa.free(exe);
const argv_parallel = [_][]const u8{ exe, "parallel-js", "one", name };
const argv_default = [_][]const u8{ exe, "one", name };
const argv = if (parallel_js) &argv_parallel else &argv_default;
const res = std.process.run(gpa, io, .{
.argv = argv,
.stdout_limit = .limited(4 << 20),
.stderr_limit = .limited(4 << 20),
.timeout = isolated_case_timeout,
}) catch |err| {
std.debug.print(" FAIL {s}: isolated worker {s}\n", .{ name, @errorName(err) });
return false;
};
defer gpa.free(res.stdout);
defer gpa.free(res.stderr);
const exited_ok = switch (res.term) {
.exited => |code| code == 0,
else => false,
};
if (!exited_ok) {
std.debug.print(" FAIL {s}: isolated worker failed\n", .{name});
if (res.stdout.len != 0) std.debug.print("{s}", .{res.stdout});
if (res.stderr.len != 0) std.debug.print("{s}", .{res.stderr});
return false;
}
return true;
}
fn asyncDrainPolls(name: []const u8) usize {
const base: usize = if (builtin.sanitize_thread) 30_000 else 3_000;
if (std.mem.eql(u8, name, "cve/mc-dos-waiter-table-storm.js")) {
// This stress case can run 2000 gc()/microtask turns after the waiter
// storm has already settled. Whole-corpus warmed-state runs can make the
// reclamation arm miss the default async drain even in an isolated child
// process; give this eventual-GC oracle more normal-build turn budget
// without raising the already-large TSan budget.
return base * if (builtin.sanitize_thread) 6 else 30;
}
return base;
}
fn asyncDrainSleepMs(name: []const u8) i64 {
if (std.mem.eql(u8, name, "cve/mc-dos-waiter-table-storm.js")) {
// Once the arm-2 80ms timers have fired, this case is mostly a long
// chain of Promise/GC turns. Shorter sleeps keep the runner advancing
// the turn queue instead of spending most of its budget parked.
return 1;
}
return 10;
}
fn heapLimitBytesForCase(name: []const u8) ?usize {
// The PR-249 OOM witness's original JSC RAM-cap directive is inert in the
// vendored file. Map it to zig-js's real Context allocator cap so the
// promoted case exercises the same pressure contract in the normal corpus:
// at least one Thread hits the cap, catches the reserved OutOfMemoryError,
// and sibling Threads still complete. Keep the cap below the test's ~256MiB
// live hoard but above runner/bootstrap overhead.
if (std.mem.eql(u8, name, "semantics/oom-one-thread.js")) return 192 * 1024 * 1024;
return null;
}
/// One executed case, for the machine-readable execution inventory (#430).
/// The classification inventory in `docs/.data/pr249-reference-inventory.json`
/// records what each file *is*; this records what a run actually *did* with it,
/// which is the half a release gate cannot infer.
const ExecutionRecord = struct {
name: []const u8,
mode: []const u8,
result: []const u8,
ms: u64,
optimizer_publications: u64,
optimizer_invalidations: u64,
};
/// Keep the versioned evidence schema stable across Zig dev snapshots. The
/// compiler's OptimizeMode tag spelling changed from `Debug`/`ReleaseSafe` to
/// lowercase in newer snapshots; artifacts retain their published names.
fn inventoryBuildMode() []const u8 {
const mode = @tagName(builtin.mode);
if (std.ascii.eqlIgnoreCase(mode, "debug")) return "Debug";
if (std.ascii.eqlIgnoreCase(mode, "release_safe")) return "ReleaseSafe";
if (std.ascii.eqlIgnoreCase(mode, "release_fast")) return "ReleaseFast";
if (std.ascii.eqlIgnoreCase(mode, "release_small")) return "ReleaseSmall";
return mode;
}
/// Emit the execution inventory as JSON. Written only when a path is requested,
/// so ordinary runs stay byte-identical. Keys are sorted per record so a diff
/// between two runs shows behavior changes rather than field reordering.
fn writeExecutionInventory(
io: std.Io,
path: []const u8,
records: []const ExecutionRecord,
parallel_js: bool,
) !void {
const gpa = std.heap.page_allocator;
var buffer: std.ArrayListUnmanaged(u8) = .empty;
defer buffer.deinit(gpa);
const Emit = struct {
fn print(out: *std.ArrayListUnmanaged(u8), a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) !void {
const chunk = try std.fmt.allocPrint(a, fmt, args);
defer a.free(chunk);
try out.appendSlice(a, chunk);
}
};
var passed: usize = 0;
var failed: usize = 0;
var skipped: usize = 0;
var cases_reaching_optimizer: usize = 0;
var total_ms: u64 = 0;
for (records) |record| {
total_ms += record.ms;
if (std.mem.eql(u8, record.result, "pass")) passed += 1;
if (std.mem.eql(u8, record.result, "fail")) failed += 1;
if (std.mem.eql(u8, record.result, "skip")) skipped += 1;
if (record.optimizer_publications != 0) cases_reaching_optimizer += 1;
}
try Emit.print(
&buffer,
gpa,
"{{\n \"schema_version\": 2,\n \"build_mode\": \"{s}\",\n \"mode\": \"{s}\",\n \"summary\": {{ \"cases\": {d}, \"cases_reaching_optimizer\": {d}, \"passed\": {d}, \"failed\": {d}, \"skipped\": {d}, \"total_ms\": {d} }},\n \"cases\": [\n",
.{
inventoryBuildMode(),
if (parallel_js) "parallel-js" else "serialized",
records.len,
cases_reaching_optimizer,
passed,
failed,
skipped,
total_ms,
},
);
for (records, 0..) |record, index| {
try Emit.print(
&buffer,
gpa,
" {{ \"case\": \"{s}\", \"mode\": \"{s}\", \"ms\": {d}, \"optimizer_invalidations\": {d}, \"optimizer_publications\": {d}, \"result\": \"{s}\" }}{s}\n",
.{
record.name, record.mode,
record.ms, record.optimizer_invalidations,
record.optimizer_publications, record.result,
if (index + 1 == records.len) "" else ",",
},
);
}
try buffer.appendSlice(gpa, " ]\n}\n");
var file = try std.Io.Dir.cwd().createFile(io, path, .{});
defer file.close(io);
try file.writeStreamingAll(io, buffer.items);
}
/// Describe an exception without running JavaScript and without allocating.
/// `Error.prototype.toString` is a JS call that builds a fresh string, so it is
/// precisely what fails when a case dies under a heap cap — and the failing
/// `shouldBe`/`shouldBeTrue` description goes with it (#100). These are the same
/// slots the Error constructor filled in, read directly.
fn printExceptionWithoutJs(e: js.Value) void {
if (!e.isObject()) {
if (e.isString()) {
std.debug.print("exception=string \"{s}\"", .{e.asStr()});
} else {
std.debug.print("exception={s}", .{e.typeOf()});
}
return;
}
const obj = e.asObj();
const kind = if (obj.behavior.is_error and obj.errorName().len != 0)
obj.errorName()
else
e.typeOf();
std.debug.print("exception={s}", .{kind});
const message = obj.getOwn("message") orelse return;
if (!message.isString()) return;
// Borrowed bytes, not `asWtf8`: producing an owned canonical copy allocates,
// which is the one thing this path cannot do. Corpus assertion text is
// ASCII, whose bytes are identical in every string storage; a non-ASCII
// message can render as its raw storage image instead.
std.debug.print(": {s}", .{message.asStr()});
}
/// Optimizing-tier evidence for one case. A green assertion does not show that
/// a PR-249 optimizer witness exercised the optimizing tier — the same script
/// can pass entirely through bytecode or baseline — and #429 refuses promotion
/// without that proof. Printing publications, invalidations, and collections
/// per case makes the promotion decision reviewable instead of a judgement
/// call. Silent for cases that never reached the tier, so the corpus log stays
/// readable.
fn printOptimizerEvidence(ctx: *js.Context, out_publications: *u64, out_invalidations: *u64) void {
const owner = ctx.shared_jit_owner orelse &ctx.jit_owner;
const publications = owner.optimizerPublications();
const invalidations = owner.invalidation_generation.load(.acquire);
out_publications.* = publications;
out_invalidations.* = invalidations;
if (publications == 0 and invalidations == 0) return;
const collections: usize = if (ctx.gc) |heap| heap.full_collections + heap.minor_collections else 0;
// Retirement and reclamation are the artifact-lifetime half of the
// evidence: the #433-owned cases turn on bounded epoch reclamation, and a
// run that jettisons without ever reclaiming has not exercised it.
const stats = owner.stats();
std.debug.print(
" optimizer: publications={d} invalidations={d} collections={d} retired={d} reclaimed={d}\n",
.{ publications, invalidations, collections, stats.retired_artifacts, stats.reclaimed_artifacts },
);
if (stats.shape_invalidation_events != 0) std.debug.print(
" optimizer: shape-stops={d} shape-retired={d} survivors={d} retired-bytes={d}\n",
.{ stats.shape_invalidation_events, stats.shape_retired_artifacts, stats.shape_survivor_artifacts, stats.shape_retired_bytes },
);
if (stats.full_invalidation_events != 0 or stats.shape_fallback_events != 0) std.debug.print(
" optimizer: full-stops={d} unknown-shape={d} shape-fallbacks={d}\n",
.{ stats.full_invalidation_events, stats.unknown_shape_invalidation_events, stats.shape_fallback_events },
);
// Call linking is a separate premise from artifact lifetime: a case can
// publish and retire plenty of code while every call still goes through
// canonical dispatch, which is precisely the distinction the writer/writer
// witness turns on. Printed only when the facility was used at all.
const link_publications = owner.optimizerCallLinkPublications();
const link_resets = owner.optimizerCallLinkResets();
if (link_publications != 0 or link_resets != 0) std.debug.print(
" optimizer: call-links published={d} reset={d}\n",
.{ link_publications, link_resets },
);
}
/// Heap-cap accounting for a failing case. "Was the cap actually exhausted?" is
/// the first question for any heap-limited witness and cannot be recovered from
/// the exception alone (#100). No-op for cases that run without a cap.
fn printHeapBudget(ctx: *js.Context) void {
const stats = ctx.heapBudgetStats() orelse return;
std.debug.print(" heap budget: used {d} / limit {d} bytes (peak {d})\n", .{
stats.used_bytes, stats.limit_bytes, stats.peak_bytes,
});
}
/// Stable, allocation-free completion snapshot for a top-level failure. A
/// join rethrows the worker's exact exception, so the scalar record state is
/// the only reliable way to distinguish that path from a main-thread failure
/// when an exhausted heap cannot materialize more JS diagnostics.
fn printThreadFailureState(ctx: *js.Context) void {
if (ctx.print_buffer.items.len != 0) {
std.debug.print(" buffered output:\n{s}", .{ctx.print_buffer.items});
if (ctx.print_buffer.items[ctx.print_buffer.items.len - 1] != '\n') std.debug.print("\n", .{});
}
if (ctx.js_threads.items.len == 0) return;
std.debug.print(" thread completion state:\n", .{});
const io = js.agent.engineIo();
for (ctx.js_threads.items) |rec| {
rec.join_mutex.lockUncancelable(io);
std.debug.print(
" id={d} done={} exited={} threw={} joins-settled={}\n",
.{ rec.id, rec.done, rec.exited, rec.threw, rec.joins_settled },
);
rec.join_mutex.unlock(io);
}
}
fn printParallelGcEvidence(ctx: *js.Context) void {
if (ctx.parallelGcStats()) |stats| {
if (stats.attempts != 0) std.debug.print(
" parallel GC: attempts={d} collections={d} aborts={d} " ++
"(publication={d}, rounds={d}) generations={d} publications={d} " ++
"finish-retries={d} born-growth={d} deferred={d}/{d}\n",
.{
stats.attempts,
stats.collections,
stats.aborts,
stats.publication_timeout_aborts,
stats.round_limit_aborts,
stats.generations,
stats.peer_publications,
stats.finish_retries,
stats.born_growth_rounds,
stats.deferred_rounds,
stats.deferred_aborts,
},
);
}
if (ctx.cooperativeGcProfile()) |profile| {
if (profile.attempts != 0) std.debug.print(
" cooperative GC: attempts={d} collections={d} timeouts={d} " ++
"peer-parks={d} exit-cleanups={d} bytes-reset={d}\n",
.{
profile.attempts,
profile.collections,
profile.timeouts,
profile.peer_parks,
profile.exit_cleanups,
profile.bytes_reset_total,
},
);
}
}
const CaseTiming = struct {
name: []const u8 = "",
ms: u64 = 0,
};
fn nowNs(io: std.Io) i96 {
return std.Io.Clock.awake.now(io).nanoseconds;
}
fn elapsedMs(start_ns: i96, end_ns: i96) u64 {
if (end_ns <= start_ns) return 0;
return @intCast(@divFloor(end_ns - start_ns, std.time.ns_per_ms));
}
fn recordSlowCase(slowest: []CaseTiming, name: []const u8, ms: u64) void {
var insert_at: ?usize = null;
for (slowest, 0..) |entry, i| {
if (ms > entry.ms) {
insert_at = i;
break;
}
}
const at = insert_at orelse return;
var i = slowest.len - 1;
while (i > at) : (i -= 1) slowest[i] = slowest[i - 1];
slowest[at] = .{ .name = name, .ms = ms };
}
fn estimatedSerializedShardMs(name: []const u8) u64 {
// CI-observed serialized/GIL corpus costs from the per-case shard summaries.
// Unknown cases keep a small non-zero default so greedy assignment still
// spreads the rest of the allowlist evenly by count.