#!/bin/bash
# bench-gc-memory.sh — compare asm no-GC vs asm naive GC under
# sustained allocation load. Each build runs the same .lsp workload
# while a sampler records RSS from /proc/<pid>/status. Reports
# wall time, peak RSS, final RSS.
set -e
cd "$(dirname "$0")/.."

ulimit -v 524288
trap 'pkill -9 -u "$USER" -f "asm/lumbda" 2>/dev/null || true' EXIT

make -s -C asm all

WORKLOAD=examples/bench-gc-memory.lsp

run_with_sampling() {
    local bin="$1"
    local label="$2"
    local pid peak=0 final=0 rss
    echo "== $label =="
    "$bin" < "$WORKLOAD" > /tmp/gc-bench.out &
    pid=$!
    while kill -0 "$pid" 2>/dev/null; do
        rss=$(awk '/^VmRSS:/ {print $2}' /proc/$pid/status 2>/dev/null || echo 0)
        if [ -n "$rss" ] && [ "$rss" -gt "$peak" ]; then
            peak=$rss
        fi
        final=$rss
        sleep 0.05
    done
    wait "$pid"
    cat /tmp/gc-bench.out
    echo "peak_rss_kb=$peak"
    echo "final_rss_kb=$final"
    echo ""
}

run_with_sampling ./asm/lumbda    "asm (no GC, 64 MB chunks)"
run_with_sampling ./asm/lumbda-gc "asm (naive GC, 1 MB chunks)"

rm -f /tmp/gc-bench.out

if pgrep -u "$USER" -f 'asm/lumbda' > /dev/null; then
    echo "STRAGGLER detected" >&2
    exit 1
fi
