#!/usr/bin/env bash
# regression-named-let-leak.sh
#
# Wraps tests/regression-named-let-leak.lsp under a memory cap so
# a regression fails the run within seconds instead of consuming
# host RAM. Runs the .lsp on every available tier (Python, C, C
# --fast); skips a tier silently if its binary is missing.
#
# Memory cap: 256 MB virt per process. A clean run completes in
# ~30 MB; the historical leak ran past 1.8 GB before being killed,
# so 256 MB is a tight ceiling that catches regression fast.
#
# Wall-clock cap: 15s per tier.

set -e

LSP="tests/regression-named-let-leak.lsp"
[ -f "$LSP" ] || { echo "missing $LSP — run from lumbda repo root"; exit 2; }

MEMCAP_KB=262144     # 256 MB virtual memory ceiling
TIMEOUT_S=15

run_tier() {
    local label="$1" cmd="$2"
    if [ -z "$cmd" ] || ! command -v $(echo "$cmd" | awk '{print $1}') >/dev/null 2>&1; then
        printf "[skip] %s — binary missing\n" "$label"
        return 0
    fi
    printf "── %s ──\n" "$label"
    if ( ulimit -v $MEMCAP_KB; timeout ${TIMEOUT_S}s $cmd "$LSP" ); then
        printf "[pass] %s\n\n" "$label"
    else
        rc=$?
        printf "[fail] %s exited rc=%d (oom-killer or timeout = leak)\n\n" "$label" "$rc"
        return $rc
    fi
}

cd "$(dirname "$0")/.."

run_tier "Python tier (--fast)" "python3 lumbda.py --fast"
run_tier "C tier (tree-walker)"  "./c/lumbda"
run_tier "C tier (--fast JIT)"   "./c/lumbda --fast"

echo "════════════════════════════════════════"
echo "All tiers passed regression-named-let-leak"
