-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathrun_memory_stability_tests.sh
More file actions
executable file
·1865 lines (1674 loc) · 64.2 KB
/
Copy pathrun_memory_stability_tests.sh
File metadata and controls
executable file
·1865 lines (1674 loc) · 64.2 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
#!/usr/bin/env bash
# Memory-stability regression suite.
#
# Two failure modes this catches that microbenchmarks miss:
# 1. Slow RSS accumulation in long-running programs (a real "2 GB
# after an hour" leak that a 300 ms bench wouldn't surface).
# 2. Crashes when GC fires aggressively during sensitive ops
# (parse, recursion, closure init, write barriers).
#
# How it works:
# - test_memory_*.ts run a sustained allocate-and-discard loop
# for 100k-200k iterations. RSS must stay under a per-test limit
# (set ~50% above the current baseline). If a future change
# pins blocks, leaks the parse-key cache, or breaks tenuring,
# RSS climbs and the test fails.
# - test_gc_*.ts force aggressive GC scheduling during sensitive
# operations. Test passes ⟺ exit code 0 + correct stdout.
# - PERRY_GC_TRACE=1 JSON lines are parsed for GC acceptance gates:
# default-env copied-minor must report fallback_reason=none without
# rebuilding the malloc registry, precise low-pressure runs must not pin bytes,
# forced policy evacuation must move and release originals cleanly,
# fallback reasons must remain explicit known values, and representative
# traced workloads emit a copied-minor fallback evidence report.
# - targeted low-pressure benchmarks are compiled into $TMPDIR and run
# under /usr/bin/time:
# $PERRY compile --no-cache benchmarks/suite/07_object_create.ts -o $TMPDIR/07_object_create
# $PERRY compile --no-cache benchmarks/suite/12_binary_trees.ts -o $TMPDIR/12_binary_trees
# $PERRY compile --no-cache benchmarks/suite/bench_gc_pressure.ts -o $TMPDIR/bench_gc_pressure
# Gates: 07_object_create <= 10 ms / 64 MB RSS,
# 12_binary_trees <= 10 ms / 64 MB RSS,
# bench_gc_pressure <= 80 ms / 128 MB RSS.
#
# Each test runs under FOUR GC mode combos:
# - default (generational GC + generated write barriers)
# - mark-sweep (PERRY_GEN_GC=0 — bisection escape hatch)
# - explicit generational GC (PERRY_GEN_GC=1)
# - force-evac+verify (default write barriers + forced evacuation verifier:
# PERRY_GEN_GC_EVACUATE=1 PERRY_GC_FORCE_EVACUATE=1
# PERRY_GC_VERIFY_EVACUATION=1)
# so a regression in any mode is caught.
#
# Usage: scripts/run_memory_stability_tests.sh
# Exit: 0 on all pass, 1 on any failure.
set -euo pipefail
cd "$(dirname "$0")/.."
GC_EVIDENCE_ENABLED=0
GC_EVIDENCE_ROOT="${PERRY_GC_EVIDENCE_DIR:-}"
GC_EVIDENCE_LOG=""
GC_EVIDENCE_TRACE_COUNT=0
GC_EVIDENCE_ARTIFACTS=()
GC_EVIDENCE_TRACE_ARTIFACTS=()
GC_EVIDENCE_TRACE_SUMMARY_ARTIFACTS=()
ensure_output_parent() {
local path="$1"
if [[ -n "$path" ]]; then
mkdir -p "$(dirname "$path")"
fi
}
record_gc_evidence_artifact() {
local path="$1"
if [[ -n "$path" ]]; then
GC_EVIDENCE_ARTIFACTS+=("$path")
fi
}
sanitize_gc_evidence_name() {
local value="$1"
value=$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')
value=$(printf '%s' "$value" | sed -E 's/[^a-z0-9._-]+/_/g; s/^_+//; s/_+$//')
if [[ -z "$value" ]]; then
value="trace"
fi
printf '%s' "$value"
}
init_gc_evidence_outputs() {
if [[ -n "$GC_EVIDENCE_ROOT" ]]; then
GC_EVIDENCE_ENABLED=1
mkdir -p \
"$GC_EVIDENCE_ROOT/reports" \
"$GC_EVIDENCE_ROOT/logs" \
"$GC_EVIDENCE_ROOT/traces" \
"$GC_EVIDENCE_ROOT/trace-summaries"
if [[ -z "${PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT:-}" ]]; then
PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT="$GC_EVIDENCE_ROOT/reports/copied_minor_fallback_report.json"
fi
if [[ -z "${PERRY_TARGET_COLLECTOR_GATES_OUT:-}" ]]; then
PERRY_TARGET_COLLECTOR_GATES_OUT="$GC_EVIDENCE_ROOT/reports/target_collector_gates_report.json"
fi
if [[ -z "${PERRY_TEST_SUMMARY_OUT:-}" ]]; then
PERRY_TEST_SUMMARY_OUT="$GC_EVIDENCE_ROOT/reports/memory_stability_summary.json"
fi
GC_EVIDENCE_LOG="$GC_EVIDENCE_ROOT/logs/memory-stability.log"
: >"$GC_EVIDENCE_LOG"
record_gc_evidence_artifact "$GC_EVIDENCE_LOG"
exec > >(tee -a "$GC_EVIDENCE_LOG") 2>&1
fi
ensure_output_parent "${PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT:-}"
ensure_output_parent "${PERRY_TARGET_COLLECTOR_GATES_OUT:-}"
ensure_output_parent "${PERRY_TEST_SUMMARY_OUT:-}"
record_gc_evidence_artifact "${PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT:-}"
record_gc_evidence_artifact "${PERRY_TARGET_COLLECTOR_GATES_OUT:-}"
record_gc_evidence_artifact "${PERRY_TEST_SUMMARY_OUT:-}"
}
copy_gc_trace_evidence() {
local group="$1"
local label="$2"
local trace_file="$3"
LAST_EVIDENCE_TRACE_FILE=""
if [[ "$GC_EVIDENCE_ENABLED" -ne 1 || -z "$trace_file" || ! -f "$trace_file" ]]; then
return
fi
local safe_group safe_label dest_dir dest
safe_group=$(sanitize_gc_evidence_name "$group")
safe_label=$(sanitize_gc_evidence_name "$label")
GC_EVIDENCE_TRACE_COUNT=$((GC_EVIDENCE_TRACE_COUNT + 1))
dest_dir="$GC_EVIDENCE_ROOT/traces/$safe_group"
mkdir -p "$dest_dir"
dest=$(printf '%s/%03d_%s.log' "$dest_dir" "$GC_EVIDENCE_TRACE_COUNT" "$safe_label")
if cp "$trace_file" "$dest"; then
LAST_EVIDENCE_TRACE_FILE="$dest"
GC_EVIDENCE_TRACE_ARTIFACTS+=("$dest")
record_gc_evidence_artifact "$dest"
else
printf " WARN [gc-evidence] failed to copy trace %s -> %s\n" "$trace_file" "$dest"
fi
}
write_gc_trace_summary() {
local group="$1"
local label="$2"
local assertion_mode="$3"
local status="$4"
local trace_file="$5"
local copied_trace_file="$6"
LAST_EVIDENCE_TRACE_SUMMARY_FILE=""
if [[ "$GC_EVIDENCE_ENABLED" -ne 1 || -z "$trace_file" || ! -f "$trace_file" ]]; then
return
fi
local safe_group safe_label dest_dir dest
safe_group=$(sanitize_gc_evidence_name "$group")
safe_label=$(sanitize_gc_evidence_name "$label")
dest_dir="$GC_EVIDENCE_ROOT/trace-summaries/$safe_group"
mkdir -p "$dest_dir"
dest=$(printf '%s/%03d_%s.json' "$dest_dir" "$GC_EVIDENCE_TRACE_COUNT" "$safe_label")
if "$PYTHON" - \
"$label" "$assertion_mode" "$status" "$trace_file" "$copied_trace_file" "$dest" <<'PY'; then
import json
import sys
from pathlib import Path
label = sys.argv[1]
assertion_mode = sys.argv[2]
status = sys.argv[3]
trace_file = Path(sys.argv[4])
copied_trace_file = sys.argv[5]
out = Path(sys.argv[6])
known_fallback_reasons = (
"none",
"copy_only_roots",
"barriers_inactive",
"conservative_stack",
"malloc_registry_unavailable",
"pinned_young_root",
"pinned_young_dirty_slot",
"pinned_young_transitive",
"not_attempted",
)
fallback_reason_counts = {reason: 0 for reason in known_fallback_reasons}
def nested(obj, *path, default=None):
cur = obj
for key in path:
if not isinstance(cur, dict):
return default
cur = cur.get(key, default)
return cur
def non_negative_int(value):
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
return 0
return value
gc_cycle_count = 0
copied_bytes = 0
promoted_bytes = 0
moved_bytes = 0
old_page_moved_bytes = 0
with trace_file.open("r", encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line.startswith("{"):
continue
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if not isinstance(event, dict) or event.get("event") != "gc_cycle":
continue
gc_cycle_count += 1
copying_nursery = nested(event, "copying_nursery", default={})
if not isinstance(copying_nursery, dict):
copying_nursery = {}
reason = copying_nursery.get("fallback_reason")
if isinstance(reason, str):
fallback_reason_counts.setdefault(reason, 0)
fallback_reason_counts[reason] += 1
else:
fallback_reason_counts.setdefault("_missing", 0)
fallback_reason_counts["_missing"] += 1
copied_bytes += non_negative_int(copying_nursery.get("copied_bytes"))
promoted_bytes += non_negative_int(copying_nursery.get("promoted_bytes"))
moved_bytes += non_negative_int(nested(event, "evacuation", "moved_bytes", default=0))
old_page_moved_bytes += non_negative_int(
nested(event, "evacuation", "old_page_moved_bytes", default=0)
)
summary = {
"schema_version": 1,
"workload_label": label,
"assertion_mode": assertion_mode,
"status": status,
"source_trace_path": str(trace_file),
"trace_path": copied_trace_file or str(trace_file),
"gc_cycle_count": gc_cycle_count,
"fallback_reason_counts": fallback_reason_counts,
"copied_bytes": copied_bytes,
"promoted_bytes": promoted_bytes,
"moved_bytes": moved_bytes,
"old_page_moved_bytes": old_page_moved_bytes,
"byte_totals": {
"copied_bytes": copied_bytes,
"promoted_bytes": promoted_bytes,
"moved_bytes": moved_bytes,
"old_page_moved_bytes": old_page_moved_bytes,
},
}
with out.open("w", encoding="utf-8") as fh:
json.dump(summary, fh, indent=2)
fh.write("\n")
PY
LAST_EVIDENCE_TRACE_SUMMARY_FILE="$dest"
GC_EVIDENCE_TRACE_SUMMARY_ARTIFACTS+=("$dest")
record_gc_evidence_artifact "$dest"
else
printf " WARN [gc-evidence] failed to summarize trace %s\n" "$trace_file"
fi
}
record_gc_trace_evidence() {
local group="$1"
local label="$2"
local assertion_mode="$3"
local status="$4"
local trace_file="$5"
if [[ "$GC_EVIDENCE_ENABLED" -ne 1 || -z "$trace_file" || ! -f "$trace_file" ]]; then
return
fi
copy_gc_trace_evidence "$group" "$label" "$trace_file"
write_gc_trace_summary \
"$group" "$label" "$assertion_mode" "$status" \
"$trace_file" "$LAST_EVIDENCE_TRACE_FILE"
}
print_gc_evidence_artifacts() {
if [[ "$GC_EVIDENCE_ENABLED" -ne 1 && ${#GC_EVIDENCE_ARTIFACTS[@]} -eq 0 ]]; then
return
fi
echo ""
echo "=== GC evidence artifacts ==="
if [[ "$GC_EVIDENCE_ENABLED" -eq 1 ]]; then
echo " root: $GC_EVIDENCE_ROOT"
fi
if [[ -n "$GC_EVIDENCE_LOG" ]]; then
echo " log: $GC_EVIDENCE_LOG"
fi
if [[ -n "${PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT:-}" ]]; then
echo " copied-minor report: $PERRY_COPIED_MINOR_FALLBACK_REPORT_OUT"
fi
if [[ -n "${PERRY_TARGET_COLLECTOR_GATES_OUT:-}" ]]; then
echo " target-collector report: $PERRY_TARGET_COLLECTOR_GATES_OUT"
fi
if [[ -n "${PERRY_TEST_SUMMARY_OUT:-}" ]]; then
echo " summary: $PERRY_TEST_SUMMARY_OUT"
fi
if [[ ${#GC_EVIDENCE_TRACE_ARTIFACTS[@]} -gt 0 ]]; then
echo " traces:"
printf ' %s\n' "${GC_EVIDENCE_TRACE_ARTIFACTS[@]}"
fi
if [[ ${#GC_EVIDENCE_TRACE_SUMMARY_ARTIFACTS[@]} -gt 0 ]]; then
echo " trace summaries:"
printf ' %s\n' "${GC_EVIDENCE_TRACE_SUMMARY_ARTIFACTS[@]}"
fi
}
init_gc_evidence_outputs
cargo build --release -p perry-runtime -p perry-stdlib -p perry-runtime-static -p perry-stdlib-static -p perry --quiet
PERRY=./target/release/perry
PYTHON=${PYTHON:-python3}
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
# Globals set by run_one. Bash makes it painful to return multiple
# values cleanly; globals beat parsing a single-line string.
LAST_RSS_MB=0
LAST_EXIT=0
LAST_STDOUT_FILE=""
LAST_STDERR_FILE=""
LAST_CANARY_EXIT=0
LAST_CANARY_OUTPUT_FILE=""
LAST_GC_TRACE_FILE=""
LAST_TRACE_ASSERT_STATUS=""
LAST_EVIDENCE_TRACE_FILE=""
LAST_EVIDENCE_TRACE_SUMMARY_FILE=""
# Run a compiled binary under /usr/bin/time. Cross-platform RSS read
# (macOS reports bytes, Linux reports KB).
run_one() {
local bin="$1"
shift # remaining args are env VAR=val pairs
LAST_STDOUT_FILE="$TMPDIR/stdout.$$.$RANDOM"
LAST_STDERR_FILE="$TMPDIR/stderr.$$.$RANDOM"
LAST_EXIT=0
if [[ "$(uname)" == "Darwin" ]]; then
env "$@" /usr/bin/time -l "$bin" >"$LAST_STDOUT_FILE" 2>"$LAST_STDERR_FILE" \
|| LAST_EXIT=$?
local b
b=$(awk '/maximum resident set size/ {print $1}' "$LAST_STDERR_FILE")
b=${b:-0}
LAST_RSS_MB=$((b / 1024 / 1024))
else
env "$@" /usr/bin/time -v "$bin" >"$LAST_STDOUT_FILE" 2>"$LAST_STDERR_FILE" \
|| LAST_EXIT=$?
local kb
kb=$(awk '/Maximum resident set size/ {print $NF}' "$LAST_STDERR_FILE")
kb=${kb:-0}
LAST_RSS_MB=$((kb / 1024))
fi
}
# Compile once per GC mode. Generated write barriers are on by default;
# PERRY_WRITE_BARRIERS=0/off/false is the benchmark/debug escape hatch
# that suppresses barrier emission at compile time and disables runtime
# exact helper barriers.
PASS=0
FAIL=0
run_test() {
local ts="$1"
local rss_limit_mb="$2"
local expect_substr="$3"
local force_verify_rss_limit_mb="${4:-$rss_limit_mb}"
local mode_specs=(
"default||"
"mark-sweep||PERRY_GEN_GC=0"
"gen-gc-explicit||PERRY_GEN_GC=1"
"force-evac+verify||PERRY_GEN_GC=1 PERRY_GEN_GC_EVACUATE=1 PERRY_GC_FORCE_EVACUATE=1 PERRY_GC_VERIFY_EVACUATION=1"
)
for spec in "${mode_specs[@]}"; do
IFS='|' read -r mode_label compile_env_str env_str <<<"$spec"
local effective_rss_limit_mb="$rss_limit_mb"
if [[ "$mode_label" == "force-evac+verify" ]]; then
effective_rss_limit_mb="$force_verify_rss_limit_mb"
fi
local bin="$TMPDIR/$(basename "${ts%.ts}")_${mode_label//[^A-Za-z0-9_]/_}"
local compile_env_args=()
if [[ -n "$compile_env_str" ]]; then
# shellcheck disable=SC2206
compile_env_args=($compile_env_str)
fi
if ! env "${compile_env_args[@]+"${compile_env_args[@]}"}" \
$PERRY compile --no-cache "$ts" -o "$bin" >/dev/null 2>&1; then
printf " FAIL [%-18s] %-40s compile failed\n" "$mode_label" "$(basename "$ts")"
FAIL=$((FAIL + 1))
continue
fi
# Split env_str on spaces into argv tokens (an empty string
# gives env zero args, which is fine).
local env_args=()
if [[ -n "$env_str" ]]; then
# shellcheck disable=SC2206
env_args=($env_str)
fi
# `"${env_args[@]+"${env_args[@]}"}"` is the safe-expand
# idiom under `set -u`: empty array → no args, non-empty →
# quoted expansion.
run_one "$bin" "${env_args[@]+"${env_args[@]}"}"
local status="PASS"
local reason=""
if [[ "$LAST_EXIT" -ne 0 ]]; then
status="FAIL"
reason="exit=$LAST_EXIT"
elif [[ "$LAST_RSS_MB" -gt "$effective_rss_limit_mb" ]]; then
status="FAIL"
reason="rss=${LAST_RSS_MB}MB > limit=${effective_rss_limit_mb}MB"
elif [[ -n "$expect_substr" ]] && ! grep -qF "$expect_substr" "$LAST_STDOUT_FILE"; then
status="FAIL"
reason="stdout missing: $expect_substr"
fi
printf " %s [%-18s] %-40s rss=%3dMB / limit=%3dMB %s\n" \
"$status" "$mode_label" "$(basename "$ts")" \
"$LAST_RSS_MB" "$effective_rss_limit_mb" "$reason"
if [[ "$status" == "PASS" ]]; then
PASS=$((PASS + 1))
else
FAIL=$((FAIL + 1))
fi
done
}
run_canary() {
local label="$1"
shift
LAST_CANARY_OUTPUT_FILE="$TMPDIR/canary.$$.$RANDOM"
LAST_CANARY_EXIT=0
"$@" >"$LAST_CANARY_OUTPUT_FILE" 2>&1 || LAST_CANARY_EXIT=$?
if [[ "$LAST_CANARY_EXIT" -eq 0 ]]; then
printf " PASS [canary] %-40s\n" "$label"
PASS=$((PASS + 1))
else
printf " FAIL [canary] %-40s exit=%d\n" "$label" "$LAST_CANARY_EXIT"
sed 's/^/ /' "$LAST_CANARY_OUTPUT_FILE"
FAIL=$((FAIL + 1))
fi
}
assert_gc_trace() {
local label="$1"
local trace_file="$2"
local mode="$3"
local output_file="$TMPDIR/gc_trace_assert.$$.$RANDOM"
LAST_TRACE_ASSERT_STATUS="fail"
if "$PYTHON" - "$mode" "$trace_file" >"$output_file" 2>&1 <<'PY'; then
import json
import sys
mode = sys.argv[1]
trace_path = sys.argv[2]
allowed_fallback_reasons = {
"none",
"copy_only_roots",
"barriers_inactive",
"conservative_stack",
"malloc_registry_unavailable",
"pinned_young_root",
"pinned_young_dirty_slot",
"pinned_young_transitive",
"not_attempted",
}
def nested(obj, *path, default=None):
cur = obj
for key in path:
if not isinstance(cur, dict):
return default
cur = cur.get(key, default)
return cur
cycles = []
with open(trace_path, "r", encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line.startswith("{"):
continue
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if event.get("event") == "gc_cycle":
cycles.append(event)
errors = []
if not cycles:
errors.append("no gc_cycle JSON events found")
for idx, cycle in enumerate(cycles):
reason = nested(cycle, "copying_nursery", "fallback_reason")
eligible = nested(cycle, "copying_nursery", "eligible")
shadow_roots = cycle.get("shadow_roots")
root_sources = cycle.get("root_sources")
layout_scans = cycle.get("layout_scans")
if reason not in allowed_fallback_reasons:
errors.append(f"cycle {idx}: unexpected fallback_reason={reason!r}")
if not isinstance(eligible, bool):
errors.append(f"cycle {idx}: copying_nursery.eligible={eligible!r}, want bool")
elif reason == "none" and eligible is not True:
errors.append(f"cycle {idx}: eligible={eligible!r} with fallback_reason='none'")
elif reason != "none" and eligible is not False:
errors.append(f"cycle {idx}: eligible={eligible!r} with fallback_reason={reason!r}")
if not isinstance(shadow_roots, dict):
errors.append(f"cycle {idx}: shadow_roots missing or not an object")
else:
for field in ("slots_scanned", "nonzero_slots", "pointer_roots", "rewritten_slots"):
value = shadow_roots.get(field)
if not isinstance(value, int) or value < 0:
errors.append(f"cycle {idx}: shadow_roots.{field}={value!r}, want non-negative int")
slots = shadow_roots.get("slots_scanned", -1)
nonzero = shadow_roots.get("nonzero_slots", -1)
pointers = shadow_roots.get("pointer_roots", -1)
rewritten = shadow_roots.get("rewritten_slots", -1)
if isinstance(slots, int) and isinstance(nonzero, int) and nonzero > slots:
errors.append(f"cycle {idx}: shadow_roots.nonzero_slots={nonzero} > slots_scanned={slots}")
if isinstance(nonzero, int) and isinstance(pointers, int) and pointers > nonzero:
errors.append(f"cycle {idx}: shadow_roots.pointer_roots={pointers} > nonzero_slots={nonzero}")
if isinstance(pointers, int) and isinstance(rewritten, int) and rewritten > pointers:
errors.append(f"cycle {idx}: shadow_roots.rewritten_slots={rewritten} > pointer_roots={pointers}")
if not isinstance(root_sources, dict):
errors.append(f"cycle {idx}: root_sources missing or not an object")
else:
for source in (
"compiled_shadow",
"module_globals",
"runtime_handles",
"runtime_mutable_scanners",
"ffi_mutable_scanners",
):
stats = root_sources.get(source)
if not isinstance(stats, dict):
errors.append(f"cycle {idx}: root_sources.{source} missing or not an object")
continue
for field in (
"registered_scanners",
"slots_scanned",
"nonzero_slots",
"pointer_roots",
"rewritten_slots",
):
value = stats.get(field)
if not isinstance(value, int) or value < 0:
errors.append(
f"cycle {idx}: root_sources.{source}.{field}={value!r}, "
"want non-negative int"
)
slots = stats.get("slots_scanned", -1)
nonzero = stats.get("nonzero_slots", -1)
pointers = stats.get("pointer_roots", -1)
rewritten = stats.get("rewritten_slots", -1)
if isinstance(slots, int) and isinstance(nonzero, int) and nonzero > slots:
errors.append(
f"cycle {idx}: root_sources.{source}.nonzero_slots={nonzero} "
f"> slots_scanned={slots}"
)
if isinstance(nonzero, int) and isinstance(pointers, int) and pointers > nonzero:
errors.append(
f"cycle {idx}: root_sources.{source}.pointer_roots={pointers} "
f"> nonzero_slots={nonzero}"
)
if isinstance(pointers, int) and isinstance(rewritten, int) and rewritten > pointers:
errors.append(
f"cycle {idx}: root_sources.{source}.rewritten_slots={rewritten} "
f"> pointer_roots={pointers}"
)
native = root_sources.get("native_stack_fallback")
if not isinstance(native, dict):
errors.append(f"cycle {idx}: root_sources.native_stack_fallback missing or not an object")
else:
decision = native.get("decision")
if decision not in ("scan", "skip_disabled", "skip_shadow_stack_active"):
errors.append(
f"cycle {idx}: root_sources.native_stack_fallback.decision={decision!r}"
)
if not isinstance(native.get("scanned"), bool):
errors.append(
f"cycle {idx}: root_sources.native_stack_fallback.scanned="
f"{native.get('scanned')!r}, want bool"
)
for field in (
"roots_found",
"pinned_roots",
"pinned_bytes",
"compiled_frame_pinned_roots",
"compiled_frame_pinned_bytes",
):
value = native.get(field)
if not isinstance(value, int) or value < 0:
errors.append(
f"cycle {idx}: root_sources.native_stack_fallback.{field}="
f"{value!r}, want non-negative int"
)
if not isinstance(layout_scans, dict):
errors.append(f"cycle {idx}: layout_scans missing or not an object")
else:
for field in (
"pointer_slots_read",
"masked_pointer_slots_read",
"unknown_layout_slots_read",
"pointer_free_ranges_skipped",
"pointer_free_slots_skipped",
"raw_numeric_array_ranges_skipped",
"raw_numeric_array_slots_skipped",
"raw_numeric_object_field_ranges_skipped",
"raw_numeric_object_field_slots_skipped",
):
value = layout_scans.get(field)
if not isinstance(value, int) or value < 0:
errors.append(f"cycle {idx}: layout_scans.{field}={value!r}, want non-negative int")
pointer_slots = layout_scans.get("pointer_slots_read", -1)
masked_slots = layout_scans.get("masked_pointer_slots_read", -1)
unknown_slots = layout_scans.get("unknown_layout_slots_read", -1)
pointer_free_ranges = layout_scans.get("pointer_free_ranges_skipped", -1)
pointer_free_slots = layout_scans.get("pointer_free_slots_skipped", -1)
if (
isinstance(pointer_slots, int)
and isinstance(masked_slots, int)
and isinstance(unknown_slots, int)
and masked_slots + unknown_slots > pointer_slots
):
errors.append(
f"cycle {idx}: layout_scans masked+unknown={masked_slots + unknown_slots} "
f"> pointer_slots_read={pointer_slots}"
)
if (
isinstance(pointer_free_ranges, int)
and isinstance(pointer_free_slots, int)
and pointer_free_ranges > 0
and pointer_free_slots == 0
):
errors.append(f"cycle {idx}: pointer-free ranges skipped but slots skipped is zero")
if mode in ("copied_minor_precise", "copied_minor_default"):
for idx, cycle in enumerate(cycles):
if cycle.get("collection_kind") != "minor":
errors.append(f"cycle {idx}: collection_kind={cycle.get('collection_kind')!r}, want 'minor'")
reason = nested(cycle, "copying_nursery", "fallback_reason")
eligible = nested(cycle, "copying_nursery", "eligible")
rebuilds = nested(cycle, "copying_nursery", "malloc_registry_rebuilds", default=-1)
conservative_pinned_bytes = cycle.get("conservative_pinned_bytes", -1)
legacy_pinned_bytes = nested(
cycle, "legacy_copy_only_scanner_pinned", "bytes", default=-1
)
native_pinned_bytes = nested(
cycle, "root_sources", "native_stack_fallback", "pinned_bytes", default=-1
)
compiled_frame_pinned_bytes = nested(
cycle,
"root_sources",
"native_stack_fallback",
"compiled_frame_pinned_bytes",
default=-1,
)
if reason != "none":
errors.append(f"cycle {idx}: fallback_reason={reason!r}, want 'none'")
if eligible is not True:
errors.append(f"cycle {idx}: eligible={eligible!r}, want true")
if rebuilds != 0:
errors.append(f"cycle {idx}: malloc_registry_rebuilds={rebuilds}, want 0")
if conservative_pinned_bytes != 0:
errors.append(
f"cycle {idx}: conservative_pinned_bytes={conservative_pinned_bytes}, want 0"
)
if legacy_pinned_bytes != 0:
errors.append(
f"cycle {idx}: legacy_copy_only_scanner_pinned.bytes={legacy_pinned_bytes}, want 0"
)
if native_pinned_bytes != 0:
errors.append(
f"cycle {idx}: root_sources.native_stack_fallback.pinned_bytes="
f"{native_pinned_bytes}, want 0"
)
if compiled_frame_pinned_bytes != 0:
errors.append(
f"cycle {idx}: root_sources.native_stack_fallback."
f"compiled_frame_pinned_bytes={compiled_frame_pinned_bytes}, want 0"
)
copied_productive = [
cycle
for cycle in cycles
if nested(cycle, "copying_nursery", "copied_objects", default=0)
+ nested(cycle, "copying_nursery", "promoted_objects", default=0)
> 0
]
if not copied_productive:
errors.append("no copied-minor trace copied or promoted any object")
nonzero_shadow_roots = [
nested(cycle, "shadow_roots", "nonzero_slots", default=0) for cycle in cycles
]
if not nonzero_shadow_roots:
errors.append("copied-minor trace did not report shadow_roots.nonzero_slots")
elif nonzero_shadow_roots[-1] > nonzero_shadow_roots[0]:
errors.append(
"shadow_roots.nonzero_slots grew across copied-minor probe: "
f"{nonzero_shadow_roots}"
)
mutable_source_evidence = [
sum(
nested(cycle, "root_sources", source, "pointer_roots", default=0)
+ nested(cycle, "root_sources", source, "rewritten_slots", default=0)
for source in (
"compiled_shadow",
"module_globals",
"runtime_handles",
"runtime_mutable_scanners",
"ffi_mutable_scanners",
)
)
for cycle in cycles
]
if not mutable_source_evidence or max(mutable_source_evidence) == 0:
errors.append("copied-minor trace did not report mutable root source evidence")
elif mode == "evacuation_productive":
productive = [
cycle
for cycle in cycles
if nested(cycle, "evacuation_policy", "enabled") is True
and nested(cycle, "evacuation", "moved_bytes", default=0) > 0
]
if not productive:
errors.append("no policy-enabled evacuation moved bytes")
for idx, cycle in enumerate(productive):
moved_bytes = nested(cycle, "evacuation", "moved_bytes", default=-1)
released_bytes = nested(cycle, "evacuation", "released_original_bytes", default=-2)
moved_objects = nested(cycle, "evacuation", "moved_objects", default=-1)
released_objects = nested(cycle, "evacuation", "released_original_objects", default=-2)
retained_bytes = nested(cycle, "evacuation", "retained_forwarded_stub_bytes", default=-1)
retained_objects = nested(
cycle, "evacuation", "retained_forwarded_stub_objects", default=-1
)
sweep_retained_bytes = nested(cycle, "sweep", "retained_forwarded_stub_bytes", default=-1)
sweep_retained_objects = nested(
cycle, "sweep", "retained_forwarded_stub_objects", default=-1
)
if moved_bytes != released_bytes:
errors.append(
f"productive evacuation {idx}: moved_bytes={moved_bytes}, "
f"released_original_bytes={released_bytes}"
)
if moved_objects != released_objects:
errors.append(
f"productive evacuation {idx}: moved_objects={moved_objects}, "
f"released_original_objects={released_objects}"
)
if retained_bytes != 0 or retained_objects != 0:
errors.append(
f"productive evacuation {idx}: retained forwarding stubs "
f"bytes={retained_bytes} objects={retained_objects}"
)
if sweep_retained_bytes != 0 or sweep_retained_objects != 0:
errors.append(
f"productive evacuation {idx}: sweep retained forwarding stubs "
f"bytes={sweep_retained_bytes} objects={sweep_retained_objects}"
)
elif mode == "barriers_inactive":
matches = [
cycle
for cycle in cycles
if nested(cycle, "copying_nursery", "fallback_reason") == "barriers_inactive"
and nested(cycle, "evacuation_policy", "reason") == "barriers_inactive"
]
if not matches:
errors.append("no trace reported barriers_inactive for copying and evacuation policy")
for idx, cycle in enumerate(matches):
if nested(cycle, "copying_nursery", "eligible") is not False:
errors.append(f"barriers-inactive trace {idx}: copied-minor unexpectedly eligible")
if nested(cycle, "evacuation_policy", "enabled") is not False:
errors.append(f"barriers-inactive trace {idx}: evacuation policy unexpectedly enabled")
if nested(cycle, "evacuation", "moved_bytes", default=-1) != 0:
errors.append(f"barriers-inactive trace {idx}: evacuation moved bytes")
elif mode != "fallback_reasons":
errors.append(f"unknown assertion mode {mode!r}")
if errors:
print("\n".join(errors))
sys.exit(1)
print(f"validated {len(cycles)} gc_cycle event(s)")
PY
local detail
detail=$(tr '\n' ' ' <"$output_file" | sed 's/[[:space:]]*$//')
printf " PASS [gc-trace] %-40s %s\n" "$label" "$detail"
PASS=$((PASS + 1))
LAST_TRACE_ASSERT_STATUS="pass"
else
printf " FAIL [gc-trace] %-40s\n" "$label"
sed 's/^/ /' "$output_file"
FAIL=$((FAIL + 1))
LAST_TRACE_ASSERT_STATUS="fail"
fi
}
run_gc_trace_probe() {
local ts="$TMPDIR/default_copied_minor_churn.ts"
local bin="$TMPDIR/default_copied_minor_churn"
local compile_output="$TMPDIR/default_copied_minor_churn_compile.$$.$RANDOM"
LAST_GC_TRACE_FILE=""
cat >"$ts" <<'EOF'
declare function gc(): void;
function smallBlob(i: number): string {
return JSON.stringify({ id: i, name: "small_" + i, value: i * 7 });
}
function largeBlob(i: number): string {
const items: any[] = [];
for (let j = 0; j < 18; j++) {
items.push({
id: i * 18 + j,
name: "item_" + j,
nested: { x: j, y: j * 2 },
});
}
return JSON.stringify(items);
}
function churnBatch(base: number): number {
let checksum = 0;
for (let k = 0; k < 64; k++) {
const i = base + k;
const s: any = JSON.parse(smallBlob(i));
const l: any = JSON.parse(largeBlob(i));
const shortText = "s" + (i % 9);
const name = "record_" + i + "_value_" + (i * 3);
const obj: any = { id: i, left: s, right: l[0], n: shortText.length + name.length };
checksum += s.id + l.length + l[0].id + obj.n;
}
return checksum;
}
function copiedProbe(i: number): number {
const live: any[] = [];
live.push(i);
live.push(i + 1);
live.push(i + 2);
gc();
return i + 3;
}
function main(): number {
let checksum = 0;
for (let batch = 0; batch < 10; batch++) {
checksum += churnBatch(batch * 64);
checksum += copiedProbe(batch * 64);
}
return checksum;
}
const result = main();
console.log("default_copied_minor_churn:" + result);
EOF
if ! $PERRY compile --no-cache "$ts" -o "$bin" >"$compile_output" 2>&1; then
printf " FAIL [gc-trace] %-40s compile failed\n" "default copied minor churn"
sed 's/^/ /' "$compile_output"
FAIL=$((FAIL + 1))
return
fi
run_one "$bin" PERRY_GC_TRACE=1
LAST_GC_TRACE_FILE="$LAST_STDERR_FILE"
if [[ "$LAST_EXIT" -ne 0 ]]; then
printf " FAIL [gc-trace] %-40s exit=%d\n" "default copied minor churn" "$LAST_EXIT"
sed 's/^/ /' "$LAST_STDERR_FILE"
record_gc_trace_evidence \
"gc-trace" "default copied minor churn" "copied_minor_default" "fail" \
"$LAST_GC_TRACE_FILE"
FAIL=$((FAIL + 1))
return
fi
if ! grep -qF "default_copied_minor_churn:3913788" "$LAST_STDOUT_FILE"; then
printf " FAIL [gc-trace] %-40s stdout mismatch\n" "default copied minor churn"
sed 's/^/ /' "$LAST_STDOUT_FILE"
record_gc_trace_evidence \
"gc-trace" "default copied minor churn" "copied_minor_default" "fail" \
"$LAST_GC_TRACE_FILE"
FAIL=$((FAIL + 1))
return
fi
assert_gc_trace "default copied minor churn" "$LAST_STDERR_FILE" "copied_minor_default"
record_gc_trace_evidence \
"gc-trace" "default copied minor churn" "copied_minor_default" \
"$LAST_TRACE_ASSERT_STATUS" "$LAST_GC_TRACE_FILE"
}
write_copied_minor_fallback_workloads() {
local out_dir="$1"
cat >"$out_dir/json_roundtrip.ts" <<'EOF'
declare function gc(): void;
function payload(i: number): string {
const items: any[] = [];
for (let j = 0; j < 24; j++) {
items.push({
id: i * 24 + j,
name: "item_" + j + "_for_" + i,
nested: { x: j, y: j * 3 },
});
}
return JSON.stringify({
id: i,
route: "/api/items/" + i,
ok: (i % 2) === 0,
items,
});
}
let checksum = 0;
for (let batch = 0; batch < 8; batch++) {
for (let k = 0; k < 80; k++) {
const i = batch * 80 + k;
const parsed: any = JSON.parse(payload(i));
const reshaped = JSON.stringify({
id: parsed.id,
first: parsed.items[0].name,
count: parsed.items.length,
lastY: parsed.items[23].nested.y,
});
const again: any = JSON.parse(reshaped);
checksum += again.id + again.count + again.first.length + again.lastY;
}
gc();
}
console.log("json_roundtrip:" + checksum);
EOF
cat >"$out_dir/string_churn.ts" <<'EOF'
declare function gc(): void;
function label(i: number): string {
return "request_" + i + "_tenant_" + (i % 17) + "_segment_" + (i % 5);
}
let total = 0;
for (let batch = 0; batch < 10; batch++) {
for (let k = 0; k < 400; k++) {
const i = batch * 400 + k;
const shortText = "s" + (i % 9);
const mediumText = "field_" + i;
const longText = label(i) + "_payload_" + (i * 13);
const combined = shortText + "|" + mediumText + "|" + longText;
total += shortText.length + mediumText.length + longText.length + combined.length;
if ((i % 4) === 0) {
total += ("copy_" + combined).length;
}
}
gc();
}
console.log("string_churn:" + total);
EOF
cat >"$out_dir/object_property_churn.ts" <<'EOF'
declare function gc(): void;
function makeRecord(i: number): any {
return {
id: i,
name: "record_" + i,
status: (i % 3) === 0 ? "open" : "closed",
nested: { count: i * 3, tag: "tag_" + (i % 11) },