STRA-338: integrate the engine track (kar-off-ab base, S5a, S5b, S13 ratchets) into the hexagonal base; the baseline is recomputed on the merged tree (growth only in the seven kar-off-ab files)

This commit is contained in:
Pavlo Ratushnyi
2026-11-05 21:51:28 +01:00
180 changed files with 28421 additions and 3731 deletions
+91 -7
View File
@@ -52,16 +52,36 @@ def is_test_file(path, src):
def production_lines(text):
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped."""
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped.
An inline module under another test cfg (`#[cfg(all(test, ...))]` then `mod x {`) is skipped up to its closing
`}` at column 0; the code after it still counts."""
lines = text.splitlines()
for index, line in enumerate(lines):
if line.startswith("#[cfg(test)]") and index + 1 < len(lines) and lines[index + 1].startswith("mod "):
return [row for row in lines[:index] if not row.lstrip().startswith("//")]
return [row for row in lines if not row.lstrip().startswith("//")]
kept = []
index = 0
while index < len(lines):
line = lines[index]
following = lines[index + 1] if index + 1 < len(lines) else ""
if line.startswith("#[cfg(test)]") and following.startswith("mod "):
break
if _is_test_cfg(line) and line.startswith("#[cfg(") and following.startswith("mod ") and following.rstrip().endswith("{"):
index = _after_block(lines, index + 1)
continue
if not line.lstrip().startswith("//"):
kept.append(line)
index += 1
return kept
def _after_block(lines, start):
"""Index of the line after the column-0 `}` that closes the block opened at `start`."""
for index in range(start + 1, len(lines)):
if lines[index].startswith("}"):
return index + 1
return len(lines)
def count_patterns(packages, patterns):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only."""
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only (test files and modules declared under a test cfg are skipped)."""
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
counts = {}
for pkg in packages:
@@ -70,12 +90,76 @@ def count_patterns(packages, patterns):
return counts
_MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;")
_PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
def test_only_modules(src):
"""Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a
`#[path]`). `_under_test_module` extends this to the files below such a module."""
found = set()
for path in rust_files(src):
for name, explicit in _test_declarations(_text(path)):
target = _module_file(path, name, explicit)
if target is not None:
found.add(target)
return found
def _test_declarations(text):
"""[(module name, #[path] value or None)] of the `mod x;` lines whose attribute block is a test cfg."""
out = []
attrs = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#[") or (attrs and _unbalanced(" ".join(attrs))):
attrs.append(stripped)
continue
decl = _MOD_LINE.match(stripped)
if decl and _is_test_cfg(" ".join(attrs)):
explicit = _PATH_ATTR.search(" ".join(attrs))
out.append((decl.group(1), explicit.group(1) if explicit else None))
attrs = []
return out
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _is_test_cfg(block):
return "cfg(" in block and re.search(r"\btest\b", block) is not None and "not(test" not in block
def _module_file(declaring, name, explicit):
here = declaring.parent
if explicit:
target = (here / explicit).resolve()
return target if target.is_file() else None
base = here if declaring.name in ("lib.rs", "main.rs", "mod.rs") else here / declaring.stem
for candidate in (base / f"{name}.rs", base / name / "mod.rs"):
if candidate.is_file():
return candidate.resolve()
return None
def _under_test_module(path, test_files):
"""The file itself or a file in the directory a test-only module owns (`x.rs` owns `x/`, `mod.rs` its folder)."""
resolved = path.resolve()
for owner in test_files:
folder = owner.parent if owner.name == "mod.rs" else owner.with_suffix("")
if resolved == owner or resolved.is_relative_to(folder):
return True
return False
def _package_counts(src, compiled):
totals = {}
if not src.is_dir():
return totals
test_files = test_only_modules(src)
for path in rust_files(src):
if is_test_file(path, src):
if is_test_file(path, src) or _under_test_module(path, test_files):
continue
rows = production_lines(_text(path))
for pid, rx in compiled:
+24
View File
@@ -138,6 +138,13 @@ class Measurement(unittest.TestCase):
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n'
self.assertEqual(len(measure.production_lines(text)), 3)
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
rows = measure.production_lines(text)
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
@@ -148,6 +155,23 @@ class Measurement(unittest.TestCase):
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 4})
if __name__ == "__main__":
unittest.main()
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env bash
# Codex + runtime + model comparison, vanilla Strata against Leleka, on the owner's two tasks (docs/experiments/codex-compare-5090.md). Test tooling, never in serving.
#
# ONE BLOCK = one stack start of one arm, then the warm-up cell and the requested cells of ONE repetition. A queue stub sets CMP_ARM / CMP_REPS / CMP_TASKS:
# CMP_ARM=ours HOLDER JOB (inherits the sealed KAR memfd): the release package, `leleka up --foreground --kar-fd`, shipped configuration (KAR PLE, prefix cache auto / tail reply).
# CMP_ARM=vanilla holder-free window payload (started by cmp_window.sh): vanilla Strata 0.2.6 launcher, shipped defaults (route tail skip and CPU prefill share ON).
# CMP_VANILLA_LOSSY=0 turns both lossy defaults off (variant VANL instead of VAN).
# CMP_TASKS ("ttt nestng-crm") CMP_OPTIONAL (tasks dropped, with a note, when not ready) CMP_REPS ("1") CMP_WALL (cell wall limit s, default 3000) CMP_ROUNDS (round cap, default 150) CMP_RUN (default $CMP/runs/main)
# CMP_TARBALL (ours; default the final release package)
# Cells: cell.py of the codex-lossy-delta study (logging proxy, temperature 0 injected for BOTH arms, real Codex CLI, task acceptance); no AGENTS.md pad: the sessions are what a
# user gets. Output: $RUN/<VARIANT>/<task>-r<rep>/ (cell.json, proxy/, acceptance.log ...), $RUN/<VARIANT>/stack-r<rep>/. Variants: LEL = Leleka, VAN = vanilla shipped, VANL = vanilla lossless.
set -uo pipefail
ARM=${CMP_ARM:?CMP_ARM ours|vanilla}
CMP=/data/leleka-e2e/codex-compare
TASKS_ROOT=$CMP/tasks
CELLPY=$CMP/delta/cell.py
CODEX=/home/para/work/codex-e2e/bin/codex
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
A=/home/para/work/leleka/models/leleka-gates/assets
CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib
TASKS=${CMP_TASKS:-"ttt"}
REPS=${CMP_REPS:-"1"}
RUN=${CMP_RUN:-$CMP/runs/main}
WALL=${CMP_WALL:-3000}; ROUNDS=${CMP_ROUNDS:-150}
NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin 2>/dev/null | tail -1)
NM=$CMP/nm
case $ARM in ours) VAR=LEL;; vanilla) if [ "${CMP_VANILLA_LOSSY:-1}" = 1 ]; then VAR=VAN; else VAR=VANL; fi;; *) echo "bad CMP_ARM"; exit 2;; esac
BLK=$(echo "$REPS" | tr ' ' '+')
mkdir -p "$RUN" "$RUN/$VAR"
exec > >(tee -a "$RUN/job-$VAR-r$BLK.log") 2>&1
log() { echo "[cmp $VAR $(date -u +%T)] $*"; }
note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >>/data/leleka-e2e/decode/notes.md; }
# ---- guards ---------------------------------------------------------------------------------------------------------------------------------
( cd "$CMP" && sha256sum --quiet -c INSTALL.sha256 ) || { echo "installed tools differ from INSTALL.sha256"; exit 3; }
python3 -I "$CMP/delta/taskfile.py" check "$TASKS_ROOT" >"$RUN/tasks-check-$VAR-r$BLK.txt" 2>&1 || { echo "task files differ from their manifest"; cat "$RUN/tasks-check-$VAR-r$BLK.txt"; exit 3; }
# a task listed in CMP_OPTIONAL that is not ready (not installed, or the Node toolchain not proven in the Codex sandbox) is DROPPED with a loud note instead of refusing the block
nestng_ready() { [ -f "$TASKS_ROOT/nestng-crm/task.md" ] && [ -f "$CMP/toolchain/NESTNG_OK" ] && [ -d "$NM/backend/node_modules" ] && [ -d "$NM/frontend/node_modules" ]; }
KEEP=""
for t in $TASKS; do
if [ "$t" = nestng-crm ] && ! nestng_ready; then
case " ${CMP_OPTIONAL:-} " in *" $t "*) log "TASK DROPPED: $t is not ready (toolchain/NESTNG_OK missing)"; note "codex-compare block $VAR reps [$REPS]: task $t DROPPED (not ready); queue it again later"; continue;; esac
echo "task $t is not ready (toolchain/NESTNG_OK, shared node_modules)"; exit 3
fi
[ -f "$TASKS_ROOT/$t/task.md" ] || { echo "task $t is not installed in $TASKS_ROOT"; exit 3; }
KEEP="$KEEP $t"
done
TASKS=${KEEP# }
[ -f "$TASKS_ROOT/smoke-mini/task.md" ] || { echo "task smoke-mini is not installed"; exit 3; }
[ -x "$CODEX" ] || { echo "no codex binary"; exit 3; }
[ -n "$NODE_BIN" ] && [ -x "$NODE_BIN/node" ] || { echo "no node toolchain under $CMP/toolchain"; exit 3; }
STANDALONE=0; FD=${LELEKA_STRA169_KAR_FD:-}
if [ "$ARM" = ours ]; then
readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || { echo "ours needs the holder's sealed memfd"; exit 3; }
[ -d "$G/MODEL.lock" ] || { echo "MODEL.lock is not held"; exit 3; }
else
mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held (holder still up?)"; exit 3; }; STANDALONE=1
fi
got=0
for _ in $(seq 1 4320); do
if mkdir "$LOCK" 2>/dev/null; then echo "codex-compare $VAR $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; [ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock"; exit 3; }
SUP_PID=; MON_PID=
stop_stack() {
if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi
SUP_PID=
}
cleanup() {
stop_stack
[ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null
pkill -KILL -f "$CMP/ours-prefix/bin/" 2>/dev/null
if [ "$ARM" = vanilla ]; then ( cd "$HOME/work/vanilla-strata/control" && ./bin/strata launch --stop >/dev/null 2>&1 ); fi
sleep 3
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
[ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock" 2>/dev/null
note "codex-compare block $VAR reps [$REPS] ended: $RUN"
}
trap cleanup EXIT
note "codex-compare block $VAR started: $RUN tasks=[$TASKS] reps=[$REPS] wall=$WALL cap=$ROUNDS; holds gpu.lock"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "something uses the GPU"; exit 3; fi
if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then echo "a stack process exists"; exit 3; fi
for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && { echo "port $p in use"; exit 3; }; done
export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
# what the agent's shell sees, identical for both arms: Node on PATH, no analytics, caches in /tmp (the sandbox writes the workspace and /tmp only)
export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/cmp-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; $CODEX --version; node --version; sha256sum "$CODEX"; } | tee "$RUN/$VAR/host-r$BLK.txt"
STK=$RUN/$VAR/stack-r$BLK; mkdir -p "$STK"
nvidia-smi --query-gpu=timestamp,temperature.gpu,clocks.sm,clocks.mem,power.draw,utilization.gpu --format=csv -l 10 >"$STK/mon.csv" 2>/dev/null & MON_PID=$!
run_cells() { # $1 upstream url, $2 upstream model, $3 engine log, $4 api key ('' = none)
local url=$1 model=$2 elog=$3 key=$4 rep task t1 rc list link
for rep in $REPS; do
list="smoke-mini $TASKS"
[ $((rep % 2)) = 0 ] && list="smoke-mini $(echo $TASKS | tr ' ' '\n' | tac | tr '\n' ' ')" # task order alternates with the repetition
for task in $list; do
CELL=$RUN/$VAR/$task-r$rep; [ "$task" = smoke-mini ] && CELL=$RUN/$VAR/smoke-mini-r$((100 + rep))
[ -f "$CELL/cell.json" ] && { log "cell $CELL already done: skipped"; continue; }
link=""; [ "$task" = nestng-crm ] && link="--link-tree backend/node_modules=$NM/backend/node_modules --link-tree frontend/node_modules=$NM/frontend/node_modules"
t1=$(date +%s)
E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout $((WALL + 900)) python3 -I "$CELLPY" --cell-dir "$CELL" --variant "$VAR" --task "$task" --rep "$([ "$task" = smoke-mini ] && echo $((100 + rep)) || echo $rep)" \
--tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit "$WALL" --max-rounds "$ROUNDS" \
--engine-log "$elog" --active-dir "$RUN/active-$VAR" --config-extra 'model_auto_compact_token_limit = 100000000' $link >"$CELL.out" 2>&1; rc=$?
log "cell $VAR $task r$rep rc=$rc $(( $(date +%s) - t1 )) s: $(tail -1 "$CELL.out" | cut -c1-200)"
done
done
}
if [ "$ARM" = ours ]; then
# ---- the release package, prepared ONCE into $CMP/ours-* (state, assets, prefix) and reused by every block ---------------------------------------
TARBALL=${CMP_TARBALL:-/data/leleka-e2e/release-5090/leleka-0.1.0-17e372944279-5090-linux-x86_64.tar.xz}
P=$CMP/ours-pkg; AS=$CMP/ours-assets; ST=$CMP/ours-state; PFX=$CMP/ours-prefix
if [ ! -x "$P/bin/leleka" ]; then mkdir -p "$P" && tar -xJf "$TARBALL" -C "$P" --strip-components=1 || { echo "unpack failed"; exit 5; }; fi
BIN=$P/bin
( cd "$P" && sha256sum --quiet -c SHA256SUMS && echo "SHA256SUMS ok" ); "$BIN/leleka" version | tee "$STK/version.txt"; sha256sum "$TARBALL" | tee -a "$STK/version.txt"
if [ ! -e "$AS/model" ]; then
mkdir -p "$AS/data"
ln -s "$A/model" "$AS/model"; ln -s "$A/tokenizer-assets" "$AS/tokenizer-assets"; ln -s "$A/qwen-iq3-s-l2-v4.kar" "$AS/qwen-iq3-s-l2-v4.kar"
cp "$A/qwen-iq3-s-l2-v4.kar.provenance.json" "$AS/qwen-iq3-s-l2-v4.kar.provenance.json"
cp -al "$A/data/iq3_s" "$AS/data/iq3_s"; cp -al "$A/data/mtp-rt" "$AS/data/mtp-rt"
fi
COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD"
if [ ! -f "$ST/leleka.json" ]; then timeout 3000 "$BIN/leleka" up --mode none $COMMON >"$STK/up-prepare.txt" 2>&1; log "up --mode none rc=$?"; fi
[ -f "$ST/leleka.json" ] || { echo "up did not prepare the state"; tail -20 "$STK/up-prepare.txt"; exit 6; }
log "leleka up --foreground (shipped configuration)"
t0=$(date +%s)
setsid "$BIN/leleka" up --foreground $COMMON --timeout-s 1800 >"$STK/up-foreground.txt" 2>&1 &
SUP_PID=$!
ready=0
for _ in $(seq 1 700); do
if "$PFX/bin/leleka" status --state-dir "$ST" >/dev/null 2>&1; then ready=1; break; fi
kill -0 "$SUP_PID" 2>/dev/null || break
sleep 3
done
if [ $ready != 1 ]; then log "NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$STK/up-foreground.txt" | cut -c1-240; exit 7; fi
log "ready after $(( $(date +%s) - t0 )) s"
echo "$(( $(date +%s) - t0 ))" >"$STK/ready_s.txt"
"$PFX/bin/leleka" status --state-dir "$ST" >"$STK/status.txt" 2>&1; "$PFX/bin/leleka" status --state-dir "$ST" --json >"$STK/status.json" 2>&1
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick.txt" 2>&1
KEY=$(cat "$ST/api-key")
run_cells http://127.0.0.1:8081 qwen-iq3 "$ST/logs/engine.log" "$KEY"
cp "$ST/logs/engine.log" "$STK/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$STK/requests.log" 2>/dev/null
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick-end.txt" 2>&1
stop_stack
else
# ---- vanilla Strata 0.2.6 (launcher + engine 0.1.50), shipped defaults unless CMP_VANILLA_LOSSY=0; state redirected into the run directory ----------
export XDG_CONFIG_HOME=$STK/xdg-config XDG_STATE_HOME=$STK/xdg-state
mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"; cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/"
if [ "${CMP_VANILLA_LOSSY:-1}" = 1 ]; then unset STRATA_ROUTE_TAIL_SKIP STRATA_PREFILL_CPU_SHARE; else export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; fi
unset STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE
S=$HOME/work/vanilla-strata/control/bin/strata
{ sha256sum "$HOME/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata"; cat "$HOME/work/vanilla-strata/control/VERSION" "$HOME/work/vanilla-strata/control/COMMIT" 2>/dev/null; env | grep -E '^STRATA_' | sort; } >"$STK/env.txt"
cd "$HOME/work/vanilla-strata/control"
t0=$(date +%s)
timeout 2400 "$S" launch --model iq3_s --family qwen --model-path "$A/model" --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes >"$STK/launch.out" 2>&1
log "vanilla launch rc=$? ready after $(( $(date +%s) - t0 )) s"
echo "$(( $(date +%s) - t0 ))" >"$STK/ready_s.txt"
if curl -fs http://127.0.0.1:8090/v1/models >"$STK/models.json"; then
MODEL=$(python3 -c "import json;print(json.load(open('$STK/models.json'))['data'][0]['id'])")
EL=$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log
run_cells http://127.0.0.1:8090 "$MODEL" "$EL" ""
cp "$EL" "$STK/engine.log" 2>/dev/null
grep -iE "route tail skip|CPU share" "$STK/engine.log" | head -4 >"$STK/lossy-lines.txt"
else
log "vanilla did not become ready"
fi
"$S" launch --stop >>"$STK/launch.out" 2>&1
sleep 8
fi
log "done"
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Re-run the acceptance over stored cells of the comparison with a corrected accept.py (variants LEL / VAN / VANL; delta/reaccept.py only knows V?).
cmp_reaccept.py RUNS_ROOT TASKS_ROOT task [task ...]
Old acceptance.log / acceptance.rc are kept as *.prev; cell.json gets `accepted`, `acceptance_rc`, `reaccepted_utc`. Prints every cell with its old and new verdict.
"""
import glob
import json
import os
import shutil
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "delta"))
import cell as cellmod # noqa: E402
import taskfile # noqa: E402
runs, tasks_root = sys.argv[1], sys.argv[2]
only = set(sys.argv[3:])
assert only, "name the tasks"
assert not taskfile.check(tasks_root), "task files differ from the manifest"
for cj in sorted(glob.glob(os.path.join(runs, "*", "*-r*", "cell.json"))):
d = os.path.dirname(cj)
info = json.load(open(cj))
if info["task"] not in only:
continue
for n in ("acceptance.log", "acceptance.rc"):
if os.path.exists(os.path.join(d, n)) and not os.path.exists(os.path.join(d, n + ".prev")):
shutil.copyfile(os.path.join(d, n), os.path.join(d, n + ".prev"))
rc = cellmod.run_acceptance(os.path.join(tasks_root, info["task"]), os.path.join(d, "workspace"), d, d)
open(os.path.join(d, "acceptance.rc"), "w").write("%d\n" % rc)
was = info.get("accepted")
info.update({"accepted": rc == 0, "acceptance_rc": rc, "reaccepted_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"reaccepted_tasks_manifest_sha256": taskfile.sha256_file(os.path.join(tasks_root, "MANIFEST.sha256"))})
json.dump(info, open(cj + ".part", "w"), indent=1)
os.replace(cj + ".part", cj)
print("%s %s r%s: accepted %s -> %s%s" % (info["variant"], info["task"], info["rep"], was, rc == 0, " CHANGED" if was != (rc == 0) else ""), flush=True)
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Side-by-side report of the vanilla-vs-Leleka Codex comparison (test tooling, stdlib only, Python 3.9+).
cmp_report.py RUNS_ROOT [--out DIR]
Reads every cell under RUNS_ROOT (`<VARIANT>/<task>-r<k>/cell.json`, written by cmp_codex_job.sh; warm-up cells `smoke-mini-r10x` are listed but not compared) through the
indexer of the lossy-delta study (delta/index.py) and writes RUNS_ROOT/_compare/{compare.md,compare.csv}:
quality accepted (objective acceptance), acceptance checks passed / total, failed model requests, termination, the six browser checks of the tic-tac-toe page when
RUNS_ROOT/_compare/browser.json exists ({"LEL/ttt-r1": "6/6", ...}, produced on the laptop by delta/browser_check_ttt.sh)
iterations model requests (rounds), tool calls, requests that ended in an error, input tokens re-read in total
speed wall seconds, decode tok/s (output tokens over decode time), mean time to first byte, mean seconds per request
Per task and variant: every repetition, mean and sd; then the paired difference Leleka minus vanilla for repetitions that exist in both arms. It makes NO verdict about quality
beyond the numbers; the sessions to read are linked (transcript.md per cell, written by index.py).
"""
import csv
import json
import os
import statistics
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "delta"))
import index # noqa: E402
NAMES = {"LEL": "Leleka (release package, KAR, shipped)", "VAN": "vanilla Strata 0.2.6 (shipped defaults)", "VANL": "vanilla Strata 0.2.6 (lossy defaults off)",
"LELK": "Leleka, KAR PLE (rtx5090-32g, standalone stack; KAR on / off study)", "LELG": "Leleka, GGUF PLE (rtx5090-32g-gguf-ple, standalone stack; KAR on / off study)"}
def acceptance(d):
p, f = 0, 0
try:
for line in open(os.path.join(d, "acceptance.log"), encoding="utf-8", errors="replace"):
if line.startswith("PASS "):
p += 1
elif line.startswith("FAIL "):
f += 1
except OSError:
pass
return p, p + f
def ttfb_mean(rs):
xs = [((r.get("t_first_byte_ms") or 0) - (r.get("t_start_ms") or 0)) / 1000 for r in rs if r.get("t_first_byte_ms")]
return round(statistics.mean(xs), 2) if xs else None
def mean_sd(xs):
xs = [x for x in xs if isinstance(x, (int, float))]
if not xs:
return "-"
if len(xs) == 1:
return "%.1f" % xs[0]
return "%.1f ± %.1f" % (statistics.mean(xs), statistics.stdev(xs))
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
root = os.path.abspath(args[0])
out = os.path.abspath(sys.argv[sys.argv.index("--out") + 1]) if "--out" in sys.argv else os.path.join(root, "_compare")
os.makedirs(out, exist_ok=True)
browser = {}
try:
browser = json.load(open(os.path.join(out, "browser.json")))
except (OSError, ValueError):
pass
rows = []
for sset, d, info in index.find_cells(root):
row, rs = index.summarize(sset, d, info)
ok, tot = acceptance(d)
row["acc_pass"], row["acc_total"] = ok, tot
row["ttfb_mean_s"] = ttfb_mean(rs)
row["s_per_request"] = round(row["model_s"] / row["rounds"], 2) if row["rounds"] else None
row["browser"] = browser.get("%s/%s-r%s" % (row["variant"], row["task"], row["rep"]), "")
row["cached_share"] = round(row["cached_tokens_total"] / row["in_tokens_total"], 3) if row["in_tokens_total"] else None
rows.append(row)
rows.sort(key=lambda r: (r["task"], r["variant"], r["rep"]))
if rows:
with open(os.path.join(out, "compare.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
tasks = sorted(set(r["task"] for r in rows if not r["task"].startswith("smoke")))
variants = [v for v in ("LEL", "VAN", "VANL", "LELK", "LELG") if any(r["variant"] == v for r in rows)]
md = ["# Codex comparison: %s" % ", ".join("%s = %s" % (v, NAMES[v]) for v in variants), "",
"Temperature 0 is injected for every arm; same Codex CLI, same prompts, same limits; no AGENTS.md pad. Greedy sessions are not reproducible run to run, so read the repetitions, not one cell.", ""]
for t in tasks:
md += ["## %s" % t, "", "| variant | rep | accepted | checks | browser | rounds (failed) | tool calls | wall s | decode tok/s | ttfb s | s/request | in tokens (cached) | ctx peak | termination |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in [x for x in rows if x["task"] == t]:
md.append("| %s | %s | %s | %s/%s | %s | %s (%s) | %s | %s | %s | %s | %s | %s (%s) | %s | %s |" % (
r["variant"], r["rep"], r["accepted"], r["acc_pass"], r["acc_total"], r["browser"] or "-", r["rounds"], r["rounds_failed"], r["tool_calls"], r["wall_s"],
r["decode_tok_s"], r["ttfb_mean_s"], r["s_per_request"], r["in_tokens_total"], r["cached_share"], r["ctx_peak"], r["termination"]))
md += ["", "| variant | n | accepted | rounds | tool calls | wall s | decode tok/s | s/request |", "|---|---|---|---|---|---|---|---|"]
for v in variants:
rs_ = [x for x in rows if x["task"] == t and x["variant"] == v]
if rs_:
md.append("| %s | %d | %d/%d | %s | %s | %s | %s | %s |" % (v, len(rs_), sum(1 for x in rs_ if x["accepted"] == "yes"), len(rs_), mean_sd([x["rounds"] for x in rs_]), mean_sd([x["tool_calls"] for x in rs_]),
mean_sd([x["wall_s"] for x in rs_]), mean_sd([x["decode_tok_s"] for x in rs_]), mean_sd([x["s_per_request"] for x in rs_])))
# the reference is VANL (vanilla with both lossy defaults off = the Original of the quality studies); VAN is what a vanilla user gets by default
for x, y, why in (("LEL", "VANL", "Leleka minus the reference"), ("VAN", "VANL", "vanilla shipped minus the reference (the cost of vanilla's lossy defaults)"), ("LEL", "VAN", "Leleka minus vanilla shipped"),
("LELG", "LELK", "GGUF PLE minus KAR PLE (same runtime, KAR on / off study)")):
if x not in variants or y not in variants:
continue
pairs = []
for rep in sorted(set(r["rep"] for r in rows if r["task"] == t)):
p1 = [r for r in rows if r["task"] == t and r["variant"] == x and r["rep"] == rep]
p2 = [r for r in rows if r["task"] == t and r["variant"] == y and r["rep"] == rep]
if p1 and p2:
pairs.append((p1[0], p2[0]))
if pairs:
md += ["", "Paired by repetition, %s %s (%d pair%s):" % (x + " - " + y, why, len(pairs), "" if len(pairs) == 1 else "s"), ""]
for key, label in (("rounds", "rounds"), ("tool_calls", "tool calls"), ("wall_s", "wall s"), ("decode_tok_s", "decode tok/s")):
ds = [p[0][key] - p[1][key] for p in pairs if isinstance(p[0][key], (int, float)) and isinstance(p[1][key], (int, float))]
md.append("* %s: %s (per pair: %s)" % (label, mean_sd(ds), ", ".join("%+.1f" % d for d in ds)))
md.append("")
md += ["## Sessions to read", ""]
md += ["* %s %s r%s: `%s` (%s, %s rounds)" % (r["variant"], r["task"], r["rep"], r["transcript"], r["accepted"], r["rounds"]) for r in rows if not r["task"].startswith("smoke")]
open(os.path.join(out, "compare.md"), "w", encoding="utf-8").write("\n".join(md) + "\n")
print("\n".join(md[:60]))
print("written", os.path.join(out, "compare.md"))
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# A holder-free window for cmp_codex_job.sh (vanilla arm), started DETACHED by a queue stub that has touched jobs/STOP and closed the holder's descriptor
# (the mechanism of the quality-245k and service-validation windows): cmp_window.sh LABEL (environment CMP_* is passed through)
# 1. waits until the lab holder has ended and its memfd is gone; 2. runs cmp_codex_job.sh; 3. ALWAYS restarts the lab holder afterwards, so the queue goes on.
set -u
LABEL=${1:-window}
C=/data/leleka-e2e/codex-compare
H=$HOME/work/gpu-runs/holder2
NOTES=/data/leleka-e2e/decode/notes.md
note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >> "$NOTES"; }
restart_holder() {
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then echo "a holder is already running"; return; fi
rmdir "$HOME/work/gpu-runs/MODEL.lock" 2>/dev/null # ours, if the payload died holding it
rm -f "$H/jobs/STOP" "$H/jobs/READY"
# the restarted holder must not inherit this window's CMP_* settings (it passes its environment on to every later queue stub: cmp-van-r2 once ran as VANL because of it)
( cd "$H" && unset CMP_ARM CMP_TASKS CMP_OPTIONAL CMP_REPS CMP_VANILLA_LOSSY CMP_WALL CMP_ROUNDS CMP_RUN CMP_TARBALL && setsid nohup bash /data/leleka-e2e/single-copy/tools/single-copy-holder.sh > "$H/holder3.out" 2>&1 < /dev/null & )
note "window $LABEL over: holder restarted with single-copy-holder.sh (holder3.out); queue open again"
}
trap restart_holder EXIT
note "window $LABEL: waiting for the holder to end (jobs/STOP is set), then cmp_codex_job.sh: arm=${CMP_ARM:-?} reps=[${CMP_REPS:-}] tasks=[${CMP_TASKS:-}]"
for _ in $(seq 1 1440); do
if ! pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null && [ ! -d "$HOME/work/gpu-runs/MODEL.lock" ]; then break; fi
sleep 5
done
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then note "window $LABEL: the holder did not end in 2 h, giving up (holder left as it is)"; trap - EXIT; exit 3; fi
sleep 5
note "window $LABEL: holder gone, MemAvailable $(awk '/^MemAvailable:/{printf "%d GiB", $2/1048576}' /proc/meminfo); starting"
bash "$C/tools/cmp_codex_job.sh" > "$C/window-$LABEL.out" 2>&1
note "window $LABEL: cmp_codex_job.sh ended rc=$?; log $C/window-$LABEL.out"
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
# Run ON the server: bash gen_stubs.sh PREFIX writes the queue stubs of the full comparison (setup + 9 blocks + report) and appends them to jobs/PRIORITY (backup first).
# Every stub sets ALL CMP_* variables itself (a restarted holder used to pass a window's variables on to later stubs). Finished cells are skipped by the job, so a pass only runs what is missing.
set -e
P=${1:?prefix}
H=$HOME/work/gpu-runs/holder2/jobs
cp $H/PRIORITY $H/PRIORITY.bak-$P
PRE='unset CMP_ARM CMP_TASKS CMP_OPTIONAL CMP_REPS CMP_VANILLA_LOSSY CMP_WALL CMP_ROUNDS CMP_RUN CMP_TARBALL'
cat > $H/$P-setup.sh <<'S'
#!/usr/bin/env bash
# codex-compare: CPU-only setup: shared node_modules of nestng-crm (idempotent) and the proof in the Codex sandbox (writes toolchain/NESTNG_OK)
set -e
export PATH=$(ls -d /data/leleka-e2e/codex-compare/toolchain/node-v*-linux-x64/bin | tail -1):$PATH
exec bash /data/leleka-e2e/codex-compare/tools/install-nestng-deps.sh
S
mk() { n=$P-$1; arm=$2; rep=$3; lossy=$4
if [ $arm = ours ]; then
cat > $H/$n.sh <<S
#!/usr/bin/env bash
# codex-compare: Leleka (release package, KAR, shipped), repetition $rep, ttt + nestng-crm (finished cells are skipped); nestng-crm REQUIRED
$PRE
export CMP_ARM=ours CMP_TASKS="ttt nestng-crm" CMP_REPS="$rep"
exec bash /data/leleka-e2e/codex-compare/tools/cmp_codex_job.sh
S
else
cat > $H/$n.sh <<S
#!/usr/bin/env bash
# codex-compare: vanilla Strata 0.2.6 (lossy defaults $([ $lossy = 1 ] && echo ON || echo OFF)), repetition $rep, ttt + nestng-crm (finished cells are skipped); holder-free window
$PRE
eval "exec \${LELEKA_STRA169_KAR_FD:-9}>&-"
touch "\$HOME/work/gpu-runs/holder2/jobs/STOP"
export CMP_ARM=vanilla CMP_VANILLA_LOSSY=$lossy CMP_TASKS="ttt nestng-crm" CMP_REPS="$rep"
setsid nohup bash /data/leleka-e2e/codex-compare/tools/cmp_window.sh $n > /data/leleka-e2e/codex-compare/window-$n.launch 2>&1 < /dev/null &
echo "$n: window launched"
S
fi; chmod +x $H/$n.sh; }
mk lel-r1 ours 1; mk van-r1 vanilla 1 1; mk vanl-r1 vanilla 1 0
mk vanl-r2 vanilla 2 0; mk van-r2 vanilla 2 1; mk lel-r2 ours 2
mk lel-r3 ours 3; mk vanl-r3 vanilla 3 0; mk van-r3 vanilla 3 1
sed "s/cmp-report/$P-report/" $H/cmp-report.sh > $H/$P-report.sh
chmod +x $H/$P-setup.sh $H/$P-report.sh
for n in setup lel-r1 van-r1 vanl-r1 vanl-r2 van-r2 lel-r2 lel-r3 vanl-r3 van-r3 report; do echo $P-$n; done >> $H/PRIORITY
echo "[$(date -u +%FT%TZ)] [DEV codex-compare] queued pass $P (setup, 9 blocks, report); backup PRIORITY.bak-$P" >> /data/leleka-e2e/decode/notes.md
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# Install the shared node_modules of the nestng-crm task on rnr5090 (runs ON the server as a CPU-only queue job, after install-node.sh), then prove the toolchain in the
# Codex sandbox (workspace-write, no network) on the bare seed. Writes codex-compare/toolchain/NESTNG_OK only when every step passed; cmp_codex_job.sh refuses nestng-crm without it.
set -euo pipefail
CMP=/data/leleka-e2e/codex-compare; NM=$CMP/nm; SEED=$CMP/tasks/nestng-crm/seed
CODEX=/home/para/work/codex-e2e/bin/codex
NOTES=/data/leleka-e2e/decode/notes.md
note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >>"$NOTES"; }
NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin | tail -1)
export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/cmp-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1
rm -f "$CMP/toolchain/NESTNG_OK"
python3 -I "$CMP/delta/taskfile.py" check "$CMP/tasks"
for d in backend frontend; do
if [ ! -d "$NM/$d/node_modules" ]; then
chmod -R u+w "$NM/$d" 2>/dev/null || true
mkdir -p "$NM/$d"; cp "$SEED/$d/package.json" "$SEED/$d/package-lock.json" "$NM/$d/"
( cd "$NM/$d" && nice -n 19 ionice -c3 npm ci --no-audit --no-fund ) > "$NM/install-$d.log" 2>&1 || { tail -20 "$NM/install-$d.log"; exit 4; }
fi
done
( cd "$NM/frontend" && npm ls @esbuild/linux-x64 2>&1 | tail -3 )
for d in backend frontend; do ( cd "$NM/$d" && find node_modules -type f -printf '%P %s\n' | sort | sha256sum | cut -c1-64 | sed "s|\$| $d file-list+sizes|" ); done | tee "$NM/DIGEST.txt"
chmod -R a-w "$NM/backend" "$NM/frontend"
# ---- the Codex sandbox on the bare seed: the same policy as the cells (workspace-write, no network), the same environment
S=$CMP/_active/sbx-$(date -u +%Y%m%dT%H%M%S); mkdir -p "$S/ws" "$S/home"
# hard-link farm exactly as the runner does it (cp -al would copy the read-only directory modes and then fail to fill them)
python3 -I -c "
import sys; sys.path.insert(0, '$CMP/delta')
import cell
for d in ('backend', 'frontend'):
cell.copy_tree('$SEED/' + d, '$S/ws/' + d) # writable copy, as the runner makes it (the installed seed is read-only)
cell.link_tree('$NM/' + d + '/node_modules', '$S/ws/' + d + '/node_modules')"
sed 's|@MODEL@|qwen-local|;s|@BASE_URL@|http://127.0.0.1:1|;s|@EFFORT@|medium|' "$CMP/config.toml.tmpl" > "$S/home/config.toml"
cd "$S/ws"
rc=0
CODEX_HOME=$S/home "$CODEX" sandbox -c 'sandbox_mode="workspace-write"' -c 'sandbox_workspace_write.network_access=false' -- bash -c '
set -e; node --version
cd backend; npm run build; test -f dist/main.js; npx jest --passWithNoTests; echo BACKEND-OK
cd ../frontend; npm run build; ls dist/*/browser | head -3; echo FRONTEND-OK' > "$S/sandbox.log" 2>&1 || rc=$?
tail -12 "$S/sandbox.log"
if [ $rc = 0 ] && grep -q BACKEND-OK "$S/sandbox.log" && grep -q FRONTEND-OK "$S/sandbox.log"; then
{ node --version; cat "$NM/DIGEST.txt"; } > "$CMP/toolchain/NESTNG_OK"
note "codex-compare: nestng-crm toolchain proven in the Codex sandbox (npm ci of both lockfiles, seed builds, rc=0); evidence $S/sandbox.log"
else
note "codex-compare: nestng-crm sandbox check FAILED rc=$rc; see $S/sandbox.log"; exit 5
fi
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Install the Node.js toolchain of the Codex comparison on rnr5090 (runs ON the server, as a CPU-only queue job so it cannot disturb a measuring job):
# the newest v22 LTS linux-x64 tarball from nodejs.org, checked against SHASUMS256.txt, unpacked into codex-compare/toolchain/ and made read-only.
set -euo pipefail
T=/data/leleka-e2e/codex-compare/toolchain
NOTES=/data/leleka-e2e/decode/notes.md
note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >>"$NOTES"; }
mkdir -p "$T/dl"; cd "$T/dl"
V=$(curl -fsS https://nodejs.org/dist/index.json | python3 -c "import json,sys; d=json.load(sys.stdin); print([x['version'] for x in d if x['version'].startswith('v22.') and x['lts']][0])")
F=node-$V-linux-x64.tar.xz
[ -f "$F" ] || curl -fsS -o "$F" "https://nodejs.org/dist/$V/$F"
curl -fsS -o SHASUMS256.txt "https://nodejs.org/dist/$V/SHASUMS256.txt"
grep " $F\$" SHASUMS256.txt | sha256sum -c -
if [ ! -x "$T/node-$V-linux-x64/bin/node" ]; then nice -n 19 ionice -c3 tar -xJf "$F" -C "$T"; chmod -R a-w "$T/node-$V-linux-x64"; fi
export PATH="$T/node-$V-linux-x64/bin:$PATH" # npm's shebang is `env node`
node --version
npm --version
note "codex-compare toolchain: node $V installed in $T ($(grep " $F\$" SHASUMS256.txt | cut -c1-16)...)"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Install the vanilla-vs-Leleka Codex comparison on rnr5090 from this worktree (small writes only: scripts and task files; no model data).
#
# bash scripts/e2e/codex/compare/install.sh
#
# Server layout (inside the work folder ~/work/leleka = /data/leleka-e2e):
# codex-compare/tasks/ frozen task set (read-only), without reference/ solutions; tasks/_external/ holds the vendored three.js
# codex-compare/delta/ runner scripts (read-only): cell.py, logproxy.py, taskfile.py, index.py
# codex-compare/tools/ cmp_codex_job.sh, cmp_window.sh, cmp_report.py (read-only)
# codex-compare/config.toml.tmpl, INSTALL.sha256
# codex-compare/toolchain/ Node.js (install-node.sh), nm/ shared node_modules (install-nestng-deps.sh), runs/ results
# Re-running replaces the scripts; nothing is hard-deleted (earlier installs go to ~/work/leleka/garbage/ with a line in LOG.txt).
set -euo pipefail
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
CODEX_DIR=$(cd "$HERE/.." && pwd) # scripts/e2e/codex
python3 "$CODEX_DIR/tasks/freeze.py" >/dev/null
python3 "$CODEX_DIR/delta/taskfile.py" check "$CODEX_DIR/tasks" >/dev/null
R=work/leleka/codex-compare
ssh rnr5090 bash -s "$R" <<'REMOTE'
set -euo pipefail
R=$1
mkdir -p "$HOME/$R"; cd "$HOME/$R"
chmod -R u+w tasks delta tools config.toml.tmpl 2>/dev/null || true
if [ -e _stage ]; then G=$HOME/work/leleka/garbage/codex-compare-stage-$(date -u +%Y%m%dT%H%M%S); mkdir -p "$G"; mv _stage "$G/"; echo "$(date -u +%FT%TZ) codex-compare: leftover _stage moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt"; fi
mkdir -p _stage/delta _stage/tasks _stage/tools
REMOTE
STAGE=$R/_stage
tar -C "$CODEX_DIR" --exclude=__pycache__ --exclude='reference' --exclude='selftest.py' -cf - tasks | ssh rnr5090 "tar -xf - -C $STAGE/tasks --strip-components=1"
tar -C "$CODEX_DIR" --exclude=__pycache__ -cf - delta | ssh rnr5090 "tar -xf - -C $STAGE/delta --strip-components=1"
tar -C "$HERE" --exclude=__pycache__ -cf - cmp_codex_job.sh cmp_window.sh cmp_report.py install-node.sh install-nestng-deps.sh gen_stubs.sh | ssh rnr5090 "tar -xf - -C $STAGE/tools"
scp -q "$CODEX_DIR/config.toml.tmpl" "rnr5090:$STAGE/config.toml.tmpl"
ssh rnr5090 bash -s "$R" <<'REMOTE'
set -euo pipefail
R=$1
cd "$HOME/$R/_stage"
mkdir -p tasks/_external
cp "$HOME/work/codex-e2e/vendor/three.module.min.js" tasks/_external/
python3 -I delta/taskfile.py check tasks
cd "$HOME/$R"
G=$HOME/work/leleka/garbage/codex-compare-prev-$(date -u +%Y%m%dT%H%M%S)
mkdir -p "$G"
for x in delta tasks tools config.toml.tmpl; do [ -e "$x" ] && mv "$x" "$G/"; done
echo "$(date -u +%FT%TZ) codex-compare: previous install moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt"
mv _stage/delta delta; mv _stage/tasks tasks; mv _stage/tools tools; mv _stage/config.toml.tmpl config.toml.tmpl; rmdir _stage
mkdir -p runs _active
chmod -R a-w tasks delta tools config.toml.tmpl
( find tasks delta tools -type f -print0 | sort -z | xargs -0 sha256sum; sha256sum config.toml.tmpl ) > INSTALL.sha256.new
mv -f INSTALL.sha256.new INSTALL.sha256
wc -l INSTALL.sha256
REMOTE
echo installed
+39 -1
View File
@@ -44,6 +44,25 @@ def copy_tree(src, dst):
shutil.copyfile(os.path.join(root, n), os.path.join(dst, rel, n) if rel != "." else os.path.join(dst, n))
def link_tree(src, dst):
"""Hard-link a (read-only, shared) tree into the workspace: no data is written, only directory entries; symlinks are recreated. Used for node_modules."""
for root, dirs, files in os.walk(src):
rel = os.path.relpath(root, src)
out = dst if rel == "." else os.path.join(dst, rel)
os.makedirs(out, exist_ok=True)
for n in files:
s, d = os.path.join(root, n), os.path.join(out, n)
if os.path.islink(s):
os.symlink(os.readlink(s), d)
else:
os.link(s, d)
for n in list(dirs):
s = os.path.join(root, n)
if os.path.islink(s):
os.symlink(os.readlink(s), os.path.join(out, n))
dirs.remove(n)
def run_acceptance(tdir, ws, cell, scratch):
"""Run the task's accept.py from a WRITABLE copy of the task directory (the installed task files are read-only, and the acceptance scripts copy
hidden files over each other). The copy has the same bytes as the frozen files (checked against the manifest before the run). -> exit code"""
@@ -92,6 +111,9 @@ def main():
ap.add_argument("--engine-log", default="")
ap.add_argument("--stack-meta", default="")
ap.add_argument("--fix-date", default="2026-10-30", help="the <current_date> Codex puts into the prompt is rewritten to this date by the proxy for every variant")
ap.add_argument("--agents-md", default="", help="a file copied to $CODEX_HOME/AGENTS.md: Codex puts it into the first request as a user message (the long-context pad of the 245k study; no 32 KiB cap for this location)")
ap.add_argument("--config-extra", default="", help="text appended to config.toml (e.g. model_auto_compact_token_limit)")
ap.add_argument("--link-tree", action="append", default=[], metavar="DST=SRC", help="after the seed digest check, hard-link the tree SRC to workspace/DST (node_modules of the Node tasks); repeatable")
ap.add_argument("--active-dir", default="", help="directory in which the workspace lives while Codex runs (moved into the cell afterwards)")
a = ap.parse_args()
@@ -134,6 +156,15 @@ def main():
shutil.rmtree(ws, ignore_errors=True)
return 3
seed_digest = have
links = []
for spec in a.link_tree:
dst_rel, _, src = spec.partition("=")
if not dst_rel or not os.path.isdir(src):
print("refusing: --link-tree %r: source directory missing" % spec, file=sys.stderr)
shutil.rmtree(ws, ignore_errors=True)
return 3
link_tree(src, os.path.join(ws, dst_rel))
links.append({"dst": dst_rel, "src": src})
with open(os.path.join(cell, "prompt.txt"), "w", encoding="utf-8", newline="") as f:
f.write(prompt)
@@ -145,7 +176,13 @@ def main():
os.makedirs(chome, mode=0o700)
tmpl = open(os.path.join(HERE, "..", "config.toml.tmpl"), encoding="utf-8").read()
cfg = tmpl.replace("@MODEL@", "qwen-local").replace("@BASE_URL@", "http://127.0.0.1:%d" % port).replace("@EFFORT@", a.effort)
if a.config_extra:
nl = chr(10)
marker = nl + "[sandbox_workspace_write]"
cfg = cfg.replace(marker, nl + a.config_extra.replace("|", nl) + nl + marker, 1)
open(os.path.join(chome, "config.toml"), "w", encoding="utf-8").write(cfg)
if a.agents_md:
shutil.copyfile(a.agents_md, os.path.join(chome, "AGENTS.md"))
# --- logging proxy
pdir = os.path.join(cell, "proxy")
@@ -265,7 +302,8 @@ def main():
"prompt_sha256": taskfile.sha256_text(prompt), "seed_digest": seed_digest, "codex_bin": a.codex_bin, "codex_sha256": a.codex_sha256,
"upstream": a.upstream, "upstream_model": a.upstream_model, "engine_log_start_offset": elog_start, "active_workspace": os.path.join(active, "ws") if a.active_dir else final_ws,
"tasks_manifest_sha256": taskfile.sha256_file(os.path.join(a.tasks_root, "MANIFEST.sha256")),
"final_message_tail": final_msg["text"][-800:], "stack": stack}
"agents_md": {"path": a.agents_md, "sha256": taskfile.sha256_file(a.agents_md), "bytes": os.path.getsize(a.agents_md)} if a.agents_md else None, "config_extra": a.config_extra,
"link_trees": links, "final_message_tail": final_msg["text"][-800:], "stack": stack}
tmp = os.path.join(cell, "cell.json.part")
json.dump(info, open(tmp, "w"), indent=1)
os.replace(tmp, os.path.join(cell, "cell.json"))
+1 -1
View File
@@ -15,7 +15,7 @@ import sys
BEGIN = "<!-- PROMPT BEGIN -->"
END = "<!-- PROMPT END -->"
SKIP_DIRS = {"__pycache__"}
SKIP_DIRS = {"__pycache__", "node_modules", ".angular", "dist"} # node_modules: hard-linked in by the runner (--link-tree), never part of a seed or a workspace digest
def sha256_file(path):
+29 -3
View File
@@ -29,7 +29,6 @@ c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched
691ed0b32061a5bff822a7816d3856f39f6bb532f927b1e35018e8149828f956 debuglog-sched/hidden/tests/test_service.py
3d6624767165d46c961f724824135f1cbb0f07588d3240301e0eb8c1eda2cca7 debuglog-sched/hidden/tests/test_sim.py
427404b7cb2a68000c9c040823ddec455d00e46a75e3df7825ceaa05dc478784 debuglog-sched/hidden/tests/test_store_queue.py
af49af474c97e5c48ed99c56f34a21ff0e4640b43c70e60749c0ea034b2809f5 debuglog-sched/seed/logs/service.log
877a32c226a527efeee6cfa49037b56c8f7cb9939e1bc3aff4cd389f0995a8de debuglog-sched/seed/run_sim.py
ffc6d8f9032bb7587a6c15736511b2b294bf6cad48447a77affe8c9c1fd717cb debuglog-sched/seed/sched/__init__.py
b2c5b733771d2bc3dd99bee690d9c602e4fbf2c3da3c8cf493e7989e3ce57714 debuglog-sched/seed/sched/clock.py
@@ -53,8 +52,8 @@ c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched
427404b7cb2a68000c9c040823ddec455d00e46a75e3df7825ceaa05dc478784 debuglog-sched/seed/tests/test_store_queue.py
e8e52f9d50662a7a1d113ccc5723b4bc4c7465668f59f00502e0f6645a523943 debuglog-sched/task.md
PROMPT debuglog-sched d596947b7043c51cd4cf36b9a35ed84a330113421d2f47d1cefb34893f507505
SEEDTREE debuglog-sched 8ffbcf1773f488add8aa764621d4e574fcf88bf35c1c99dfbe9b75febe4d4ca3
TASK debuglog-sched 3cd1971c02853761ebc8cd5e2ddbb89636aaf5452eccf780a0020aed01c21844
SEEDTREE debuglog-sched 653457f198efc18185f9fab0198a622b2dedc0fc0d49e92368fb1adfac4968b3
TASK debuglog-sched 8902b872566eb69a4f736a2843a590d0ba740a49a9dbdd14b6d09049243cef7f
REFERENCE debuglog-sched 0069c1f700e546bb692b14698c888742ea4dc82ae2aa3bc20f64701a5cb16026
fa439d6b0c7e68cc66cb3cde833200cceb7c9d6cca60172680e9b172b7f41e0c feature-query/accept.py
d1f85a4c31091f1b862791927fb35929a20b95f5b64fa2ff0fb7dd8f9f370d07 feature-query/hidden/pristine_tests/test_csv_cli.py
@@ -127,6 +126,33 @@ PROMPT fixbug-ledger 08f5c2fd63c199fa24274a7d36099354b27b7e2bde1e126a833a3a97307
SEEDTREE fixbug-ledger 41ba1db9dedeae30d1c189d70e45660639cb8e798bdf94dfb9a27e54bdb18c56
TASK fixbug-ledger c6e7743467badd427a94bad605e972b9f19c78b3cd54b141501c1dee59417302
REFERENCE fixbug-ledger 08eb07de9e7f22a9266478af9ed3643cf7bc956e32a867e903d69f2e7777f68c
b2e6c690d0a2dca9d90d2ca71261cf0cedfca30fc61ae822644d8e461941186a nestng-crm/accept.py
7594fbe27ca0a1a318f7146b741ffc6d49a1f356bca849cb1e6cd5324d88440a nestng-crm/seed/README.md
bcb15e3049ff5d131762d2bfe3a6f917c3c64c83ac772467a4073975cd423b5b nestng-crm/seed/backend/nest-cli.json
23a3084dc848bf127f97696563cab0ec113358585df6245d270b1f123c7fd533 nestng-crm/seed/backend/package-lock.json
61084aa1cffbeaa5c511a592ee61f048a1cf26f44b00299b27e5174cb5aa9291 nestng-crm/seed/backend/package.json
0472c27a52a21ebecbf6b339b052adcd4bc5e8ef02ffe8860f8782687d0ebe32 nestng-crm/seed/backend/src/app.module.ts
e25d9bd8f80b6ffbcc8826ed1b407e747e4fbe346c5bab62cbe5837da4eeb189 nestng-crm/seed/backend/src/main.ts
81e47b6032f112b49cc054a823dc9fadfbd88c56a02e7e2369722363433adbca nestng-crm/seed/backend/test/jest-e2e.json
3a016b4ee9713cd16295128bad42e6077e5ecd8c2ed225caa7d1e0e3f1c7f03f nestng-crm/seed/backend/tsconfig.build.json
00a3a37d6dad7a7b758564bd8d55e37de4b9c263a9d1072b8c7dfb4cdf053603 nestng-crm/seed/backend/tsconfig.json
e8716af95fea94712bc6a2054125164fc808dce2f5658af653562188288adb46 nestng-crm/seed/frontend/angular.json
87f8dc2edd3bb892330bb23ea3675dc2e173cbafbd35865fccc9168a58bca72c nestng-crm/seed/frontend/package-lock.json
e2ecb11d8c51cbcf24f01744d3023b96a92251eebc54dac85336b756ba97f63a nestng-crm/seed/frontend/package.json
08400dbcd6dd62da4bcd1daae84bfc4a6c2f995882cc033af8267e9af75b7347 nestng-crm/seed/frontend/src/app/app.config.ts
1dfd8848c3f15bd203df7fba51f1b94f0765e5972baca0a9f99b391b64ffb6cf nestng-crm/seed/frontend/src/app/app.html
e2ef74b4c1f7f52a30a417c6808f01b2a29e69bb0d20302527ae5001607f7180 nestng-crm/seed/frontend/src/app/app.routes.ts
e511bd4ee0785273b2d2b252382922e189fec69dfbc660dac5581fd284262d7e nestng-crm/seed/frontend/src/app/app.ts
d699b21284e03cf25dbd4022a9eca45f9fbcd460027e83f1de998c3aa98b860b nestng-crm/seed/frontend/src/index.html
ecc610fb7d56c95a01a8aa6c274a63210d45b2944dd6b9a88b2c8f70b6351037 nestng-crm/seed/frontend/src/main.ts
8996c8346765ab6f23928d29788bb2b6dd7d7baf0df0f8ed3ff584635f57afd6 nestng-crm/seed/frontend/src/styles.css
fc4898318bf701861de6a406ede37e7e848aad322c022daa4cd9e93ecbcc9ea4 nestng-crm/seed/frontend/tsconfig.app.json
fe90e111c2d5ecf01e050aac28a18db100967b1407c2d3c47149efb89466e47b nestng-crm/seed/frontend/tsconfig.json
07926c531fbc3456b19e33157e4174e74550e8cc7858b41a95358618722d71b7 nestng-crm/task.md
PROMPT nestng-crm 240f3cc6b5f179501efeb94589a7dc711983538db551a603a1820893112d4e62
SEEDTREE nestng-crm 55378d7bb67c1f5f53d9977aaa7ec50a3aed37c4125ea21735bfce00966817e8
TASK nestng-crm 927bdb5f18e56e782e787a52faeaa9eb8d3d35409a900cd15ca03e8e54b678a4
REFERENCE nestng-crm f79ad58aaede28a21e6d413f8604287c01251e9682727b629a268ecc2d509dee
2c01fffcdf4a1e959d9d3adbbd5965cf8d59e69dd330a3568966812b2f672432 refactor-shop/accept.py
f4bf75da964c784234c685b44b41c98846c6c03d46f8277115cb756d224d5f4c refactor-shop/hidden/behaviour.py
99546b78de332fc57d310eb3d0699b9d8110f662032e216c4ab886377e5588e2 refactor-shop/hidden/helpers_h.py
@@ -0,0 +1,527 @@
#!/usr/bin/env python3
"""Acceptance for the NestJS + Angular CRM task (no network, no browser; Node.js on PATH).
accept.py WORKSPACE exit 0 = every check passed
Everything runs on a COPY of the workspace in a temp directory (the workspace itself is only read). node_modules are not copied: they are linked
(symlink, on Windows a junction) from WORKSPACE/<dir>/node_modules, or, when the workspace has none (the self-test builds it from the seed alone), from
$NESTNG_NM_ROOT/<dir>/node_modules. Node and npm come from PATH; $NESTNG_NODE_BIN (a directory) is put in front of it. Expected run time 30-120 s.
Groups: structure (read only) / backend build + black-box REST checks over HTTP / the agent's own tests / frontend build / static checks of the frontend.
"""
import glob
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
WS = os.path.abspath(sys.argv[1])
NM_ROOT = os.environ.get("NESTNG_NM_ROOT", "")
STAGES = ["lead", "qualified", "proposal", "won", "lost"]
MIN_TESTS = 15
results = []
def check(name, ok, detail=""):
results.append(bool(ok))
print(("PASS " if ok else "FAIL ") + name + ("" if ok else " :: " + str(detail).replace("\n", " | ")[:300]), flush=True)
def guarded(name, fn):
"""Run fn() -> (ok, detail); an exception is a failed check, not a crash."""
try:
ok, detail = fn()
except Exception as e: # noqa: BLE001
ok, detail = False, "%s: %s" % (type(e).__name__, e)
check(name, ok, detail)
def read(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
except OSError:
return ""
# ---------------------------------------------------------------- environment
ENV = dict(os.environ)
if os.environ.get("NESTNG_NODE_BIN"):
ENV["PATH"] = os.environ["NESTNG_NODE_BIN"] + os.pathsep + ENV.get("PATH", "")
ENV.update({"CI": "1", "NG_CLI_ANALYTICS": "false", "NG_DISABLE_VERSION_CHECK": "1", "NO_COLOR": "1", "FORCE_COLOR": "0",
"npm_config_update_notifier": "false", "npm_config_fund": "false", "npm_config_audit": "false"})
NPM = shutil.which("npm", path=ENV["PATH"])
NODE = shutil.which("node", path=ENV["PATH"])
def run(cmd, cwd, timeout, env=None):
p = subprocess.run(cmd, cwd=cwd, env=env or ENV, capture_output=True, text=True, timeout=timeout, errors="replace")
return p.returncode, (p.stdout or "") + (p.stderr or "")
def link_dir(target, link):
try:
os.symlink(target, link, target_is_directory=True)
except (OSError, NotImplementedError):
if os.name != "nt":
raise
subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True)
def unlink_dir(link):
"""Remove a link made by link_dir without touching what it points at."""
try:
os.unlink(link)
except OSError:
try:
os.rmdir(link)
except OSError:
pass
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def is_int(v):
return isinstance(v, int) and not isinstance(v, bool)
# ---------------------------------------------------------------- 1. structure
guarded("structure: backend/package.json with build, test and test:e2e scripts", lambda: (
all(k in json.loads(read(os.path.join(WS, "backend", "package.json")) or "{}").get("scripts", {}) for k in ("build", "test", "test:e2e")), "scripts missing"))
guarded("structure: frontend/package.json with a build script", lambda: (
"build" in json.loads(read(os.path.join(WS, "frontend", "package.json")) or "{}").get("scripts", {}), "build script missing"))
guarded("structure: backend/src/main.ts exists", lambda: (os.path.isfile(os.path.join(WS, "backend", "src", "main.ts")), "missing"))
guarded("structure: backend has at least one test file", lambda: (
len(glob.glob(os.path.join(WS, "backend", "src", "**", "*.spec.ts"), recursive=True) + glob.glob(os.path.join(WS, "backend", "test", "**", "*.ts"), recursive=True)) > 0, "no *.spec.ts / test/*.ts"))
guarded("structure: frontend/proxy.conf.json maps /api to port 3000 on the loopback", lambda: (
re.search(r"(127\.0\.0\.1|localhost):3000", json.dumps(json.loads(read(os.path.join(WS, "frontend", "proxy.conf.json")) or "{}").get("/api", {}))) is not None, "no /api proxy target"))
guarded("structure: README.md exists and is not empty", lambda: (len(read(os.path.join(WS, "README.md")).strip()) > 20, "missing or empty"))
guarded("structure: node and npm are available", lambda: (NPM is not None and NODE is not None, "node=%s npm=%s" % (NODE, NPM)))
# ---------------------------------------------------------------- temp copy of the workspace
tmp = tempfile.mkdtemp(prefix="nestng-ws-")
copy = os.path.join(tmp, "ws")
links = []
nm_ok = {}
try:
shutil.copytree(WS, copy, ignore=shutil.ignore_patterns("node_modules", "dist", ".angular", "coverage", "out-tsc", "*.tsbuildinfo", ".git"))
for d in ("backend", "frontend"):
src = os.path.join(WS, d, "node_modules")
if not os.path.isdir(src) and NM_ROOT:
src = os.path.join(NM_ROOT, d, "node_modules")
nm_ok[d] = os.path.isdir(src) and os.path.isdir(os.path.join(copy, d))
if nm_ok[d]:
link = os.path.join(copy, d, "node_modules")
link_dir(os.path.realpath(src), link)
links.append(link)
BE, FE = os.path.join(copy, "backend"), os.path.join(copy, "frontend")
# ------------------------------------------------------------ 2. backend build and start
built = {"ok": False}
def backend_build():
if not (NPM and nm_ok.get("backend")):
return False, "no npm or no backend node_modules"
rc, out = run([NPM, "run", "build"], BE, 240)
built["ok"] = rc == 0 and os.path.isfile(os.path.join(BE, "dist", "main.js"))
return built["ok"], "rc=%s dist/main.js=%s %s" % (rc, os.path.isfile(os.path.join(BE, "dist", "main.js")), out[-200:])
guarded("backend: npm run build succeeds and produces dist/main.js", backend_build)
port = free_port()
server = None
server_log = os.path.join(tmp, "server.log")
if built["ok"]:
env = dict(ENV)
env["PORT"] = str(port)
logf = open(server_log, "w")
server = subprocess.Popen([NODE, os.path.join("dist", "main.js")], cwd=BE, env=env, stdout=logf, stderr=subprocess.STDOUT)
up = False
for _ in range(120):
if server.poll() is not None:
break
try:
socket.create_connection(("127.0.0.1", port), timeout=0.3).close()
up = True
break
except OSError:
time.sleep(0.25)
else:
up = False
guarded("backend: node dist/main.js listens on 127.0.0.1:$PORT", lambda: (up, "not listening; log: " + read(server_log)[-200:]))
BASE = "http://127.0.0.1:%d" % port
def call(method, path, body=None):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(BASE + path, data=data, method=method, headers={"Content-Type": "application/json", "Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=15) as r:
raw, status = r.read(), r.status
except urllib.error.HTTPError as e:
raw, status = e.read(), e.code
try:
js = json.loads(raw.decode("utf-8")) if raw else None
except ValueError:
js = None
return status, js
TAG = "zq%d" % (int(time.time()) % 100000)
def rest(name, fn):
if not up:
check(name, False, "the server is not running")
else:
guarded(name, fn)
def mk_company(name=None, **extra):
s, j = call("POST", "/api/companies", dict({"name": name or TAG + "-co"}, **extra))
assert s == 201 and is_int(j.get("id")), "create company: %s %s" % (s, j)
return j
def mk_contact(name=None, **extra):
s, j = call("POST", "/api/contacts", dict({"name": name or TAG + "-ct"}, **extra))
assert s == 201 and is_int(j.get("id")), "create contact: %s %s" % (s, j)
return j
def mk_deal(title=None, **extra):
s, j = call("POST", "/api/deals", dict({"title": title or TAG + "-dl"}, **extra))
assert s == 201 and is_int(j.get("id")), "create deal: %s %s" % (s, j)
return j
# ---- companies
def t_company_create():
s, j = call("POST", "/api/companies", {"name": TAG + " Acme", "website": "https://acme.test", "industry": "Tools"})
ok = s == 201 and is_int(j.get("id")) and j.get("name") == TAG + " Acme" and j.get("website") == "https://acme.test" and j.get("industry") == "Tools"
return ok, "%s %s" % (s, j)
def t_company_name_required():
a = call("POST", "/api/companies", {"website": "x"})[0]
b = call("POST", "/api/companies", {"name": ""})[0]
c = call("POST", "/api/companies", {"name": 12})[0]
return (a, b, c) == (400, 400, 400), "statuses %s %s %s" % (a, b, c)
def t_company_get_list():
c = mk_company()
s, j = call("GET", "/api/companies/%d" % c["id"])
s2, lst = call("GET", "/api/companies")
ok = s == 200 and j.get("id") == c["id"] and s2 == 200 and isinstance(lst, list) and any(x.get("id") == c["id"] for x in lst)
return ok, "%s %s %s" % (s, s2, type(lst))
def t_company_404():
a = call("GET", "/api/companies/987654")[0]
b = call("PUT", "/api/companies/987654", {"name": "x"})[0]
c = call("DELETE", "/api/companies/987654")[0]
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
def t_company_update():
c = mk_company(industry="Old")
s, j = call("PUT", "/api/companies/%d" % c["id"], {"name": c["name"] + "-x", "industry": "New"})
s2, g = call("GET", "/api/companies/%d" % c["id"])
ok = s == 200 and j.get("industry") == "New" and g.get("name") == c["name"] + "-x" and g.get("industry") == "New"
return ok, "%s %s %s" % (s, j, g)
def t_company_update_invalid():
c = mk_company()
s = call("PUT", "/api/companies/%d" % c["id"], {"name": ""})[0]
return s == 400, "status %s" % s
def t_company_search():
mk_company(TAG + " Searchable Widgets")
mk_company(TAG + " Other")
s, j = call("GET", "/api/companies?q=" + TAG.upper() + "%20SEARCHABLE")
ok = s == 200 and len(j) == 1 and j[0]["name"].endswith("Searchable Widgets")
return ok, "%s %s" % (s, j)
def t_company_delete():
c = mk_company()
a = call("DELETE", "/api/companies/%d" % c["id"])[0]
b = call("GET", "/api/companies/%d" % c["id"])[0]
return (a, b) == (204, 404), "statuses %s %s" % (a, b)
# ---- contacts
def t_contact_create():
c = mk_company()
s, j = call("POST", "/api/contacts", {"name": TAG + " Ann", "email": "ann@acme.test", "phone": "123", "companyId": c["id"]})
ok = s == 201 and is_int(j.get("id")) and j.get("email") == "ann@acme.test" and j.get("phone") == "123" and j.get("companyId") == c["id"]
return ok, "%s %s" % (s, j)
def t_contact_name_required():
a = call("POST", "/api/contacts", {"email": "a@b.co"})[0]
b = call("POST", "/api/contacts", {"name": ""})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_contact_bad_email():
s = call("POST", "/api/contacts", {"name": "Bob", "email": "not-an-email"})[0]
return s == 400, "status %s" % s
def t_contact_unknown_company():
s = call("POST", "/api/contacts", {"name": "Bob", "companyId": 987654})[0]
return s == 400, "status %s" % s
def t_contact_search():
mk_contact(TAG + " Searchable Ann", email="ann.%s@one.test" % TAG)
mk_contact(TAG + " Bob", email="bob.%s@two.test" % TAG)
s, byname = call("GET", "/api/contacts?q=" + TAG.upper() + "%20searchable")
s2, byemail = call("GET", "/api/contacts?q=BOB." + TAG.upper() + "@TWO")
ok = s == 200 and len(byname) == 1 and s2 == 200 and len(byemail) == 1 and byemail[0]["name"].endswith("Bob")
return ok, "%s %s | %s %s" % (s, byname, s2, byemail)
def t_contact_update_clear_company():
co = mk_company()
ct = mk_contact(companyId=co["id"])
s, j = call("PUT", "/api/contacts/%d" % ct["id"], {"phone": "999", "companyId": None})
g = call("GET", "/api/contacts/%d" % ct["id"])[1]
ok = s == 200 and j.get("phone") == "999" and j.get("companyId") is None and g.get("companyId") is None and g.get("phone") == "999"
return ok, "%s %s %s" % (s, j, g)
def t_contact_404_delete():
ct = mk_contact()
a = call("GET", "/api/contacts/987654")[0]
b = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
c = call("GET", "/api/contacts/%d" % ct["id"])[0]
return (a, b, c) == (404, 204, 404), "statuses %s %s %s" % (a, b, c)
# ---- deals
def t_deal_defaults():
s, j = call("POST", "/api/deals", {"title": TAG + " Renewal"})
ok = s == 201 and is_int(j.get("id")) and j.get("amount") == 0 and j.get("stage") == "lead" and j.get("companyId") is None and j.get("contactId") is None
return ok, "%s %s" % (s, j)
def t_deal_full():
co, ct = mk_company(), mk_contact()
s, j = call("POST", "/api/deals", {"title": TAG + " Full", "amount": 1234.5, "stage": "proposal", "companyId": co["id"], "contactId": ct["id"]})
ok = s == 201 and j.get("amount") == 1234.5 and j.get("stage") == "proposal" and j.get("companyId") == co["id"] and j.get("contactId") == ct["id"]
return ok, "%s %s" % (s, j)
def t_deal_title_required():
a = call("POST", "/api/deals", {"amount": 5})[0]
b = call("POST", "/api/deals", {"title": ""})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_amount_not_number():
a = call("POST", "/api/deals", {"title": "x", "amount": "lots"})[0]
b = call("POST", "/api/deals", {"title": "x", "amount": -5})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_invalid_stage():
s = call("POST", "/api/deals", {"title": "x", "stage": "maybe"})[0]
return s == 400, "status %s" % s
def t_deal_unknown_refs():
a = call("POST", "/api/deals", {"title": "x", "companyId": 987654})[0]
b = call("POST", "/api/deals", {"title": "x", "contactId": 987654})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_move_stage():
d = mk_deal(amount=10)
s, j = call("PUT", "/api/deals/%d" % d["id"], {"stage": "qualified"})
g = call("GET", "/api/deals/%d" % d["id"])[1]
ok = s == 200 and j.get("stage") == "qualified" and g.get("stage") == "qualified" and g.get("title") == d["title"] and g.get("amount") == 10
return ok, "%s %s %s" % (s, j, g)
def t_deal_put_invalid_stage():
d = mk_deal()
s = call("PUT", "/api/deals/%d" % d["id"], {"stage": "nope"})[0]
g = call("GET", "/api/deals/%d" % d["id"])[1]
return s == 400 and g.get("stage") == "lead", "status %s stage %s" % (s, g.get("stage"))
def t_deal_404():
a = call("GET", "/api/deals/987654")[0]
b = call("PUT", "/api/deals/987654", {"stage": "won"})[0]
c = call("DELETE", "/api/deals/987654")[0]
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
def t_deal_stage_filter():
mk_deal(TAG + " f1", stage="won")
mk_deal(TAG + " f2", stage="lost")
s, j = call("GET", "/api/deals?stage=won")
ok = s == 200 and len(j) >= 1 and all(d["stage"] == "won" for d in j) and any(d["title"] == TAG + " f1" for d in j) and not any(d["title"] == TAG + " f2" for d in j)
return ok, "%s n=%s" % (s, None if j is None else len(j))
def t_deal_stage_bogus():
s = call("GET", "/api/deals?stage=bogus")[0]
return s == 400, "status %s" % s
def t_deal_q_and_stage():
mk_deal(TAG + " Alpha one", stage="won")
mk_deal(TAG + " Alpha two", stage="lost")
mk_deal(TAG + " Beta", stage="won")
s, j = call("GET", "/api/deals?stage=won&q=" + TAG.upper() + "%20alpha")
s2, k = call("GET", "/api/deals?q=" + TAG.upper() + "%20ALPHA")
ok = s == 200 and [d["title"] for d in j] == [TAG + " Alpha one"] and s2 == 200 and len(k) == 2
return ok, "%s %s | %s %s" % (s, j, s2, k)
def t_deal_delete():
d = mk_deal()
a = call("DELETE", "/api/deals/%d" % d["id"])[0]
b = call("GET", "/api/deals/%d" % d["id"])[0]
c = call("DELETE", "/api/deals/%d" % d["id"])[0]
return (a, b, c) == (204, 404, 404), "statuses %s %s %s" % (a, b, c)
# ---- pipeline and references
def t_pipeline_shape():
s, j = call("GET", "/api/pipeline")
ok = s == 200 and isinstance(j, dict) and all(st in j and is_int(j[st].get("count")) and isinstance(j[st].get("amount"), (int, float)) for st in STAGES)
return ok, "%s %s" % (s, j)
def t_pipeline_totals():
before = call("GET", "/api/pipeline")[1]
mk_deal(stage="proposal", amount=7.5)
mk_deal(stage="proposal", amount=2.25)
after = call("GET", "/api/pipeline")[1]
ok = (after["proposal"]["count"] == before["proposal"]["count"] + 2 and abs(after["proposal"]["amount"] - before["proposal"]["amount"] - 9.75) < 1e-6
and after["won"] == before["won"])
return ok, "%s -> %s" % (before["proposal"], after["proposal"])
def t_pipeline_matches_list():
pipe = call("GET", "/api/pipeline")[1]
deals = call("GET", "/api/deals")[1]
for st in STAGES:
mine = [d for d in deals if d["stage"] == st]
if pipe[st]["count"] != len(mine) or abs(pipe[st]["amount"] - sum(d["amount"] for d in mine)) > 1e-6:
return False, "stage %s: %s vs %d deals" % (st, pipe[st], len(mine))
return True, ""
def t_delete_company_clears_refs():
co = mk_company()
ct = mk_contact(companyId=co["id"])
d = mk_deal(companyId=co["id"], contactId=ct["id"])
s = call("DELETE", "/api/companies/%d" % co["id"])[0]
c2 = call("GET", "/api/contacts/%d" % ct["id"])
d2 = call("GET", "/api/deals/%d" % d["id"])
ok = s == 204 and c2[0] == 200 and c2[1].get("companyId") is None and d2[0] == 200 and d2[1].get("companyId") is None and d2[1].get("contactId") == ct["id"]
return ok, "%s %s %s" % (s, c2, d2)
def t_delete_contact_clears_refs():
ct = mk_contact()
d = mk_deal(contactId=ct["id"])
s = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
d2 = call("GET", "/api/deals/%d" % d["id"])
return s == 204 and d2[0] == 200 and d2[1].get("contactId") is None, "%s %s" % (s, d2)
def t_ids_unique_integers():
ids = [mk_company()["id"] for _ in range(3)]
return len(set(ids)) == 3 and all(is_int(i) for i in ids), "ids %s" % ids
for nm, fn in [
("rest: POST /api/companies creates (201, integer id, fields)", t_company_create),
("rest: company name is required (400)", t_company_name_required),
("rest: GET company by id and in the list", t_company_get_list),
("rest: unknown company id gives 404 on GET, PUT and DELETE", t_company_404),
("rest: PUT /api/companies/:id updates and persists", t_company_update),
("rest: PUT company with an empty name is 400", t_company_update_invalid),
("rest: ?q= searches companies case-insensitively", t_company_search),
("rest: DELETE company is 204, then 404", t_company_delete),
("rest: POST /api/contacts creates with a company", t_contact_create),
("rest: contact name is required (400)", t_contact_name_required),
("rest: contact email must look like an email (400)", t_contact_bad_email),
("rest: contact with an unknown companyId is 400", t_contact_unknown_company),
("rest: ?q= searches contacts by name and by email", t_contact_search),
("rest: PUT contact updates and companyId null clears it", t_contact_update_clear_company),
("rest: contact 404 on unknown id, DELETE 204", t_contact_404_delete),
("rest: POST /api/deals defaults (amount 0, stage lead, null refs)", t_deal_defaults),
("rest: POST deal with all fields", t_deal_full),
("rest: deal title is required (400)", t_deal_title_required),
("rest: deal amount must be a number >= 0 (400)", t_deal_amount_not_number),
("rest: deal with an invalid stage is 400", t_deal_invalid_stage),
("rest: deal with unknown companyId or contactId is 400", t_deal_unknown_refs),
("rest: PUT deal moves it to another stage", t_deal_move_stage),
("rest: PUT deal with an invalid stage is 400 and changes nothing", t_deal_put_invalid_stage),
("rest: deal 404 on unknown id for GET, PUT and DELETE", t_deal_404),
("rest: GET /api/deals?stage= filters", t_deal_stage_filter),
("rest: GET /api/deals?stage=bogus is 400", t_deal_stage_bogus),
("rest: ?stage= and ?q= combine; q is case-insensitive", t_deal_q_and_stage),
("rest: DELETE deal is 204, then 404", t_deal_delete),
("rest: GET /api/pipeline has count and amount for all five stages", t_pipeline_shape),
("rest: pipeline totals follow new deals", t_pipeline_totals),
("rest: pipeline agrees with the deals list", t_pipeline_matches_list),
("rest: deleting a company clears references, keeps deals", t_delete_company_clears_refs),
("rest: deleting a contact clears the deal reference", t_delete_contact_clears_refs),
("rest: ids are unique integers", t_ids_unique_integers),
]:
rest(nm, fn)
if server is not None:
server.terminate()
try:
server.wait(10)
except subprocess.TimeoutExpired:
server.kill()
# ------------------------------------------------------------ 3. the agent's own backend tests
def count_tests(out):
m = re.search(r"Tests:\s+(?:(\d+) failed,\s*)?(?:(\d+) skipped,\s*)?(?:(\d+) todo,\s*)?(?:(\d+) passed,\s*)?(\d+) total", out)
if not m:
return 0, 0
return int(m.group(4) or 0), int(m.group(1) or 0)
own = {"passed": 0}
def own_tests(script):
def f():
if not (NPM and nm_ok.get("backend")):
return False, "no npm or no backend node_modules"
rc, out = run([NPM, "run", script], BE, 240)
passed, failed = count_tests(out)
own["passed"] += passed if rc == 0 else 0
return rc == 0 and failed == 0 and passed >= 1, "rc=%s passed=%s failed=%s %s" % (rc, passed, failed, out[-250:])
return f
guarded("backend tests: npm test passes (>= 1 test)", own_tests("test"))
guarded("backend tests: npm run test:e2e passes (>= 1 test)", own_tests("test:e2e"))
check("backend tests: at least %d test cases pass in total" % MIN_TESTS, own["passed"] >= MIN_TESTS, "total passed %d" % own["passed"])
# ------------------------------------------------------------ 4. frontend build
def frontend_build():
if not (NPM and nm_ok.get("frontend")):
return False, "no npm or no frontend node_modules"
rc, out = run([NPM, "run", "build"], FE, 280)
idx = glob.glob(os.path.join(FE, "dist", "**", "index.html"), recursive=True)
return rc == 0 and len(idx) > 0, "rc=%s index.html=%d %s" % (rc, len(idx), out[-300:])
guarded("frontend: npm run build (production) succeeds and writes index.html", frontend_build)
finally:
for lk in links:
unlink_dir(lk)
shutil.rmtree(tmp, ignore_errors=True)
# ---------------------------------------------------------------- 5. static checks of the frontend sources (read only, on the workspace)
SRC = os.path.join(WS, "frontend", "src")
files = [p for p in glob.glob(os.path.join(SRC, "**", "*"), recursive=True) if os.path.isfile(p) and p.endswith((".ts", ".html")) and not p.endswith(".spec.ts")]
texts = {p: read(p) for p in files}
alltext = "\n".join(texts.values())
ts_text = "\n".join(t for p, t in texts.items() if p.endswith(".ts"))
guarded("frontend src: Router config with companies, contacts and deals routes", lambda: (
re.search(r"\bRoutes\b", ts_text) is not None and all(re.search(r"""path\s*:\s*['"]%s['"]""" % r, ts_text) for r in ("companies", "contacts", "deals")), "routes not found"))
guarded("frontend src: router outlet and provideRouter are used", lambda: (
re.search(r"router-outlet|RouterOutlet", alltext) is not None and re.search(r"provideRouter|RouterModule", ts_text) is not None, "missing"))
guarded("frontend src: HttpClient is provided and injected", lambda: (
re.search(r"provideHttpClient|HttpClientModule", ts_text) is not None and re.search(r"inject\(\s*HttpClient\s*\)|:\s*HttpClient\b", ts_text) is not None, "missing"))
guarded("frontend src: calls /api/companies, /api/contacts and /api/deals", lambda: (
all(re.search(r"/api/" + r, ts_text) or (re.search(r"/api/\$\{", ts_text) and r in ts_text) for r in ("companies", "contacts", "deals")), "no calls to the API"))
guarded("frontend src: create, update and delete requests are made", lambda: (
all(re.search(pat, ts_text) for pat in (r"\.post\s*[<(]", r"\.(put|patch)\s*[<(]", r"\.delete\s*[<(]")), "post/put/delete missing"))
guarded("frontend src: a board with one column per stage (all five stages and a loop over stages)", lambda: (
all(st in alltext for st in STAGES) and any(re.search(r"@for|\*ngFor|\.map\(|\.forEach\(", t) and re.search(r"stage", t, re.I) for t in texts.values()), "the five stages and a loop over stages are not both in the frontend sources"))
guarded("frontend src: a search input", lambda: (
re.search(r"<input[^>]*search", alltext, re.I) is not None, "no <input ... search ...>"))
guarded("frontend src: forms use FormsModule or ReactiveFormsModule", lambda: (
re.search(r"FormsModule|ReactiveFormsModule|FormBuilder|FormControl", ts_text) is not None, "no forms module"))
guarded("frontend src: components for companies, contacts and deals exist", lambda: (
re.search(r"@Component", ts_text) is not None and all(re.search(r"class\s+\w*" + r, ts_text, re.I) for r in ("Compan", "Contact", "Deal")), "components missing"))
print("SUMMARY %d/%d" % (sum(results), len(results)))
sys.exit(0 if all(results) else 1)
@@ -0,0 +1,25 @@
# Reference solution notes (never installed on the server)
`overlay/` holds the files that, copied over `seed/`, make `accept.py` pass 56/56: the whole backend (`src/`, `test/crm.e2e-spec.ts`; 15 unit and 15 e2e tests) and the frontend
(`src/app/*`, `proxy.conf.json`, `angular.json` with `proxyConfig`). It only adds or replaces files: the seed has no file that would have to be deleted.
## Running `selftest.py nestng-crm` (no edit of selftest.py is needed)
`selftest.py` builds the workspace from `seed/` (+ `reference/overlay/`) WITHOUT node_modules, so `accept.py` needs `NESTNG_NM_ROOT`, a directory that holds
`backend/node_modules` and `frontend/node_modules` (made with `npm ci` from the two seed lockfiles; on the laptop it was `.../scratchpad/nestng-dev/ci`):
```sh
NESTNG_NM_ROOT=/path/to/nm-root python3 scripts/e2e/codex/tasks/selftest.py nestng-crm
# nestng-crm seed: ok rc=1 79.1s seed+overlay: ok rc=0 21.6s
# selftest: all good
```
On the server add `NESTNG_NODE_BIN=<dir of node and npm>` if node is not on PATH. selftest compares `workspace_lines` before and after the acceptance run: unchanged.
## What the main session has to add for the real runner (not in this task directory)
1. `cell.py`: after `copy_tree(seed, ws)` and the SEEDTREE check, hard-link the shared `backend/node_modules` and `frontend/node_modules` into `ws` (`cp -al`-style, no data copy);
exclude `node_modules`, `dist`, `.angular` from the final `workspace.sha256` and from any digest of the workspace.
2. `MANIFEST.sha256`: `python3 scripts/e2e/codex/tasks/freeze.py` (this task is picked up by `taskfile.task_ids`); read-only install on the server like the other tasks.
3. Node on PATH in the Codex shell and for `accept.py` (`NESTNG_NODE_BIN`); the allowed acceptance run time of this task is up to 300 s (README says < 120 s for the others).
4. Server `npm ci` of the shared trees: see `../NOTES.md`.
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { CompaniesController } from './companies/companies.controller';
import { ContactsController } from './contacts/contacts.controller';
import { DealsController } from './deals/deals.controller';
import { PipelineController } from './pipeline/pipeline.controller';
import { StoreService } from './common/store.service';
@Module({
controllers: [CompaniesController, ContactsController, DealsController, PipelineController],
providers: [StoreService],
})
export class AppModule {}
@@ -0,0 +1,26 @@
export const STAGES = ['lead', 'qualified', 'proposal', 'won', 'lost'] as const;
export type Stage = (typeof STAGES)[number];
export interface Company {
id: number;
name: string;
website: string | null;
industry: string | null;
}
export interface Contact {
id: number;
name: string;
email: string | null;
phone: string | null;
companyId: number | null;
}
export interface Deal {
id: number;
title: string;
amount: number;
stage: Stage;
companyId: number | null;
contactId: number | null;
}
@@ -0,0 +1,30 @@
import { BadRequestException } from '@nestjs/common';
import { ParseIdPipe, matches } from './parse-id.pipe';
describe('ParseIdPipe', () => {
const pipe = new ParseIdPipe();
it('parses a positive integer', () => {
expect(pipe.transform('42')).toBe(42);
});
it.each(['abc', '-1', '1.5', ''])('rejects %p', (value) => {
expect(() => pipe.transform(value)).toThrow(BadRequestException);
});
});
describe('matches', () => {
it('is case-insensitive', () => {
expect(matches('Acme Corp', 'acme')).toBe(true);
expect(matches('Acme Corp', 'CORP')).toBe(true);
});
it('matches everything for an empty query', () => {
expect(matches('anything', '')).toBe(true);
expect(matches(null, undefined)).toBe(true);
});
it('does not match a missing text', () => {
expect(matches(null, 'x')).toBe(false);
});
});
@@ -0,0 +1,15 @@
import { BadRequestException, PipeTransform } from '@nestjs/common';
/** The id in the path must be a positive integer; anything else is a 400 (an unknown but valid id is a 404 later). */
export class ParseIdPipe implements PipeTransform<string, number> {
transform(value: string): number {
if (!/^\d+$/.test(value)) throw new BadRequestException('id must be a positive integer');
return Number(value);
}
}
/** Case-insensitive substring match; an empty query matches everything. */
export function matches(text: string | null | undefined, q: string | undefined): boolean {
if (!q) return true;
return (text ?? '').toLowerCase().includes(q.toLowerCase());
}
@@ -0,0 +1,42 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Company, Contact, Deal } from './models';
/** In-memory storage for all three resources; ids are integers that are never reused. */
@Injectable()
export class StoreService {
companies = new Map<number, Company>();
contacts = new Map<number, Contact>();
deals = new Map<number, Deal>();
private seq = { companies: 1, contacts: 1, deals: 1 };
nextId(kind: 'companies' | 'contacts' | 'deals'): number {
return this.seq[kind]++;
}
requireCompany(id: number): Company {
const found = this.companies.get(id);
if (!found) throw new NotFoundException(`company ${id} not found`);
return found;
}
requireContact(id: number): Contact {
const found = this.contacts.get(id);
if (!found) throw new NotFoundException(`contact ${id} not found`);
return found;
}
requireDeal(id: number): Deal {
const found = this.deals.get(id);
if (!found) throw new NotFoundException(`deal ${id} not found`);
return found;
}
/** A reference that is given (not null or undefined) must point at an existing record. */
checkCompanyRef(id: number | null | undefined): void {
if (id !== null && id !== undefined && !this.companies.has(id)) throw new BadRequestException(`companyId ${id} does not exist`);
}
checkContactRef(id: number | null | undefined): void {
if (id !== null && id !== undefined && !this.contacts.has(id)) throw new BadRequestException(`contactId ${id} does not exist`);
}
}
@@ -0,0 +1,50 @@
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
import { Company } from '../common/models';
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
import { StoreService } from '../common/store.service';
import { CreateCompanyDto, UpdateCompanyDto } from './company.dto';
@Controller('companies')
export class CompaniesController {
constructor(private readonly store: StoreService) {}
@Get()
list(@Query('q') q?: string): Company[] {
return [...this.store.companies.values()].filter((c) => matches(c.name, q));
}
@Post()
create(@Body() dto: CreateCompanyDto): Company {
const company: Company = {
id: this.store.nextId('companies'),
name: dto.name,
website: dto.website ?? null,
industry: dto.industry ?? null,
};
this.store.companies.set(company.id, company);
return company;
}
@Get(':id')
get(@Param('id', ParseIdPipe) id: number): Company {
return this.store.requireCompany(id);
}
@Put(':id')
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateCompanyDto): Company {
const company = this.store.requireCompany(id);
if (dto.name !== undefined) company.name = dto.name;
if (dto.website !== undefined) company.website = dto.website;
if (dto.industry !== undefined) company.industry = dto.industry;
return company;
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIdPipe) id: number): void {
this.store.requireCompany(id);
this.store.companies.delete(id);
for (const contact of this.store.contacts.values()) if (contact.companyId === id) contact.companyId = null;
for (const deal of this.store.deals.values()) if (deal.companyId === id) deal.companyId = null;
}
}
@@ -0,0 +1,30 @@
import { IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator';
export class CreateCompanyDto {
@IsString()
@IsNotEmpty()
name!: string;
@IsOptional()
@IsString()
website?: string | null;
@IsOptional()
@IsString()
industry?: string | null;
}
export class UpdateCompanyDto {
@ValidateIf((o: UpdateCompanyDto) => o.name !== undefined)
@IsString()
@IsNotEmpty()
name?: string;
@IsOptional()
@IsString()
website?: string | null;
@IsOptional()
@IsString()
industry?: string | null;
}
@@ -0,0 +1,7 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
/** Shared by main.ts and the tests: global prefix and validation. */
export function configureApp(app: INestApplication): void {
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
}
@@ -0,0 +1,38 @@
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator';
export class CreateContactDto {
@IsString()
@IsNotEmpty()
name!: string;
@IsOptional()
@IsEmail()
email?: string | null;
@IsOptional()
@IsString()
phone?: string | null;
@IsOptional()
@IsInt()
companyId?: number | null;
}
export class UpdateContactDto {
@ValidateIf((o: UpdateContactDto) => o.name !== undefined)
@IsString()
@IsNotEmpty()
name?: string;
@IsOptional()
@IsEmail()
email?: string | null;
@IsOptional()
@IsString()
phone?: string | null;
@IsOptional()
@IsInt()
companyId?: number | null;
}
@@ -0,0 +1,53 @@
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
import { Contact } from '../common/models';
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
import { StoreService } from '../common/store.service';
import { CreateContactDto, UpdateContactDto } from './contact.dto';
@Controller('contacts')
export class ContactsController {
constructor(private readonly store: StoreService) {}
@Get()
list(@Query('q') q?: string): Contact[] {
return [...this.store.contacts.values()].filter((c) => matches(c.name, q) || matches(c.email, q));
}
@Post()
create(@Body() dto: CreateContactDto): Contact {
this.store.checkCompanyRef(dto.companyId);
const contact: Contact = {
id: this.store.nextId('contacts'),
name: dto.name,
email: dto.email ?? null,
phone: dto.phone ?? null,
companyId: dto.companyId ?? null,
};
this.store.contacts.set(contact.id, contact);
return contact;
}
@Get(':id')
get(@Param('id', ParseIdPipe) id: number): Contact {
return this.store.requireContact(id);
}
@Put(':id')
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateContactDto): Contact {
const contact = this.store.requireContact(id);
this.store.checkCompanyRef(dto.companyId);
if (dto.name !== undefined) contact.name = dto.name;
if (dto.email !== undefined) contact.email = dto.email;
if (dto.phone !== undefined) contact.phone = dto.phone;
if (dto.companyId !== undefined) contact.companyId = dto.companyId;
return contact;
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIdPipe) id: number): void {
this.store.requireContact(id);
this.store.contacts.delete(id);
for (const deal of this.store.deals.values()) if (deal.contactId === id) deal.contactId = null;
}
}
@@ -0,0 +1,49 @@
import { IsIn, IsInt, IsNotEmpty, IsNumber, IsOptional, IsString, Min, ValidateIf } from 'class-validator';
import { STAGES, Stage } from '../common/models';
export class CreateDealDto {
@IsString()
@IsNotEmpty()
title!: string;
@IsOptional()
@IsNumber({ allowNaN: false, allowInfinity: false })
@Min(0)
amount?: number;
@IsOptional()
@IsIn(STAGES)
stage?: Stage;
@IsOptional()
@IsInt()
companyId?: number | null;
@IsOptional()
@IsInt()
contactId?: number | null;
}
export class UpdateDealDto {
@ValidateIf((o: UpdateDealDto) => o.title !== undefined)
@IsString()
@IsNotEmpty()
title?: string;
@IsOptional()
@IsNumber({ allowNaN: false, allowInfinity: false })
@Min(0)
amount?: number;
@IsOptional()
@IsIn(STAGES)
stage?: Stage;
@IsOptional()
@IsInt()
companyId?: number | null;
@IsOptional()
@IsInt()
contactId?: number | null;
}
@@ -0,0 +1,65 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { StoreService } from '../common/store.service';
import { CompaniesController } from '../companies/companies.controller';
import { PipelineController } from '../pipeline/pipeline.controller';
import { DealsController } from './deals.controller';
describe('DealsController', () => {
let store: StoreService;
let deals: DealsController;
let companies: CompaniesController;
let pipeline: PipelineController;
beforeEach(() => {
store = new StoreService();
deals = new DealsController(store);
companies = new CompaniesController(store);
pipeline = new PipelineController(store);
});
it('creates a deal with defaults', () => {
expect(deals.create({ title: 'First' })).toEqual({ id: 1, title: 'First', amount: 0, stage: 'lead', companyId: null, contactId: null });
});
it('never reuses ids', () => {
const a = deals.create({ title: 'a' });
deals.remove(a.id);
expect(deals.create({ title: 'b' }).id).toBe(2);
});
it('rejects an unknown company reference', () => {
expect(() => deals.create({ title: 'x', companyId: 99 })).toThrow(BadRequestException);
});
it('throws NotFound for an unknown id', () => {
expect(() => deals.get(5)).toThrow(NotFoundException);
});
it('filters by stage and by text together', () => {
deals.create({ title: 'Big Renewal', stage: 'won', amount: 10 });
deals.create({ title: 'Small renewal', stage: 'lead', amount: 1 });
deals.create({ title: 'Other', stage: 'won', amount: 5 });
expect(deals.list('renewal', 'won').map((d) => d.title)).toEqual(['Big Renewal']);
expect(() => deals.list(undefined, 'bogus')).toThrow(BadRequestException);
});
it('summarises the pipeline for every stage', () => {
deals.create({ title: 'a', stage: 'won', amount: 10 });
deals.create({ title: 'b', stage: 'won', amount: 5.5 });
deals.create({ title: 'c' });
expect(pipeline.pipeline()).toEqual({
lead: { count: 1, amount: 0 },
qualified: { count: 0, amount: 0 },
proposal: { count: 0, amount: 0 },
won: { count: 2, amount: 15.5 },
lost: { count: 0, amount: 0 },
});
});
it('clears the company reference of a deal when the company is deleted', () => {
const company = companies.create({ name: 'Acme' });
const deal = deals.create({ title: 'd', companyId: company.id });
companies.remove(company.id);
expect(deals.get(deal.id).companyId).toBeNull();
});
});
@@ -0,0 +1,59 @@
import { BadRequestException, Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
import { Deal, STAGES, Stage } from '../common/models';
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
import { StoreService } from '../common/store.service';
import { CreateDealDto, UpdateDealDto } from './deal.dto';
@Controller('deals')
export class DealsController {
constructor(private readonly store: StoreService) {}
@Get()
list(@Query('q') q?: string, @Query('stage') stage?: string): Deal[] {
if (stage !== undefined && stage !== '' && !STAGES.includes(stage as Stage)) {
throw new BadRequestException(`stage must be one of ${STAGES.join(', ')}`);
}
return [...this.store.deals.values()].filter((d) => matches(d.title, q) && (!stage || d.stage === stage));
}
@Post()
create(@Body() dto: CreateDealDto): Deal {
this.store.checkCompanyRef(dto.companyId);
this.store.checkContactRef(dto.contactId);
const deal: Deal = {
id: this.store.nextId('deals'),
title: dto.title,
amount: dto.amount ?? 0,
stage: dto.stage ?? 'lead',
companyId: dto.companyId ?? null,
contactId: dto.contactId ?? null,
};
this.store.deals.set(deal.id, deal);
return deal;
}
@Get(':id')
get(@Param('id', ParseIdPipe) id: number): Deal {
return this.store.requireDeal(id);
}
@Put(':id')
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateDealDto): Deal {
const deal = this.store.requireDeal(id);
this.store.checkCompanyRef(dto.companyId);
this.store.checkContactRef(dto.contactId);
if (dto.title !== undefined) deal.title = dto.title;
if (dto.amount !== undefined) deal.amount = dto.amount;
if (dto.stage !== undefined) deal.stage = dto.stage;
if (dto.companyId !== undefined) deal.companyId = dto.companyId;
if (dto.contactId !== undefined) deal.contactId = dto.contactId;
return deal;
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIdPipe) id: number): void {
this.store.requireDeal(id);
this.store.deals.delete(id);
}
}
@@ -0,0 +1,12 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { configureApp } from './configure-app';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
configureApp(app);
const port = Number(process.env.PORT) || 3000;
await app.listen(port, '127.0.0.1');
}
bootstrap();
@@ -0,0 +1,19 @@
import { Controller, Get } from '@nestjs/common';
import { STAGES, Stage } from '../common/models';
import { StoreService } from '../common/store.service';
@Controller('pipeline')
export class PipelineController {
constructor(private readonly store: StoreService) {}
@Get()
pipeline(): Record<Stage, { count: number; amount: number }> {
const result = {} as Record<Stage, { count: number; amount: number }>;
for (const stage of STAGES) result[stage] = { count: 0, amount: 0 };
for (const deal of this.store.deals.values()) {
result[deal.stage].count += 1;
result[deal.stage].amount += deal.amount;
}
return result;
}
}
@@ -0,0 +1,152 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
describe('CRM API (e2e)', () => {
let app: INestApplication;
let http: ReturnType<INestApplication['getHttpServer']>;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
configureApp(app);
await app.init();
http = app.getHttpServer();
});
afterEach(async () => {
await app.close();
});
const post = (path: string, body: object) => request(http).post(path).send(body);
describe('companies', () => {
it('creates, reads, updates and deletes a company', async () => {
const created = await post('/api/companies', { name: 'Acme', website: 'https://acme.test', industry: 'Tools' }).expect(201);
expect(created.body).toEqual({ id: 1, name: 'Acme', website: 'https://acme.test', industry: 'Tools' });
await request(http).get('/api/companies/1').expect(200).expect(created.body);
const updated = await request(http).put('/api/companies/1').send({ industry: 'Hardware' }).expect(200);
expect(updated.body).toMatchObject({ id: 1, name: 'Acme', industry: 'Hardware' });
await request(http).delete('/api/companies/1').expect(204);
await request(http).get('/api/companies/1').expect(404);
});
it('requires a name', async () => {
await post('/api/companies', { website: 'x' }).expect(400);
await post('/api/companies', { name: '' }).expect(400);
await post('/api/companies', { name: 5 }).expect(400);
});
it('answers 404 for an unknown id', async () => {
await request(http).get('/api/companies/99').expect(404);
await request(http).put('/api/companies/99').send({ name: 'x' }).expect(404);
await request(http).delete('/api/companies/99').expect(404);
});
it('searches by name, case-insensitively', async () => {
await post('/api/companies', { name: 'Acme Corp' });
await post('/api/companies', { name: 'Globex' });
const res = await request(http).get('/api/companies?q=ACME').expect(200);
expect(res.body.map((c: { name: string }) => c.name)).toEqual(['Acme Corp']);
});
});
describe('contacts', () => {
it('creates, updates and deletes a contact', async () => {
await post('/api/companies', { name: 'Acme' });
const created = await post('/api/contacts', { name: 'Ann', email: 'ann@acme.test', phone: '123', companyId: 1 }).expect(201);
expect(created.body).toEqual({ id: 1, name: 'Ann', email: 'ann@acme.test', phone: '123', companyId: 1 });
const updated = await request(http).put('/api/contacts/1').send({ phone: '999', companyId: null }).expect(200);
expect(updated.body).toMatchObject({ phone: '999', companyId: null });
await request(http).delete('/api/contacts/1').expect(204);
await request(http).get('/api/contacts/1').expect(404);
});
it('validates name, email and company reference', async () => {
await post('/api/contacts', {}).expect(400);
await post('/api/contacts', { name: 'Bob', email: 'not-an-email' }).expect(400);
await post('/api/contacts', { name: 'Bob', companyId: 42 }).expect(400);
});
it('searches by name or email', async () => {
await post('/api/contacts', { name: 'Ann', email: 'ann@one.test' });
await post('/api/contacts', { name: 'Bob', email: 'bob@two.test' });
const byName = await request(http).get('/api/contacts?q=an').expect(200);
expect(byName.body).toHaveLength(1);
const byEmail = await request(http).get('/api/contacts?q=TWO.test').expect(200);
expect(byEmail.body.map((c: { name: string }) => c.name)).toEqual(['Bob']);
});
});
describe('deals', () => {
it('applies defaults', async () => {
const res = await post('/api/deals', { title: 'Renewal' }).expect(201);
expect(res.body).toEqual({ id: 1, title: 'Renewal', amount: 0, stage: 'lead', companyId: null, contactId: null });
});
it('rejects bad input', async () => {
await post('/api/deals', {}).expect(400);
await post('/api/deals', { title: 'x', amount: 'lots' }).expect(400);
await post('/api/deals', { title: 'x', amount: -1 }).expect(400);
await post('/api/deals', { title: 'x', stage: 'maybe' }).expect(400);
await post('/api/deals', { title: 'x', contactId: 7 }).expect(400);
});
it('moves a deal between stages and rejects an invalid stage', async () => {
await post('/api/deals', { title: 'Renewal', amount: 100 });
await request(http).put('/api/deals/1').send({ stage: 'proposal' }).expect(200).expect((r) => expect(r.body.stage).toBe('proposal'));
await request(http).put('/api/deals/1').send({ stage: 'nope' }).expect(400);
});
it('filters by stage and q', async () => {
await post('/api/deals', { title: 'Alpha deal', stage: 'won' });
await post('/api/deals', { title: 'Beta deal', stage: 'won' });
await post('/api/deals', { title: 'Alpha two', stage: 'lost' });
const won = await request(http).get('/api/deals?stage=won').expect(200);
expect(won.body).toHaveLength(2);
const both = await request(http).get('/api/deals?stage=won&q=alpha').expect(200);
expect(both.body.map((d: { title: string }) => d.title)).toEqual(['Alpha deal']);
await request(http).get('/api/deals?stage=bogus').expect(400);
});
it('answers 404 for an unknown id', async () => {
await request(http).get('/api/deals/5').expect(404);
await request(http).delete('/api/deals/5').expect(404);
});
});
describe('pipeline and references', () => {
it('reports count and amount for every stage', async () => {
await post('/api/deals', { title: 'a', amount: 10, stage: 'won' });
await post('/api/deals', { title: 'b', amount: 2.5, stage: 'won' });
await post('/api/deals', { title: 'c' });
const res = await request(http).get('/api/pipeline').expect(200);
expect(res.body).toEqual({
lead: { count: 1, amount: 0 },
qualified: { count: 0, amount: 0 },
proposal: { count: 0, amount: 0 },
won: { count: 2, amount: 12.5 },
lost: { count: 0, amount: 0 },
});
});
it('clears references when a company or a contact is deleted, without deleting deals', async () => {
await post('/api/companies', { name: 'Acme' });
await post('/api/contacts', { name: 'Ann', companyId: 1 });
await post('/api/deals', { title: 'd', companyId: 1, contactId: 1 });
await request(http).delete('/api/contacts/1').expect(204);
await request(http).get('/api/deals/1').expect(200).expect((r) => expect(r.body).toMatchObject({ companyId: 1, contactId: null }));
await request(http).delete('/api/companies/1').expect(204);
await request(http).get('/api/deals/1').expect(200).expect((r) => expect(r.body).toMatchObject({ companyId: null, contactId: null }));
});
it('nulls the company of a contact when the company is deleted', async () => {
await post('/api/companies', { name: 'Acme' });
await post('/api/contacts', { name: 'Ann', companyId: 1 });
await request(http).delete('/api/companies/1').expect(204);
await request(http).get('/api/contacts/1').expect(200).expect((r) => expect(r.body.companyId).toBeNull());
});
});
});
@@ -0,0 +1,54 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"analytics": false
},
"newProjectRoot": "projects",
"projects": {
"frontend": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"assets": [],
"styles": ["src/styles.css"]
},
"configurations": {
"production": {
"budgets": [
{ "type": "initial", "maximumWarning": "1MB", "maximumError": "2MB" }
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": { "buildTarget": "frontend:build:production" },
"development": { "buildTarget": "frontend:build:development" }
},
"defaultConfiguration": "development"
}
}
}
}
}
@@ -0,0 +1,6 @@
{
"/api": {
"target": "http://127.0.0.1:3000",
"secure": false
}
}
@@ -0,0 +1,48 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Company, Contact, Deal } from './models';
type Resource = 'companies' | 'contacts' | 'deals';
/** Thin typed wrapper over the REST API of the backend (the dev server proxies /api to it). */
@Injectable({ providedIn: 'root' })
export class ApiService {
private readonly http = inject(HttpClient);
private list<T>(resource: Resource, q: string): Observable<T[]> {
let params = new HttpParams();
if (q.trim()) params = params.set('q', q.trim());
return this.http.get<T[]>(`/api/${resource}`, { params });
}
companies(q = ''): Observable<Company[]> {
return this.list<Company>('companies', q);
}
saveCompany(id: number | null, body: Partial<Company>): Observable<Company> {
return id === null ? this.http.post<Company>('/api/companies', body) : this.http.put<Company>(`/api/companies/${id}`, body);
}
deleteCompany(id: number): Observable<void> {
return this.http.delete<void>(`/api/companies/${id}`);
}
contacts(q = ''): Observable<Contact[]> {
return this.list<Contact>('contacts', q);
}
saveContact(id: number | null, body: Partial<Contact>): Observable<Contact> {
return id === null ? this.http.post<Contact>('/api/contacts', body) : this.http.put<Contact>(`/api/contacts/${id}`, body);
}
deleteContact(id: number): Observable<void> {
return this.http.delete<void>(`/api/contacts/${id}`);
}
deals(q = ''): Observable<Deal[]> {
return this.list<Deal>('deals', q);
}
saveDeal(id: number | null, body: Partial<Deal>): Observable<Deal> {
return id === null ? this.http.post<Deal>('/api/deals', body) : this.http.put<Deal>(`/api/deals/${id}`, body);
}
deleteDeal(id: number): Observable<void> {
return this.http.delete<void>(`/api/deals/${id}`);
}
}
@@ -0,0 +1,14 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(),
],
};
@@ -0,0 +1,7 @@
<h1>CRM</h1>
<nav>
<a routerLink="/deals" routerLinkActive="active">Deals</a>
<a routerLink="/companies" routerLinkActive="active">Companies</a>
<a routerLink="/contacts" routerLinkActive="active">Contacts</a>
</nav>
<router-outlet />
@@ -0,0 +1,12 @@
import { Routes } from '@angular/router';
import { CompaniesComponent } from './companies/companies';
import { ContactsComponent } from './contacts/contacts';
import { DealsComponent } from './deals/deals';
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'deals' },
{ path: 'companies', component: CompaniesComponent },
{ path: 'contacts', component: ContactsComponent },
{ path: 'deals', component: DealsComponent },
{ path: '**', redirectTo: 'deals' },
];
@@ -0,0 +1,9 @@
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink, RouterLinkActive],
templateUrl: './app.html',
})
export class App {}
@@ -0,0 +1,104 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ApiService } from '../api.service';
import { Company } from '../models';
@Component({
selector: 'app-companies',
imports: [FormsModule],
template: `
<h2>Companies</h2>
<input type="search" name="search" placeholder="Search companies" [ngModel]="query()" (ngModelChange)="search($event)" />
<form (ngSubmit)="save()">
<input name="name" placeholder="Name" [(ngModel)]="form.name" required />
<input name="website" placeholder="Website" [(ngModel)]="form.website" />
<input name="industry" placeholder="Industry" [(ngModel)]="form.industry" />
<button type="submit">{{ editingId() === null ? 'Add company' : 'Save company' }}</button>
@if (editingId() !== null) {
<button type="button" (click)="cancel()">Cancel</button>
}
</form>
@if (error()) {
<p class="error">{{ error() }}</p>
}
<table>
<thead><tr><th>Name</th><th>Website</th><th>Industry</th><th></th></tr></thead>
<tbody>
@for (company of companies(); track company.id) {
<tr>
<td>{{ company.name }}</td>
<td>{{ company.website }}</td>
<td>{{ company.industry }}</td>
<td>
<button type="button" (click)="edit(company)">Edit</button>
<button type="button" (click)="remove(company)">Delete</button>
</td>
</tr>
} @empty {
<tr><td colspan="4">No companies</td></tr>
}
</tbody>
</table>
`,
})
export class CompaniesComponent implements OnInit {
private readonly api = inject(ApiService);
readonly companies = signal<Company[]>([]);
readonly query = signal('');
readonly error = signal('');
readonly editingId = signal<number | null>(null);
form = { name: '', website: '', industry: '' };
ngOnInit(): void {
this.load();
}
load(): void {
this.api.companies(this.query()).subscribe({
next: (list) => this.companies.set(list),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
search(q: string): void {
this.query.set(q);
this.load();
}
save(): void {
const body = { name: this.form.name, website: this.form.website || null, industry: this.form.industry || null };
this.api.saveCompany(this.editingId(), body).subscribe({
next: () => {
this.cancel();
this.load();
},
error: (err: HttpErrorResponse) => this.fail(err),
});
}
edit(company: Company): void {
this.editingId.set(company.id);
this.form = { name: company.name, website: company.website ?? '', industry: company.industry ?? '' };
}
cancel(): void {
this.editingId.set(null);
this.form = { name: '', website: '', industry: '' };
this.error.set('');
}
remove(company: Company): void {
this.api.deleteCompany(company.id).subscribe({
next: () => this.load(),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
private fail(err: HttpErrorResponse): void {
this.error.set(`Request failed (${err.status})`);
}
}
@@ -0,0 +1,126 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ApiService } from '../api.service';
import { Company, Contact } from '../models';
interface ContactForm {
name: string;
email: string;
phone: string;
companyId: number | null;
}
const EMPTY: ContactForm = { name: '', email: '', phone: '', companyId: null };
@Component({
selector: 'app-contacts',
imports: [FormsModule],
template: `
<h2>Contacts</h2>
<input type="search" name="search" placeholder="Search contacts" [ngModel]="query()" (ngModelChange)="search($event)" />
<form (ngSubmit)="save()">
<input name="name" placeholder="Name" [(ngModel)]="form.name" required />
<input name="email" placeholder="Email" [(ngModel)]="form.email" />
<input name="phone" placeholder="Phone" [(ngModel)]="form.phone" />
<select name="companyId" [(ngModel)]="form.companyId">
<option [ngValue]="null">No company</option>
@for (company of companies(); track company.id) {
<option [ngValue]="company.id">{{ company.name }}</option>
}
</select>
<button type="submit">{{ editingId() === null ? 'Add contact' : 'Save contact' }}</button>
@if (editingId() !== null) {
<button type="button" (click)="cancel()">Cancel</button>
}
</form>
@if (error()) {
<p class="error">{{ error() }}</p>
}
<table>
<thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Company</th><th></th></tr></thead>
<tbody>
@for (contact of contacts(); track contact.id) {
<tr>
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td>{{ companyName(contact.companyId) }}</td>
<td>
<button type="button" (click)="edit(contact)">Edit</button>
<button type="button" (click)="remove(contact)">Delete</button>
</td>
</tr>
} @empty {
<tr><td colspan="5">No contacts</td></tr>
}
</tbody>
</table>
`,
})
export class ContactsComponent implements OnInit {
private readonly api = inject(ApiService);
readonly contacts = signal<Contact[]>([]);
readonly companies = signal<Company[]>([]);
readonly query = signal('');
readonly error = signal('');
readonly editingId = signal<number | null>(null);
form: ContactForm = { ...EMPTY };
ngOnInit(): void {
this.api.companies().subscribe({ next: (list) => this.companies.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
this.load();
}
load(): void {
this.api.contacts(this.query()).subscribe({
next: (list) => this.contacts.set(list),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
search(q: string): void {
this.query.set(q);
this.load();
}
companyName(id: number | null): string {
return this.companies().find((c) => c.id === id)?.name ?? '';
}
save(): void {
const body = { name: this.form.name, email: this.form.email || null, phone: this.form.phone || null, companyId: this.form.companyId };
this.api.saveContact(this.editingId(), body).subscribe({
next: () => {
this.cancel();
this.load();
},
error: (err: HttpErrorResponse) => this.fail(err),
});
}
edit(contact: Contact): void {
this.editingId.set(contact.id);
this.form = { name: contact.name, email: contact.email ?? '', phone: contact.phone ?? '', companyId: contact.companyId };
}
cancel(): void {
this.editingId.set(null);
this.form = { ...EMPTY };
this.error.set('');
}
remove(contact: Contact): void {
this.api.deleteContact(contact.id).subscribe({
next: () => this.load(),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
private fail(err: HttpErrorResponse): void {
this.error.set(`Request failed (${err.status})`);
}
}
@@ -0,0 +1,149 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ApiService } from '../api.service';
import { Company, Contact, Deal, STAGES, Stage } from '../models';
interface DealForm {
title: string;
amount: number;
stage: Stage;
companyId: number | null;
contactId: number | null;
}
const EMPTY: DealForm = { title: '', amount: 0, stage: 'lead', companyId: null, contactId: null };
@Component({
selector: 'app-deals',
imports: [FormsModule],
template: `
<h2>Deals</h2>
<input type="search" name="search" placeholder="Search deals" [ngModel]="query()" (ngModelChange)="search($event)" />
<form (ngSubmit)="save()">
<input name="title" placeholder="Title" [(ngModel)]="form.title" required />
<input name="amount" type="number" min="0" placeholder="Amount" [(ngModel)]="form.amount" />
<select name="stage" [(ngModel)]="form.stage">
@for (stage of stages; track stage) {
<option [ngValue]="stage">{{ stage }}</option>
}
</select>
<select name="companyId" [(ngModel)]="form.companyId">
<option [ngValue]="null">No company</option>
@for (company of companies(); track company.id) {
<option [ngValue]="company.id">{{ company.name }}</option>
}
</select>
<select name="contactId" [(ngModel)]="form.contactId">
<option [ngValue]="null">No contact</option>
@for (contact of contacts(); track contact.id) {
<option [ngValue]="contact.id">{{ contact.name }}</option>
}
</select>
<button type="submit">{{ editingId() === null ? 'Add deal' : 'Save deal' }}</button>
@if (editingId() !== null) {
<button type="button" (click)="cancel()">Cancel</button>
}
</form>
@if (error()) {
<p class="error">{{ error() }}</p>
}
<div class="board">
@for (stage of stages; track stage) {
<section class="column" [attr.data-stage]="stage">
<h3>{{ stage }} ({{ byStage()[stage].length }})</h3>
@for (deal of byStage()[stage]; track deal.id) {
<article class="card">
<strong>{{ deal.title }}</strong>
<span>{{ deal.amount }}</span>
<select [ngModel]="deal.stage" [name]="'move-' + deal.id" (ngModelChange)="move(deal, $event)">
@for (target of stages; track target) {
<option [ngValue]="target">{{ target }}</option>
}
</select>
<button type="button" (click)="edit(deal)">Edit</button>
<button type="button" (click)="remove(deal)">Delete</button>
</article>
}
</section>
}
</div>
`,
})
export class DealsComponent implements OnInit {
private readonly api = inject(ApiService);
readonly stages = STAGES;
readonly deals = signal<Deal[]>([]);
readonly companies = signal<Company[]>([]);
readonly contacts = signal<Contact[]>([]);
readonly query = signal('');
readonly error = signal('');
readonly editingId = signal<number | null>(null);
form: DealForm = { ...EMPTY };
readonly byStage = computed(() => {
const groups: Record<Stage, Deal[]> = { lead: [], qualified: [], proposal: [], won: [], lost: [] };
for (const deal of this.deals()) groups[deal.stage].push(deal);
return groups;
});
ngOnInit(): void {
this.api.companies().subscribe({ next: (list) => this.companies.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
this.api.contacts().subscribe({ next: (list) => this.contacts.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
this.load();
}
load(): void {
this.api.deals(this.query()).subscribe({
next: (list) => this.deals.set(list),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
search(q: string): void {
this.query.set(q);
this.load();
}
move(deal: Deal, stage: Stage): void {
this.api.saveDeal(deal.id, { stage }).subscribe({
next: () => this.load(),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
save(): void {
this.api.saveDeal(this.editingId(), { ...this.form, amount: Number(this.form.amount) || 0 }).subscribe({
next: () => {
this.cancel();
this.load();
},
error: (err: HttpErrorResponse) => this.fail(err),
});
}
edit(deal: Deal): void {
this.editingId.set(deal.id);
this.form = { title: deal.title, amount: deal.amount, stage: deal.stage, companyId: deal.companyId, contactId: deal.contactId };
}
cancel(): void {
this.editingId.set(null);
this.form = { ...EMPTY };
this.error.set('');
}
remove(deal: Deal): void {
this.api.deleteDeal(deal.id).subscribe({
next: () => this.load(),
error: (err: HttpErrorResponse) => this.fail(err),
});
}
private fail(err: HttpErrorResponse): void {
this.error.set(`Request failed (${err.status})`);
}
}
@@ -0,0 +1,26 @@
export const STAGES = ['lead', 'qualified', 'proposal', 'won', 'lost'] as const;
export type Stage = (typeof STAGES)[number];
export interface Company {
id: number;
name: string;
website: string | null;
industry: string | null;
}
export interface Contact {
id: number;
name: string;
email: string | null;
phone: string | null;
companyId: number | null;
}
export interface Deal {
id: number;
title: string;
amount: number;
stage: Stage;
companyId: number | null;
contactId: number | null;
}
@@ -0,0 +1,3 @@
# CRM
`backend/` is a NestJS application, `frontend/` is an Angular application. Dependencies are already installed in each `node_modules`.
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,48 @@
{
"name": "backend",
"version": "0.0.1",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"start": "nest start",
"start:prod": "node dist/main.js",
"test": "jest",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"testEnvironment": "node"
},
"dependencies": {
"@nestjs/common": "11.2.8",
"@nestjs/core": "11.2.8",
"@nestjs/platform-express": "11.2.8",
"class-transformer": "0.5.1",
"class-validator": "0.15.1",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2"
},
"devDependencies": {
"@nestjs/cli": "11.0.24",
"@nestjs/schematics": "11.1.0",
"@nestjs/testing": "11.2.8",
"@types/express": "5.0.6",
"@types/jest": "29.5.14",
"@types/node": "22.20.5",
"@types/supertest": "6.0.3",
"jest": "29.7.0",
"supertest": "7.3.1",
"ts-jest": "29.4.15",
"typescript": "5.9.3"
}
}
@@ -0,0 +1,4 @@
import { Module } from '@nestjs/common';
@Module({})
export class AppModule {}
@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
@@ -0,0 +1,7 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": { "^.+\\.(t|j)s$": "ts-jest" }
}
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"target": "ES2022",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": true,
"forceConsistentCasingInFileNames": true
}
}
@@ -0,0 +1,51 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"analytics": false
},
"newProjectRoot": "projects",
"projects": {
"frontend": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"assets": [],
"styles": ["src/styles.css"]
},
"configurations": {
"production": {
"budgets": [
{ "type": "initial", "maximumWarning": "1MB", "maximumError": "2MB" }
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular/build:dev-server",
"configurations": {
"production": { "buildTarget": "frontend:build:production" },
"development": { "buildTarget": "frontend:build:development" }
},
"defaultConfiguration": "development"
}
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "frontend",
"version": "0.0.0",
"private": true,
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build"
},
"dependencies": {
"@angular/common": "20.3.35",
"@angular/compiler": "20.3.35",
"@angular/core": "20.3.35",
"@angular/forms": "20.3.35",
"@angular/platform-browser": "20.3.35",
"@angular/router": "20.3.35",
"rxjs": "7.8.2",
"tslib": "2.8.1",
"zone.js": "0.15.1"
},
"devDependencies": {
"@angular/build": "20.3.42",
"@angular/cli": "20.3.42",
"@angular/compiler-cli": "20.3.35",
"typescript": "5.9.3"
}
}
@@ -0,0 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
],
};
@@ -0,0 +1,2 @@
<h1>CRM</h1>
<router-outlet />
@@ -0,0 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];
@@ -0,0 +1,9 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
templateUrl: './app.html',
})
export class App {}
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CRM</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
@@ -0,0 +1,5 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
@@ -0,0 +1 @@
/* global styles */
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts"]
}
@@ -0,0 +1,22 @@
{
"compileOnSave": false,
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "ES2022",
"module": "preserve"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
@@ -0,0 +1,38 @@
---
id: nestng-crm
title: Simple NestJS + Angular CRM
kind: create
expected_rounds: 30-70
---
# Simple NestJS + Angular CRM
Task for the vanilla Strata vs Leleka comparison with the real Codex CLI (written 2026-11-05). Single phase, two projects in one workspace.
The seed is two freshly scaffolded projects (a Nest module with no controllers, an Angular 20 standalone app with an empty router) with exact-pinned
`package.json` and `package-lock.json` files; `node_modules` is NOT part of the seed: the runner installs both trees once from the lockfiles (`NOTES.md`)
and hard-links them into every workspace, because the agent has no network. Node.js 22 must be on the PATH of the Codex shell. No browser, no Karma.
Acceptance (`accept.py`, 56 checks, 20-120 s): black-box REST checks over HTTP against `node dist/main.js`, the agent's own jest tests (>= 15 cases),
the production `ng build`, static checks of the Angular sources. A browser check of the UI is NOT part of the acceptance (the server has no browser).
## Prompt
<!-- PROMPT BEGIN -->
Build a small CRM web application in the current directory. It has two parts that are already scaffolded here: a NestJS REST API in `backend/` and an Angular single-page app in `frontend/`. Both already have their package.json, tsconfig files and installed dependencies (`backend/node_modules`, `frontend/node_modules`). There is NO network and NO browser: you cannot install packages, so do not change the dependencies and use only what is installed (NestJS 11: @nestjs/common, core, platform-express, testing; class-validator, class-transformer; jest, ts-jest, supertest; Angular 20: common, core, forms, router, platform-browser with the esbuild application builder). Node.js 22 and npm are on the PATH.
Backend (`backend/`, TypeScript, NestJS, in-memory storage, no database):
- Fixed commands: `npm run build` compiles to `dist/`; `node dist/main.js` starts the server on the port in the environment variable PORT (default 3000), bound to 127.0.0.1. Every route is under the `/api` prefix and speaks JSON.
- Resources and fields: companies {id, name (required), website, industry}; contacts {id, name (required), email, phone, companyId}; deals {id, title (required), amount, stage, companyId, contactId}. Optional fields that were not given are returned as null. A deal's amount is a number >= 0 (default 0); its stage is exactly one of lead, qualified, proposal, won, lost (default lead). companyId and contactId are optional integers or null.
- For each of /api/companies, /api/contacts, /api/deals: GET lists all records (a JSON array); POST creates a record and answers 201 with it, including an integer id (1, 2, 3, ..., never reused); GET /api/<resource>/:id returns one record; PUT /api/<resource>/:id updates the fields that are present in the body and answers 200 with the updated record (null clears companyId or contactId); DELETE /api/<resource>/:id answers 204. An unknown id gives 404 for GET, PUT and DELETE.
- Validation, answered with 400 on POST and on PUT for the fields given: name or title missing, empty or not a string; amount not a number or negative; stage not one of the five values; email that is not a valid email address; companyId or contactId that is not an integer or that refers to a record that does not exist.
- Search: GET /api/companies?q=text filters by name; GET /api/contacts?q=text by name or email; GET /api/deals?q=text by title. All are case-insensitive substring matches. GET /api/deals?stage=won filters by stage and combines with q; an invalid stage in the query is 400.
- GET /api/pipeline returns {"lead": {"count": n, "amount": total}, "qualified": {...}, "proposal": {...}, "won": {...}, "lost": {...}}, all five stages always present, summing the deals of each stage.
- Deleting a company must not delete anything else: it sets companyId to null on its contacts and deals. Deleting a contact sets contactId to null on its deals.
- Tests: `npm test` runs jest unit tests (src/**/*.spec.ts) and `npm run test:e2e` runs end-to-end tests with supertest (test/*.e2e-spec.ts; the config is already there). Both must run offline and pass, and together they must cover every endpoint and the validation rules.
Frontend (`frontend/`, Angular 20, standalone components, TypeScript strict mode as scaffolded):
- `npm run build` (the production build) must succeed without errors. There are no frontend tests.
- `frontend/proxy.conf.json` proxies `/api` to http://127.0.0.1:3000 and `npm start` (ng serve) uses it.
- Use the Angular Router with the routes /companies, /contacts and /deals (the empty path redirects to /deals) and a navigation bar linking to them. The app talks to the API with HttpClient at /api/....
- Each of the companies, contacts and deals pages lists its records, has a search box that filters the list through the ?q= parameter, a form to create a record, a way to edit a record and a delete button. Contact and deal forms let the user pick the company (and the deal form the contact) from the existing records.
- The deals page is a board with one column per stage (lead, qualified, proposal, won, lost) showing the deals of that stage, and each deal can be moved to another stage from the board (a select or buttons that send a PUT).
Work step by step. Verify your work before finishing: run both test commands, start the server and exercise it with curl or a small Node script, and run `npm run build` in both projects. Write a short README.md at the top level that says how to run everything. When all of this works, reply with a short summary of what you built and how you verified it.
<!-- PROMPT END -->
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# KAR on / off at agent level (docs/experiments/kar-off-ab-5090.md): real Codex CLI sessions on the two frozen tasks of the codex-compare study, same cell runner (cell.py, logging proxy,
# temperature 0 injected, acceptance), arm by arm. Payload of a holder-free window (kar_off_window.sh). Variants: LELK = KAR (shipped rtx5090-32g, own sparse memfd), LELG = GGUF PLE
# (rtx5090-32g-gguf-ple); both are STANDALONE stacks of the same package, so they differ only in the PLE source.
# KO_SEQ space separated "arm:rep" blocks, default "kar:1 gguf:1 gguf:2 kar:2 kar:3 gguf:3" (balanced) KO_TASKS (default "ttt nestng-crm") KO_WALL (3000) KO_ROUNDS (150)
# KO_OUT result dir (default $K/runs/codex)
# One block = one stack start, the warm-up cell smoke-mini and the cells of ONE repetition (task order alternates with the repetition, as in cmp_codex_job.sh).
set -uo pipefail
. /data/leleka-e2e/kar-off-ab/tools/kar_off_common.sh
OUT=${KO_OUT:-$K/runs/codex}
SEQ=${KO_SEQ:-"kar:1 gguf:1 gguf:2 kar:2 kar:3 gguf:3"}
TASKS=${KO_TASKS:-"ttt nestng-crm"}
WALL=${KO_WALL:-3000}; ROUNDS=${KO_ROUNDS:-150}
TASKS_ROOT=$CMP/tasks; CELLPY=$CMP/delta/cell.py; CODEX=/home/para/work/codex-e2e/bin/codex
NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin 2>/dev/null | tail -1); NM=$CMP/nm
mkdir -p "$OUT"
exec > >(tee -a "$OUT/job-$(date -u +%H%M%S).log") 2>&1
KO_SUP_PID=; KO_SAMPLER_PID=
cleanup() { ko_sampler_stop; ko_stop; ko_release; ko_note "codex job ended: $OUT"; }
trap cleanup EXIT
( cd "$CMP" && sha256sum --quiet -c INSTALL.sha256 ) || { echo "codex-compare tools differ from INSTALL.sha256"; exit 3; }
python3 -I "$CMP/delta/taskfile.py" check "$TASKS_ROOT" >"$OUT/tasks-check.txt" 2>&1 || { echo "task files differ from their manifest"; cat "$OUT/tasks-check.txt"; exit 3; }
for t in smoke-mini $TASKS; do [ -f "$TASKS_ROOT/$t/task.md" ] || { echo "task $t is not installed"; exit 3; }; done
[ -x "$CODEX" ] && [ -n "$NODE_BIN" ] && [ -x "$NODE_BIN/node" ] && [ -f "$CMP/toolchain/NESTNG_OK" ] || { echo "no codex / node toolchain"; exit 3; }
ko_guard "$OUT" || exit $?
ko_note "codex job started: seq [$SEQ] tasks [$TASKS] out $OUT"
export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/kar-off-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1
for arm in kar gguf; do ko_prepare "$arm" || { echo "cannot prepare arm $arm"; exit 6; }; done
for blk in $SEQ; do
arm=${blk%%:*}; rep=${blk##*:}
case $arm in kar) VAR=LELK;; gguf) VAR=LELG;; *) echo "bad block $blk"; continue;; esac
STK=$OUT/$VAR/stack-r$rep; mkdir -p "$STK"
# skip a block whose cells all exist
todo=0; for t in $TASKS; do [ -f "$OUT/$VAR/$t-r$rep/cell.json" ] || todo=1; done
[ $todo = 0 ] && { ko_log "block $blk already done: skipped"; continue; }
{ date -u +%FT%TZ; uname -r; free -g | sed -n 2p; uptime; "$CODEX" --version; node --version; } >"$STK/host.txt"
ko_sampler "$STK/host.tsv"
if ! ko_start "$arm" "$STK"; then ko_sampler_stop; ko_stop; continue; fi
if [ "$arm" = gguf ]; then fincore -b -o RES,SIZE "$SHARD1" >"$STK/fincore-before.txt" 2>&1; cat "$SHARD1" >/dev/null; fincore -b -o RES,SIZE "$SHARD1" >"$STK/fincore-after.txt" 2>&1; fi
ST=$(ko_state "$arm"); KEY=$(cat "$ST/api-key")
list="smoke-mini $TASKS"
[ $((rep % 2)) = 0 ] && list="smoke-mini $(echo $TASKS | tr ' ' '\n' | tac | tr '\n' ' ')"
for task in $list; do
CELL=$OUT/$VAR/$task-r$rep; r=$rep
[ "$task" = smoke-mini ] && { CELL=$OUT/$VAR/smoke-mini-r$((100 + rep)); r=$((100 + rep)); }
[ -f "$CELL/cell.json" ] && { ko_log "cell $CELL already done: skipped"; continue; }
link=""; [ "$task" = nestng-crm ] && link="--link-tree backend/node_modules=$NM/backend/node_modules --link-tree frontend/node_modules=$NM/frontend/node_modules"
t1=$(date +%s)
E2E_API_KEY=$KEY CLD_CODEX=$CODEX timeout $((WALL + 900)) python3 -I "$CELLPY" --cell-dir "$CELL" --variant "$VAR" --task "$task" --rep "$r" \
--tasks-root "$TASKS_ROOT" --upstream http://127.0.0.1:8081 --upstream-model qwen-iq3 --codex-bin "$CODEX" --wall-limit "$WALL" --max-rounds "$ROUNDS" \
--engine-log "$ST/logs/engine.log" --active-dir "$OUT/active-$VAR" --config-extra 'model_auto_compact_token_limit = 100000000' $link >"$CELL.out" 2>&1
ko_log "cell $VAR $task r$rep rc=$? $(( $(date +%s) - t1 )) s: $(tail -1 "$CELL.out" | cut -c1-200)"
done
cp "$ST/logs/engine.log" "$STK/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$STK/requests.log" 2>/dev/null
ko_sampler_stop; ko_stop
done
ko_log "done"
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env bash
# KAR on / off A/B (docs/experiments/kar-off-ab-5090.md): shared shell functions. Test tooling, never in serving. Source it, do not run it.
# Both arms run STANDALONE (holder-free window): the lab holder's sealed memfd is the FULL 51.5 GiB archive and leaves ~66 GiB, which cannot hold the 50 GB expert bank AND the 28.8 GB
# PLE table in the page cache. Arm KAR = the shipped profile rtx5090-32g (own sparse memfd of 16 GB, as `leleka run` makes it); arm GGUF = rtx5090-32g-gguf-ple (no archive, PLE rows from
# GGUF shard 1 through the page cache, LELEKA_PLE_DIRECT=0). Same binaries (engine, gateway, API), same assets, same expert profile, same flags otherwise.
K=${KO_ROOT:-/data/leleka-e2e/kar-off-ab}
CMP=/data/leleka-e2e/codex-compare
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib
PKG=$K/pkg # bin/ = the release 17e3729 binaries, `leleka` replaced by the kar_source=none build; MANIFEST.json updated (kar_off_install.sh)
AS=$K/assets # links to the codex-compare release assets (shards, KAR archive, MTP pack, expert profile): nothing is copied
SHARD1=$AS/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
ko_state() { echo "$K/arm-$1/state"; }
ko_prefix() { echo "$K/arm-$1/prefix"; }
ko_profile() { case $1 in kar) echo rtx5090-32g;; gguf) echo rtx5090-32g-gguf-ple;; *) echo "bad arm $1" >&2; return 2;; esac; }
ko_log() { echo "[kar-off $(date -u +%T)] $*"; }
ko_note() { echo "[$(date -u +%FT%TZ)] [DEV kar-off-ab] $*" >>/data/leleka-e2e/decode/notes.md; }
# verify the installed tools and (standalone) take MODEL.lock + gpu.lock; sets KO_STANDALONE; call ko_release in the EXIT trap
ko_guard() {
( cd "$K" && sha256sum --quiet -c INSTALL.sha256 ) || { echo "installed tools differ from INSTALL.sha256"; return 3; }
( cd "$PKG" && sha256sum --quiet -c ../pkg.sha256 ) || { echo "the package differs from pkg.sha256"; return 3; }
mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held (holder still up?)"; return 3; }
KO_STANDALONE=1
local got=0 _
for _ in $(seq 1 4320); do
if mkdir "$LOCK" 2>/dev/null; then echo "kar-off-ab $(date -u +%FT%TZ) $1" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; rmdir "$G/MODEL.lock"; KO_STANDALONE=0; return 3; }
local shmem; shmem=$(awk '/^Shmem:/{print int($2/1048576)}' /proc/meminfo)
[ "$shmem" -lt 8 ] || { echo "Shmem is $shmem GiB: a sealed memfd is still resident"; return 3; }
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "something uses the GPU"; return 3; fi
if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then echo "a stack process exists"; return 3; fi
for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && { echo "port $p in use"; return 3; }; done
export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
}
ko_release() {
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
[ "${KO_STANDALONE:-0}" = 1 ] && rmdir "$G/MODEL.lock" 2>/dev/null
}
# assets (links) and the per-arm state/prefix, idempotent. The verification stamps are copied from the codex-compare state: they are keyed by file identity, not by path.
ko_prepare() { # $1 arm
local arm=$1 st pf prof
st=$(ko_state "$arm"); pf=$(ko_prefix "$arm"); prof=$(ko_profile "$arm") || return 2
if [ ! -e "$AS/model" ]; then
mkdir -p "$AS"; cp -a "$CMP/ours-assets/." "$AS/" || return 5 # symlinks stay links; the small files (provenance, data/*) are hard-linked below
fi
if [ ! -f "$st/leleka.json" ]; then
mkdir -p "$st"; [ -d "$CMP/ours-state/stamps" ] && cp -a "$CMP/ours-state/stamps" "$st/stamps"
timeout 3000 "$PKG/bin/leleka" up --mode none --profile "$prof" --assets "$AS" --state-dir "$st" --prefix "$pf" --bin-src "$PKG/bin" --cublas-dir "$CUBLAS" --trust-archive \
>"$K/arm-$arm/up-prepare.txt" 2>&1
ko_log "up --mode none ($prof) rc=$?"
fi
[ -f "$st/leleka.json" ]
}
# start the stack of one arm in the background; waits for readiness. Sets KO_SUP_PID. $2 = output dir for the up log
ko_start() { # $1 arm $2 outdir
local arm=$1 out=$2 st pf t0 ready=0 _
st=$(ko_state "$arm"); pf=$(ko_prefix "$arm")
mkdir -p "$out"; : >"$st/logs/engine.log" 2>/dev/null
t0=$(date +%s)
# the engine inherits this environment (LELEKA_PLE_DIRECT=0 comes from the gguf profile's engine_env, not from here)
setsid "$PKG/bin/leleka" up --foreground --profile "$(ko_profile "$arm")" --assets "$AS" --state-dir "$st" --prefix "$pf" --bin-src "$PKG/bin" --cublas-dir "$CUBLAS" --trust-archive \
--timeout-s 1800 >"$out/up-foreground.txt" 2>&1 &
KO_SUP_PID=$!
for _ in $(seq 1 700); do
"$pf/bin/leleka" status --state-dir "$st" >/dev/null 2>&1 && { ready=1; break; }
kill -0 "$KO_SUP_PID" 2>/dev/null || break
sleep 3
done
if [ $ready != 1 ]; then ko_log "arm $arm NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$out/up-foreground.txt" | cut -c1-240; return 7; fi
echo "$(( $(date +%s) - t0 ))" >"$out/ready_s.txt"
ko_log "arm $arm ready after $(( $(date +%s) - t0 )) s"
"$pf/bin/leleka" status --state-dir "$st" --json >"$out/status.json" 2>&1
}
ko_stop() {
if [ -n "${KO_SUP_PID:-}" ] && kill -0 "$KO_SUP_PID" 2>/dev/null; then
kill -TERM "$KO_SUP_PID" 2>/dev/null
local _; for _ in $(seq 1 120); do kill -0 "$KO_SUP_PID" 2>/dev/null || break; sleep 2; done
fi
KO_SUP_PID=
pkill -KILL -f "$K/arm-" 2>/dev/null
sleep 5
}
# host sampler: one line every 5 s: epoch, MemAvailable, Cached, Shmem (MiB), sectors read on the model disk, GPU clock/temperature. $1 file
ko_sampler() {
( while :; do
printf '%s %s %s %s %s %s\n' "$(date +%s)" \
"$(awk '/^MemAvailable:/{printf "%d",$2/1024}' /proc/meminfo)" "$(awk '/^Cached:/{printf "%d",$2/1024}' /proc/meminfo)" "$(awk '/^Shmem:/{printf "%d",$2/1024}' /proc/meminfo)" \
"$(awk '$3=="nvme0n1"{print $6}' /proc/diskstats)" "$(nvidia-smi --query-gpu=clocks.sm,temperature.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ')"
sleep 5
done ) >"$1" 2>/dev/null &
KO_SAMPLER_PID=$!
}
ko_sampler_stop() { [ -n "${KO_SAMPLER_PID:-}" ] && kill "$KO_SAMPLER_PID" 2>/dev/null; KO_SAMPLER_PID=; }
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Install the KAR on / off tools on the server (run ON the server): kar_off_install.sh LELEKA_BINARY SCRIPTS_DIR [LELEKA_INFERENCE_BINARY]
# LELEKA_BINARY the `leleka` built from the kar_source=none commit (Linux x86_64) SCRIPTS_DIR scripts/e2e/kar-off copied to the server
# LELEKA_INFERENCE_BINARY the engine built from the same commit (the GGUF-PLE opt-in LELEKA_ORIGINAL_SERVE_GGUF_PLE); both arms then run this engine
# Creates /data/leleka-e2e/kar-off-ab/{tools,pkg,inputs.sha256,INSTALL.sha256,pkg.sha256}. The package is the release 17e3729 binaries (hard links, no copy) with `leleka` replaced; nothing under
# codex-compare/ or spd-gap/ is changed. Frozen measurement inputs (tools + the recorded requests of the two cells) are listed with their sha256.
set -euo pipefail
BIN=${1:?leleka binary}; SRC=${2:?scripts dir}; ENG=${3:-}
K=/data/leleka-e2e/kar-off-ab; CMP=/data/leleka-e2e/codex-compare
mkdir -p "$K/tools" "$K/pkg/bin" "$K/runs"
chmod u+w "$K"/tools/* "$K"/pkg/bin/leleka "$K"/*.sha256 2>/dev/null || true
for f in "$SRC"/*.sh "$SRC"/*.py; do [ -f "$f" ] && install -m 0555 "$f" "$K/tools/$(basename "$f")"; done
install -m 0555 /data/leleka-e2e/spd-gap/tools/replay_fwd.py "$K/tools/replay_fwd.py"
OURS=$CMP/ours-pkg
for b in leleka-cli leleka-daemon leleka-inference leleka-seal-exec strata-next; do [ "$b" = leleka-inference ] && [ -z "$ENG" ] && [ -e "$K/pkg/bin/$b" ] && continue; ln -f "$OURS/bin/$b" "$K/pkg/bin/$b" 2>/dev/null || cp -p "$OURS/bin/$b" "$K/pkg/bin/$b"; done
install -m 0555 "$BIN" "$K/pkg/bin/leleka"
[ -n "$ENG" ] && install -m 0555 "$ENG" "$K/pkg/bin/leleka-inference"
python3 -I - "$OURS/MANIFEST.json" "$K/pkg/MANIFEST.json" "$K/pkg/bin" <<'PY'
import hashlib, json, sys
m = json.load(open(sys.argv[1]))
for b in ("leleka", "leleka-inference"):
m["binaries"][b] = hashlib.sha256(open(sys.argv[3] + "/" + b, "rb").read()).hexdigest()
m["kar_off_ab_note"] = "`leleka` and `leleka-inference` rebuilt from the kar_source=none commits (docs/experiments/kar-off-ab-5090.md); the other binaries are the release 17e3729 ones"
json.dump(m, open(sys.argv[2], "w"), indent=2)
PY
( cd "$K/pkg" && sha256sum bin/* MANIFEST.json > ../pkg.sha256 )
( cd "$K" && sha256sum tools/* > INSTALL.sha256 )
{ for cell in $CMP/runs/main/VANL/nestng-crm-r2 $CMP/runs/main/VANL/ttt-r3; do ls "$cell"/proxy/rounds/*.fwd.json.gz | xargs sha256sum; done; sha256sum "$K/tools/replay_fwd.py"; } > "$K/inputs.sha256"
chmod a-w "$K/inputs.sha256" "$K/INSTALL.sha256" "$K/pkg.sha256"
echo "installed: $(wc -l < "$K/inputs.sha256") input digests, $(wc -l < "$K/INSTALL.sha256") tools"
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# KAR level-2 PLE against GGUF PLE in the Leleka serve stack, teacher forced (docs/experiments/kar-off-ab-5090.md section "Quality (a)"; the method of docs/quality-gate.md section 1 and 6).
# HOLDER JOB (the KAR arm inherits the sealed memfd; the GGUF arm does not need it: LELEKA_REPLAY_GGUF_PLE=1 binds the model without any archive).
# Both arms run the SAME test executable (rt-kar-off = the replay smoke of this branch), the same capture (quality-245k data/cap-both: five prompts of 45k-243k tokens, each with the recorded
# Original reply and the recorded port reply, 300 tokens) forced along the recorded text, top-16 log-probabilities of every row (LELEKA_TRACE_LOGPROBS=16), STATIC expert tier (adapt-every 0:
# placement independent of copy timing), shipped serve shape (prefix cache reply @ 8192). Each run has two twin arms (ship, shipb), so the A/A difference of one PLE source is the noise floor.
# KQ_ARMS which PLE sources, default "kar gguf" KQ_OUT result dir (default $K/runs/quality) KQ_MAX_NEW cap on the forced tokens per request (default: all recorded)
set -uo pipefail
K=/data/leleka-e2e/kar-off-ab
Q=/data/leleka-e2e/quality-245k
LOCK=/data/leleka-e2e/gpu.lock
OUT=${KQ_OUT:-$K/runs/quality}
BIN=${KQ_BIN:-$K/incoming/rt-kar-off}
A=$HOME/work/leleka/models/leleka-gates/assets
G=$HOME/work/gpu-runs
mkdir -p "$OUT"
exec > >(tee -a "$OUT/job-$(date -u +%H%M%S).log") 2>&1
( cd / && sha256sum --quiet -c "$Q/inputs/MANIFEST.sha256" ) || { echo "quality-245k MANIFEST.sha256 check failed"; exit 3; }
[ -x "$BIN" ] || { echo "missing $BIN"; exit 3; }
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
PF='!orig!fast!nocluster!store!qpf!gpool!mspan'
ARMS="ship=reply@8192/8192$PF,shipb=reply@8192/8192$PF"
unset LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_SUFFIX LELEKA_SPEC_POLICY LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB \
LELEKA_FOOTPRINT_LEGACY LELEKA_SM120_ATTN_DAILY LELEKA_DRAFT_FUSED_COMMIT LELEKA_DRAFT_ROUND LELEKA_ROUTE_TAIL_SKIP LELEKA_REPLAY_GGUF_PLE
for src in ${KQ_ARMS:-kar gguf}; do
O=$OUT/$src; mkdir -p "$O"
[ -s "$O/port.full" ] && grep -aq "test result: ok" "$O/port.full" && { echo "arm $src already done: skipped"; continue; }
DEFAULTS=(
LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45
LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_CHAIN=all
LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off
LELEKA_SM120_ATTN_DAILY_MTP=1
LELEKA_SPEC_STATS=1 LELEKA_SPEC_TRACE=1 LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16
LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_REPLAY_DIR=$Q/inputs/data/cap-both LELEKA_REPLAY_FORCE=1 "LELEKA_REPLAY_ARMS=$ARMS" LELEKA_REPLAY_PREFIX_MIB=6144
)
[ -z "${KQ_MAX_NEW:-}" ] || DEFAULTS+=(LELEKA_REPLAY_MAX_NEW=$KQ_MAX_NEW)
[ "$src" = gguf ] && DEFAULTS+=(LELEKA_REPLAY_GGUF_PLE=1 LELEKA_ORIGINAL_SERVE_GGUF_PLE=1)
got=0
for _ in $(seq 1 4320); do
if mkdir $LOCK 2>/dev/null; then echo "kar-off-quality $src $(date -u +%FT%TZ)" >$LOCK/owner; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo)
echo "=== arm $src arms=[$ARMS] MemAvailable GiB: $avail"
if [ "$avail" -lt 55 ]; then echo "abort: less than 55 GiB available"; rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null; exit 4; fi
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,clocks.max.sm,power.limit --format=csv,noheader; sha256sum "$BIN"; wc -l <"$Q/inputs/MANIFEST.sha256"
printf '%s\n' "${DEFAULTS[@]}" | sed 's/^/ENV /'; } >"$O/header.txt"
echo "start $(date -u +%FT%TZ)"
env "${DEFAULTS[@]}" nice -n 5 "$BIN" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke >"$O/port.full" 2>&1
echo "rc=$? arm=$src"; date -u +%FT%TZ
grep -a -E "^REPLAY #|REPLAY PASS|test result|panicked|FAILED|REPLAY-ARM" "$O/port.full" | cut -c1-230 | tail -30
sha256sum "$O/port.full"
rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null
sleep 15
done
echo "done"
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Speed tables of the KAR on / off replay A/B (docs/experiments/kar-off-ab-5090.md). Offline, stdlib only; test tooling.
kar_off_speed.py RUN_DIR [--md OUT.md] [--json OUT.json]
RUN_DIR holds `<arm>-p<n>/` (arm kar|gguf) with `engine.log` (the engine's own `ev:request` records) and `replay.jsonl` (replay_fwd.py). Per run (one stack start):
decode tok/s = sum(output tokens) / sum(decode ms) (pooled over the requests, not a mean of per-request rates)
prefill tok/s = sum(prompt - cached tokens) / sum(prefill ms)
tokens / round = sum(output tokens) / sum(speculative rounds)
Per arm: mean and sample sd over the passes; pairs are pass k of kar against pass k of gguf (the arms alternate, so a pair is two stack starts of the same window, not the same minute).
The recorded replies are not fed back, but each stack produces its own text, so the output tokens (and the speculation they allow) differ between arms; that difference is part of the result and is reported (output tokens per run).
"""
import argparse, glob, json, math, os, re, statistics, sys
def requests(path):
out = []
for line in open(path, encoding="utf-8", errors="replace"):
if '"ev":"request"' not in line or '"comp":"engine"' not in line:
continue
try:
out.append(json.loads(line))
except ValueError:
pass
return out
def pooled(rows):
otok = sum(r["otok"] for r in rows)
dec = sum(r["dec_ms"] for r in rows)
unc = sum(r["ptok"] - r["ctok"] for r in rows)
pf = sum(r["pf_ms"] for r in rows)
rounds = sum(r["rounds"] for r in rows)
return {
"requests": len(rows), "output_tokens": otok, "uncached_prompt_tokens": unc, "decode_s": dec / 1000, "prefill_s": pf / 1000,
"decode_tps": otok / dec * 1000 if dec else float("nan"),
"prefill_tps": unc / pf * 1000 if pf else float("nan"),
"tok_per_round": otok / rounds if rounds else float("nan"),
"tier_vram_pct": statistics.mean(r.get("tier_vram_pct", float("nan")) for r in rows) if rows else float("nan"),
}
def load_run(d):
rows = requests(os.path.join(d, "engine.log"))
replay = [json.loads(l) for l in open(os.path.join(d, "replay.jsonl"))] if os.path.exists(os.path.join(d, "replay.jsonl")) else []
errors = [r for r in replay if r.get("error") or r.get("status") != 200]
res = {"dir": d, "replay_requests": len(replay), "replay_errors": len(errors), "engine_requests": len(rows)}
res["all"] = pooled(rows)
if len(rows) == len(replay): # same order: split by recorded cell
cells = {}
for r, p in zip(rows, replay):
cells.setdefault(p["cell"], []).append(r)
res["cells"] = {c: pooled(v) for c, v in cells.items()}
return res
def ms(xs):
xs = [x for x in xs if not math.isnan(x)]
if not xs:
return float("nan"), float("nan")
return statistics.mean(xs), (statistics.stdev(xs) if len(xs) > 1 else float("nan"))
def fmt(m, s, nd=1):
return "-" if math.isnan(m) else (f"{m:.{nd}f} ± {s:.{nd}f}" if not math.isnan(s) else f"{m:.{nd}f}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("run_dir")
ap.add_argument("--md")
ap.add_argument("--json")
a = ap.parse_args()
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
runs = {}
for d in sorted(glob.glob(os.path.join(a.run_dir, "*-p[0-9]*"))):
m = re.match(r"(kar|gguf)-p(\d+)$", os.path.basename(d))
if not m or not os.path.exists(os.path.join(d, "engine.log")):
continue
order = open(os.path.join(d, "order.txt")).read().strip() if os.path.exists(os.path.join(d, "order.txt")) else "?"
r = load_run(d)
r["order"] = order
runs[(m.group(1), int(m.group(2)))] = r
lines = ["| run | window order | requests | errors | output tokens | decode tok/s | prefill tok/s | tokens / round |", "| --- | --- | --- | --- | --- | --- | --- | --- |"]
for (arm, n), r in sorted(runs.items()):
t = r["all"]
lines.append(f"| {arm} p{n} | {r['order']} | {r['engine_requests']} | {r['replay_errors']} | {t['output_tokens']} | {t['decode_tps']:.1f} | {t['prefill_tps']:.0f} | {t['tok_per_round']:.3f} |")
lines.append("")
summary = {}
metrics = [("decode_tps", "decode tok/s", 1), ("prefill_tps", "prefill tok/s", 0), ("tok_per_round", "tokens / round", 3), ("output_tokens", "output tokens", 0)]
lines += ["| scope | metric | KAR mean ± sd (n) | GGUF mean ± sd (n) | GGUF − KAR, mean of pairs ± sd | GGUF / KAR − 1 |", "| --- | --- | --- | --- | --- | --- |"]
scopes = ["all"] + sorted({c for r in runs.values() for c in r.get("cells", {})})
for scope in scopes:
for key, label, nd in metrics:
def get(r):
return (r["all"] if scope == "all" else r.get("cells", {}).get(scope, {})).get(key, float("nan"))
k = {n: get(r) for (arm, n), r in runs.items() if arm == "kar"}
g = {n: get(r) for (arm, n), r in runs.items() if arm == "gguf"}
km, ks = ms(list(k.values())); gm, gs = ms(list(g.values()))
pairs = [g[n] - k[n] for n in sorted(set(k) & set(g))]
pm, ps = ms(pairs)
rel = (gm / km - 1) * 100 if km and not math.isnan(km) and not math.isnan(gm) else float("nan")
lines.append(f"| {scope} | {label} | {fmt(km, ks, nd)} ({len(k)}) | {fmt(gm, gs, nd)} ({len(g)}) | {fmt(pm, ps, nd)} | {'-' if math.isnan(rel) else f'{rel:+.1f} %'} |")
summary[f"{scope}.{key}"] = {"kar": k, "gguf": g, "pairs": pairs}
text = "\n".join(lines) + "\n"
print(text)
if a.md:
open(a.md, "w", encoding="utf-8").write(text)
if a.json:
json.dump({"runs": {f"{k[0]}-p{k[1]}": v for k, v in runs.items()}, "summary": summary}, open(a.json, "w"), indent=1)
return 0
if __name__ == "__main__":
sys.exit(main())
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# KAR on / off speed A/B (docs/experiments/kar-off-ab-5090.md). Payload of a holder-free window (kar_off_window.sh), NOT a holder job.
# The SAME recorded Codex prompts (the VANL cells nestng-crm-r2 and ttt-r3 of the codex-compare run, 59 requests, 10-120k tokens) are replayed through each arm's service by replay_fwd.py,
# one request at a time, temperature 0; the vanilla `encrypted_content` is stripped by the tool. One stack start per pass; the arms are interleaved (KO_ORDER, default a balanced
# K G G K K G = three passes of each arm, every arm first, second and last in turn). Speed per request is the stack's own record (engine.log `ev:request`: prefill / decode ms,
# tokens, speculative rounds), cut by kar_off_speed.py.
# KO_ORDER space separated arms (kar|gguf), default "kar gguf gguf kar kar gguf" KO_OUT result dir (default $K/runs/speed) KO_CELLS recorded cells KO_MAX requests per cell (0 = all)
set -uo pipefail
. /data/leleka-e2e/kar-off-ab/tools/kar_off_common.sh
OUT=${KO_OUT:-$K/runs/speed}
ORDER=${KO_ORDER:-"kar gguf gguf kar kar gguf"}
CELLS=${KO_CELLS:-"$CMP/runs/main/VANL/nestng-crm-r2 $CMP/runs/main/VANL/ttt-r3"}
MAXR=${KO_MAX:-0}
mkdir -p "$OUT"
exec > >(tee -a "$OUT/job-$(date -u +%H%M%S).log") 2>&1
KO_SUP_PID=; KO_SAMPLER_PID=
cleanup() { ko_sampler_stop; ko_stop; ko_release; ko_note "speed job ended: $OUT"; }
trap cleanup EXIT
# measurement inputs: the recorded requests and the replay tool are frozen and digest-checked
( cd / && sha256sum --quiet -c "$K/inputs.sha256" ) || { echo "measurement inputs differ from inputs.sha256"; exit 3; }
ko_guard "$OUT" || exit $?
ko_note "speed job started: order [$ORDER] cells [$CELLS] out $OUT"
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; sha256sum "$PKG"/bin/*; cat "$K/pkg.sha256" | head -0; } >"$OUT/host.txt"
for arm in kar gguf; do ko_prepare "$arm" || { echo "cannot prepare arm $arm"; exit 6; }; done
declare -A seen=()
pass=0
for arm in $ORDER; do
pass=$((pass + 1)); seen[$arm]=$(( ${seen[$arm]:-0} + 1 ))
D=$OUT/$arm-p${seen[$arm]}
if [ -s "$D/replay.jsonl" ] && [ -f "$D/DONE" ]; then ko_log "$D already done: skipped"; continue; fi
rm -rf "$D"; mkdir -p "$D"
echo "$pass" >"$D/order.txt"
ko_log "pass $pass: arm $arm -> $D"
{ echo "before start:"; grep -E '^(MemTotal|MemAvailable|Cached|Shmem):' /proc/meminfo; } >"$D/mem-before.txt"
ko_sampler "$D/host.tsv"
if ! ko_start "$arm" "$D"; then ko_sampler_stop; ko_stop; continue; fi
if [ "$arm" = gguf ]; then
# vanilla runs `--ple-io ram`: the 28.8 GB table is RAM-resident. Make the page cache hold it before the first request (a sequential read, no write), and say how much of it is resident.
fincore -b -o RES,SIZE "$SHARD1" >"$D/fincore-shard1-before.txt" 2>&1
t1=$(date +%s); cat "$SHARD1" >/dev/null; echo "prewarm cat shard1: $(( $(date +%s) - t1 )) s" >"$D/prewarm.txt"
fincore -b -o RES,SIZE "$SHARD1" >"$D/fincore-shard1-after.txt" 2>&1
fi
{ echo "after ready:"; grep -E '^(MemTotal|MemAvailable|Cached|Shmem):' /proc/meminfo; } >"$D/mem-ready.txt"
rd0=$(awk '$3=="nvme0n1"{print $6}' /proc/diskstats)
args=(); for c in $CELLS; do args+=(--cell "$c"); done
python3 -I "$K/tools/replay_fwd.py" "${args[@]}" --url http://127.0.0.1:8081 --model qwen-iq3 --key-file "$(ko_state "$arm")/api-key" --out "$D/replay.jsonl" --max-requests "$MAXR" >"$D/replay.out" 2>&1
rc=$?
echo "nvme sectors read during the replay: $(( $(awk '$3=="nvme0n1"{print $6}' /proc/diskstats) - rd0 ))" >"$D/nvme-read.txt"
ko_log "replay rc=$rc $(wc -l <"$D/replay.jsonl") requests; $(cat "$D/nvme-read.txt")"
if [ "$arm" = gguf ]; then fincore -b -o RES,SIZE "$SHARD1" >"$D/fincore-shard1-end.txt" 2>&1; fi
cp "$(ko_state "$arm")/logs/engine.log" "$D/engine.log" 2>/dev/null; cp "$(ko_state "$arm")/logs/requests.log" "$D/requests.log" 2>/dev/null
ko_sampler_stop; ko_stop
echo "rc=$rc" >"$D/DONE"
done
ko_log "done"
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# Write the GPU-queue stubs of the KAR on / off study (run ON the server, after kar_off_install.sh) and append them to jobs/PRIORITY (a backup is made first):
# kar_off_stubs.sh smoke|speed|codex|quality [extra KEY=VALUE environment words for the payload]
# smoke window, kar_off_speed_job.sh, order "gguf kar", 2 requests per cell: proves both stacks start, the replay runs and the numbers are readable (about 25 min)
# speed window, kar_off_speed_job.sh, default balanced order (3 passes of each arm, all 59 requests)
# codex window, kar_off_codex_job.sh, default balanced blocks (LELK and LELG, 3 repetitions of both tasks)
# quality HOLDER job (inherits the sealed memfd; the GGUF arm needs none): teacher-forced logit comparison KAR against GGUF PLE, kar_off_quality_job.sh
set -euo pipefail
KIND=${1:?smoke|speed|codex|quality}; shift || true
J=$HOME/work/gpu-runs/holder2/jobs
K=/data/leleka-e2e/kar-off-ab
name=kar-off-$KIND
[ -e "$J/$name.sh" ] && { echo "$J/$name.sh exists"; exit 1; }
case $KIND in
smoke) payload=kar_off_speed_job.sh; env_words="KO_ORDER=\"gguf kar\" KO_MAX=2 KO_OUT=$K/runs/smoke";;
smoke2) payload=kar_off_speed_job.sh; env_words="KO_ORDER=\"gguf kar\" KO_MAX=2 KO_OUT=$K/runs/smoke2";;
smoke3) payload=kar_off_speed_job.sh; env_words="KO_ORDER=\"gguf\" KO_MAX=2 KO_OUT=$K/runs/smoke3";;
smoke4) payload=kar_off_speed_job.sh; env_words="KO_ORDER=\"gguf\" KO_MAX=2 KO_OUT=$K/runs/smoke4";;
smoke5) payload=kar_off_speed_job.sh; env_words="KO_ORDER=\"gguf\" KO_MAX=2 KO_OUT=$K/runs/smoke5";;
speed) payload=kar_off_speed_job.sh; env_words="KO_OUT=$K/runs/speed";;
codex) payload=kar_off_codex_job.sh; env_words="KO_OUT=$K/runs/codex";;
quality) payload=kar_off_quality_job.sh; env_words="";;
quality2) payload=kar_off_quality_job.sh; env_words="KQ_ARMS=gguf KQ_OUT=$K/runs/quality2";;
*) echo "unknown kind"; exit 2;;
esac
if [ "${KIND%2}" = quality ]; then
cat > "$J/$name.sh" <<EOF
#!/usr/bin/env bash
# kar-off-ab: teacher-forced KAR vs GGUF PLE logit comparison (holder job)
export $env_words $*
exec bash $K/tools/$payload
EOF
else
cat > "$J/$name.sh" <<EOF
#!/usr/bin/env bash
# kar-off-ab: $KIND (holder-free window, $payload)
eval "exec \${LELEKA_STRA169_KAR_FD:-9}>&-"
touch "$J/STOP"
export $env_words $*
setsid nohup bash $K/tools/kar_off_window.sh $name $payload > $K/window-$name.launch 2>&1 < /dev/null &
echo "$name: window launched"
EOF
fi
cp -p "$J/PRIORITY" "$J/PRIORITY.bak-kar-off-$KIND"
echo "$name" >> "$J/PRIORITY"
echo "queued $name ($payload $env_words $*)"
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Holder-free window for the KAR on / off payloads (docs/experiments/kar-off-ab-5090.md), started DETACHED by a queue stub that has touched jobs/STOP and closed the holder's descriptor
# (the mechanism of cmp_window.sh): kar_off_window.sh LABEL PAYLOAD.sh
# 1. waits until the lab holder has ended and its memfd is gone; 2. runs the payload; 3. ALWAYS restarts the lab holder afterwards, so the queue goes on.
set -u
LABEL=${1:?label}; PAYLOAD=${2:?payload}
K=/data/leleka-e2e/kar-off-ab
H=$HOME/work/gpu-runs/holder2
note() { echo "[$(date -u +%FT%TZ)] [DEV kar-off-ab] $*" >> /data/leleka-e2e/decode/notes.md; }
restart_holder() {
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then echo "a holder is already running"; return; fi
rmdir "$HOME/work/gpu-runs/MODEL.lock" 2>/dev/null
rm -f "$H/jobs/STOP" "$H/jobs/READY"
# the restarted holder must not inherit this window's KO_* settings (it passes its environment on to every later queue stub)
( cd "$H" && unset $(env | grep -o '^KO_[A-Z_]*') && setsid nohup bash /data/leleka-e2e/single-copy/tools/single-copy-holder.sh > "$H/holder3.out" 2>&1 < /dev/null & )
note "window $LABEL over: holder restarted with single-copy-holder.sh (holder3.out); queue open again"
}
trap restart_holder EXIT
note "window $LABEL: waiting for the holder to end (jobs/STOP is set), then $PAYLOAD"
for _ in $(seq 1 1440); do
if ! pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null && [ ! -d "$HOME/work/gpu-runs/MODEL.lock" ]; then break; fi
sleep 5
done
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then note "window $LABEL: the holder did not end in 2 h, giving up (holder left as it is)"; trap - EXIT; exit 3; fi
sleep 5
note "window $LABEL: holder gone, MemAvailable $(awk '/^MemAvailable:/{printf "%d GiB", $2/1048576}' /proc/meminfo); starting"
bash "$K/tools/$PAYLOAD" > "$K/window-$LABEL.out" 2>&1
note "window $LABEL: $PAYLOAD ended rc=$?; log $K/window-$LABEL.out"
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env python3
"""Analysis of the 245k equivalence test (docs/quality-gate.md, "245k equivalence"). Offline; no runtime use.
Inputs
--data DIR q245_prep output (p<k>.ids, r_<source><k>.ids, meta.json)
--orig NAME=RUNDIR Original run (q245_orig.py --out; plan.json + logpos); the arm is NAME, with the request keys of a read appended
(`NAME` for plain reads, `NAME.k=v` for reads with keys)
--port NAME=LOG:CAPNAME:LABEL[,LABEL...]
port replay-smoke log (LELEKA_REPLAY_FORCE=1, LELEKA_TRACE_LOGPROBS=16, LELEKA_BRINGUP_TRACE=1) of the capture
dir <data>/cap-CAPNAME (sources in the order given to q245_prep.py mkcap); the arm labels (LELEKA_REPLAY_ARMS)
in order; the arm named LABEL becomes `NAME.LABEL`
--pair A:B compare B against A (A is the reference: d_top1 is taken on A's argmax); repeatable
--envelope A:B,A:B,... the pairs that form the Original's own envelope (tolerance = the largest value among them, per statistic)
--judge A:B,... the pairs judged against that tolerance
Row alignment: a row is keyed by its position (the input token's index); only positions of the reply region, from the last token of the prompt
(its row predicts the first reply token) to the second-to-last reply token, that both arms have are compared. Port rows are valid when the window's consumed tokens equal the path.
Statistics per pair (pooled over the rows, and per request): d_top1 = |lp_A(argmax_A) - lp_B(argmax_A)| (what decides tokens), dmax16 = largest
difference over the tokens both top-16 lists hold, argmax flips (with A's top1-top2 margin), top-5 / top-16 overlap, and on the forced text
dNLL = lp_A(target) - lp_B(target) per row (mean +- standard error; exp of the mean is the perplexity ratio B/A).
"""
import argparse, json, math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import q_lib
IM_START = 248045
def ids_file(path):
return [int(x) for x in open(path).read().strip().split(",") if x]
class Data:
def __init__(self, d):
self.d = d
self.meta = json.load(open(os.path.join(d, "meta.json")))["requests"]
self.prompts, self.replies = {}, {}
def prompt(self, k):
if k not in self.prompts:
self.prompts[k] = ids_file(os.path.join(self.d, f"p{k}.ids"))
return self.prompts[k]
def reply(self, source, k):
key = (source, k)
if key not in self.replies:
p = os.path.join(self.d, f"r_{source}{k}.ids")
self.replies[key] = ids_file(p) if os.path.exists(p) else None
return self.replies[key]
def path(self, source, k):
r = self.reply(source, k)
return None if r is None else self.prompt(k) + r
def region(data, source, k, rows):
"""rows {pos: Row} -> the rows of the reply region whose target is the path's next token."""
path = data.path(source, k)
p = len(data.prompt(k))
out = {}
for pos, row in rows.items():
if p - 1 <= pos < len(path) - 1 and row.target == path[pos + 1]:
out[pos] = row
return out
def load_orig(data, name, run_dir):
plan = json.load(open(os.path.join(run_dir, "plan.json")))
arms = {}
lines = open(os.path.join(run_dir, "logpos"), "rb").read()
for req in plan["requests"]:
if req["kind"] != "read":
continue
chunk = lines[req["off0"]:req["off1"]].decode("utf-8", "replace").split("\n")
rows = {}
for line in chunk:
row = q_lib.parse_row(line)
if row is not None:
rows[row.pos] = row
arm = name + ("." + req["keys"] if req["keys"] else "")
reg = region(data, req["source"], req["k"], rows)
if req.get("resume") is not None and req["resume"] > req["turn_at"]:
print(f"WARNING {arm} source {req['source']} k {req['k']}: resumed from {req['resume']} > turn_at {req['turn_at']}: rows missing", file=sys.stderr)
arms.setdefault(arm, {})[(req["source"], req["k"])] = reg
return arms
def load_port(data, name, log, capname, labels):
capdir = os.path.join(data.d, "cap-" + capname)
docs = []
for f in sorted(os.listdir(capdir)):
if f.startswith("req-") and f.endswith(".json"):
d = json.load(open(os.path.join(capdir, f)))
docs.append((d["source"], d["k"]))
arms = {}
by = {}
for run in q_lib.parse_port_log(log):
if run["forced"]:
by.setdefault(run["pass"], {})[run["index"]] = run
for pass_no, label in enumerate(labels):
for n, run in sorted(by.get(pass_no, {}).items()):
if n >= len(docs):
continue
source, k = docs[n]
path = data.path(source, k)
valid = q_lib.valid_rows(run["windows"], path)
arms.setdefault(f"{name}.{label}", {})[(source, k)] = region(data, source, k, valid)
return arms
def stats_of(rows):
"""rows: list of per-row dicts"""
n = len(rows)
if not n:
return {"n": 0}
d1 = [r["d_top1"] for r in rows if not math.isnan(r["d_top1"])]
dm = [r["dmax"] for r in rows if not math.isnan(r["dmax"])]
fl = [r for r in rows if r["flip"]]
dn = [r["dnll"] for r in rows]
mean = sum(dn) / n
sd = math.sqrt(sum((x - mean) ** 2 for x in dn) / max(1, n - 1))
return {"n": n, "missing_top1": n - len(d1),
"d_top1": {"p50": q_lib.quantile(d1, .5), "p90": q_lib.quantile(d1, .9), "p99": q_lib.quantile(d1, .99), "max": max(d1, default=float("nan"))},
"dmax16": {"p50": q_lib.quantile(dm, .5), "p99": q_lib.quantile(dm, .99), "max": max(dm, default=float("nan"))},
"flips": len(fl), "flip_rate": len(fl) / n,
"flip_margin_max": max((r["ref_margin"] for r in fl), default=0.0),
"decisive_flips": sum(1 for r in fl if r["ref_margin"] >= 0.25),
"top5": sum(r["top5"] for r in rows) / n, "top16": sum(r["top16"] for r in rows) / n,
"dnll_mean": mean, "dnll_se": sd / math.sqrt(n), "dnll_abs_mean": sum(abs(x) for x in dn) / n,
"nll_ref": -sum(r["lp_a"] for r in rows) / n, "nll_other": -sum(r["lp_b"] for r in rows) / n}
def pair_rows(a_arm, b_arm):
out = {}
for key in sorted(set(a_arm) & set(b_arm)):
A, B = a_arm[key], b_arm[key]
rows = []
for pos in sorted(set(A) & set(B)):
a, b = A[pos], B[pos]
common = [t for t, _ in a.topk if b.lp(t) is not None]
top1_b = b.lp(a.top1)
rows.append({
"pos": pos,
"d_top1": abs(a.topk[0][1] - top1_b) if top1_b is not None else float("nan"),
"dmax": max((abs(a.lp(t) - b.lp(t)) for t in common), default=float("nan")),
"flip": a.top1 != b.top1, "ref_margin": a.margin,
"top5": len({t for t, _ in a.topk[:5]} & {t for t, _ in b.topk[:5]}) / 5.0,
"top16": len(common) / float(len(a.topk)),
"dnll": a.lp_target - b.lp_target, "lp_a": a.lp_target, "lp_b": b.lp_target})
out[key] = rows
return out
def fmt(s):
if not s["n"]:
return "no common rows"
return (f"n {s['n']:5d} d_top1 p50 {s['d_top1']['p50']:.4f} p99 {s['d_top1']['p99']:.3f} max {s['d_top1']['max']:.3f} "
f"dmax16 p99 {s['dmax16']['p99']:.2f} max {s['dmax16']['max']:.2f} flips {s['flips']} ({100 * s['flip_rate']:.2f}%, max margin {s['flip_margin_max']:.2f}, "
f"decisive>=0.25: {s['decisive_flips']}) top5 {s['top5']:.3f} top16 {s['top16']:.3f} dNLL {s['dnll_mean']:+.4f}+-{s['dnll_se']:.4f} (|.| {s['dnll_abs_mean']:.4f}) ppl ratio {math.exp(-s['dnll_mean']):.4f}")
def pool(per):
return [r for rows in per.values() for r in rows]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--orig", action="append", default=[])
ap.add_argument("--port", action="append", default=[])
ap.add_argument("--pair", action="append", default=[])
ap.add_argument("--envelope", default="")
ap.add_argument("--judge", default="")
ap.add_argument("--sources", default="", help="restrict to these sources (comma list)")
ap.add_argument("--json", default="")
ap.add_argument("--per-request", action="store_true")
a = ap.parse_args()
data = Data(a.data)
arms = {}
for spec in a.orig:
name, d = spec.split("=", 1)
arms.update(load_orig(data, name, d))
for spec in a.port:
name, rest = spec.split("=", 1)
log, cap, labels = rest.split(":")
arms.update(load_port(data, name, log, cap, labels.split(",")))
keep = set(s for s in a.sources.split(",") if s)
if keep:
arms = {n: {k: v for k, v in arm.items() if k[0] in keep} for n, arm in arms.items()}
print("arms:", {n: sorted(arm) and sum(len(v) for v in arm.values()) for n, arm in arms.items()})
for n, arm in arms.items():
miss = [(s, k) for s in sorted({s for s, _ in arm}) for k in sorted({k for _, k in arm}) if (s, k) not in arm]
if miss:
print(f" note: {n} lacks requests {miss}")
print(chr(10) + "FREE GREEDY REPLIES at each depth (the port's recorded reply of the capture against the Original's own free reply to the same prompt)")
for m in data.meta:
k = m["k"]
ra, rb = data.reply("port", k), data.reply("orig", k)
if ra is None or rb is None:
continue
n = next((i for i in range(min(len(ra), len(rb))) if ra[i] != rb[i]), None)
print(f" prompt {k} ({m.get('prompt_len')} tokens): port reply {len(ra)} tokens, Original reply {len(rb)} tokens, first different token: {'none within the shorter' if n is None else n}")
results, cache = {}, {}
def evaluate(pairspec):
if pairspec in cache:
return cache[pairspec]
ra, rb = pairspec.split(":")
per = pair_rows(arms[ra], arms[rb])
pooled = stats_of(pool(per))
res = {"pooled": pooled, "per_request": {f"{s}{k}": stats_of(rows) for (s, k), rows in per.items()}}
cache[pairspec] = res
return res
pairs = list(a.pair) + [p for p in a.envelope.split(",") if p] + [p for p in a.judge.split(",") if p]
for p in dict.fromkeys(pairs):
res = evaluate(p)
results[p] = res
print(f"\n{p}\n pooled {fmt(res['pooled'])}")
if a.per_request:
for key, s in res["per_request"].items():
print(f" {key:8s} {fmt(s)}")
env = [p for p in a.envelope.split(",") if p]
if env:
tol = {"d_top1_p99": 0, "d_top1_max": 0, "dmax16_p99": 0, "flip_rate": 0, "flip_margin_max": 0, "dnll_abs_mean": 0, "dnll_mean_abs": 0, "top5_min": 1.0, "top16_min": 1.0}
for p in env:
s = results[p]["pooled"]
if not s["n"]:
continue
tol["d_top1_p99"] = max(tol["d_top1_p99"], s["d_top1"]["p99"])
tol["d_top1_max"] = max(tol["d_top1_max"], s["d_top1"]["max"])
tol["dmax16_p99"] = max(tol["dmax16_p99"], s["dmax16"]["p99"])
tol["flip_rate"] = max(tol["flip_rate"], s["flip_rate"])
tol["flip_margin_max"] = max(tol["flip_margin_max"], s["flip_margin_max"])
tol["dnll_abs_mean"] = max(tol["dnll_abs_mean"], s["dnll_abs_mean"])
tol["dnll_mean_abs"] = max(tol["dnll_mean_abs"], abs(s["dnll_mean"]))
tol["top5_min"] = min(tol["top5_min"], s["top5"])
tol["top16_min"] = min(tol["top16_min"], s["top16"])
print("\nTOLERANCE (the Original's own envelope, largest over " + ", ".join(env) + "):")
print(" " + json.dumps({k: round(v, 4) for k, v in tol.items()}))
results["tolerance"] = tol
for p in [x for x in a.judge.split(",") if x]:
s = results[p]["pooled"]
if not s["n"]:
print(f"JUDGE {p}: no rows")
continue
miss = lambda t5: max(0.0, 1.0 - t5)
ratios = {
"d_top1_p99": s["d_top1"]["p99"] / tol["d_top1_p99"],
"d_top1_max": s["d_top1"]["max"] / (1.6 * tol["d_top1_max"]), # the largest of 3000 rows is one sample: allowed 1.6x the Original pairs' largest
"flip_rate": s["flip_rate"] / tol["flip_rate"],
"mean|dNLL|": s["dnll_abs_mean"] / tol["dnll_abs_mean"],
"top5_miss": miss(s["top5"]) / max(1e-9, miss(tol["top5_min"])),
"mean_dNLL": abs(s["dnll_mean"]) / max(tol["dnll_mean_abs"], 2 * s["dnll_se"]),
}
worst = max(ratios.values())
verdict = "PASS" if worst <= 1.0 else ("INSIDE_1.25x" if worst <= 1.25 else "FAIL(" + ",".join(k for k, v in ratios.items() if v > 1.25) + ")")
print(f"JUDGE {p}: {verdict} ratio to the Original's envelope (d_top1_max against 1.6x): " + " ".join(f"{k} {v:.2f}" for k, v in ratios.items()))
results[p]["verdict"] = verdict
results[p]["ratios"] = ratios
if a.json:
json.dump(results, open(a.json, "w"), indent=1, default=lambda x: None)
if __name__ == "__main__":
main()
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env bash
# 245k study, tool-call integrity (STRA-328): the real Codex CLI at long context (a ~160k-token AGENTS.md pad in CODEX_HOME + the frozen task set),
# against the port with prefix_cache_tail=reply (shipped), the port with the tail off, and the Original (vanilla Strata 0.2.6). Test tooling, never in serving.
#
# QC_MODE=ours HOLDER JOB (inherits the sealed KAR memfd): unpacks the release package, `leleka up --foreground --kar-fd` once per arm in QC_ARMS
# ("reply off"; reply = the profile's shipped tail, off = `--prefix-cache-tail off`), cells in each, SIGTERM.
# QC_MODE=vanilla holder-free window payload (started by q245_window.sh with Q_PAYLOAD=q245_codex_job.sh): vanilla launcher, both lossy defaults off
# (STRATA_ROUTE_TAIL_SKIP=0, STRATA_PREFILL_CPU_SHARE=0), cells, `launch --stop`.
# QC_TASKS ("fixbug-ledger debuglog-sched") QC_REPS ("1 2 3") QC_PAD (default $Q/inputs/codex/pad.md) QC_RUN (output dir) QC_TAG (cell label suffix)
# QC_CAPTURE=1 (ours): LELEKA_CAPTURE_DIR=$RUN/capture-<arm> (prompt and generated token ids of every request, for the teacher-forced scoring)
# QC_TARBALL (ours, default the final release package) QC_WALL (cell wall limit s, default 1800) QC_ROUNDS (round cap, default 150)
# One cell = cell.py of the codex-lossy-delta study (logging proxy, temperature 0 injected for every variant, task acceptance) + the pad. Cell order alternates
# the tasks inside each repetition. Output: $RUN/<arm>/<task>-r<rep>/ (cell.json, proxy/, acceptance.log, codex-events.jsonl ...), $RUN/<arm>/stack/.
set -uo pipefail
MODE=${QC_MODE:?QC_MODE ours|vanilla}
Q=/data/leleka-e2e/quality-245k
CLD=/data/leleka-e2e/codex-lossy-delta
TASKS_ROOT=$CLD/tasks
CODEX=/home/para/work/codex-e2e/bin/codex
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
A=/home/para/work/leleka/models/leleka-gates/assets
CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib
PAD=${QC_PAD:-$Q/inputs/codex/pad.md}
TASKS=${QC_TASKS:-"fixbug-ledger debuglog-sched"}
REPS=${QC_REPS:-"1 2 3"}
RUN=${QC_RUN:-$Q/runs/codex-$MODE-$(date -u +%Y%m%dT%H%M%SZ)}
WALL=${QC_WALL:-1800}; ROUNDS=${QC_ROUNDS:-150}
CONFIG_EXTRA='model_auto_compact_token_limit = 100000000'
mkdir -p "$RUN"
exec > >(tee -a "$RUN/job.log") 2>&1
log() { echo "[q245-codex $MODE $(date -u +%T)] $*"; }
note() { echo "[$(date -u +%FT%TZ)] [DEV quality-245k] $*" >>/data/leleka-e2e/decode/notes.md; }
# ---- guards ---------------------------------------------------------------------------------------------------------------------------------
( cd / && sha256sum --quiet -c "$Q/inputs/codex/MANIFEST.sha256" ) || { echo "codex inputs differ from MANIFEST.sha256"; exit 3; }
python3 -I "$Q/codex/delta/taskfile.py" check "$TASKS_ROOT" >"$RUN/tasks-check.txt" 2>&1 || { echo "task files differ from their manifest"; cat "$RUN/tasks-check.txt"; exit 3; }
[ -x "$CODEX" ] || { echo "no codex binary"; exit 3; }
[ -f "$PAD" ] || { echo "no pad $PAD"; exit 3; }
STANDALONE=0; FD=${LELEKA_STRA169_KAR_FD:-}
if [ "$MODE" = ours ]; then
readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || { echo "ours mode needs the holder's sealed memfd"; exit 3; }
[ -d "$G/MODEL.lock" ] || { echo "MODEL.lock is not held"; exit 3; }
else
mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held (holder still up?)"; exit 3; }; STANDALONE=1
fi
got=0
for _ in $(seq 1 4320); do
if mkdir "$LOCK" 2>/dev/null; then echo "quality-245k codex $MODE $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; [ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock"; exit 3; }
SUP_PID=
stop_stack() {
if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi
SUP_PID=
}
cleanup() {
stop_stack
pkill -KILL -f "$RUN/prefix/bin/" 2>/dev/null
if [ "$MODE" = vanilla ]; then ( cd "$HOME/work/vanilla-strata/control" && ./bin/strata launch --stop >/dev/null 2>&1 ); fi
sleep 3
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
[ $STANDALONE = 1 ] && rmdir "$G/MODEL.lock" 2>/dev/null
note "codex job $MODE ended: $RUN"
}
trap cleanup EXIT
note "codex job $MODE started: $RUN tasks=[$TASKS] reps=[$REPS] pad=$(wc -c <"$PAD") bytes; holds gpu.lock"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "something uses the GPU"; exit 3; fi
if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then echo "a stack process exists"; exit 3; fi
for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && { echo "port $p in use"; exit 3; }; done
export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; $CODEX --version; sha256sum "$CODEX" "$PAD"; } | tee "$RUN/host.txt"
smoke_check() { # same arguments as run_cells: one smoke-mini cell; the first request must carry the pad (>= 120k input tokens)
local arm=$1 var=$2 url=$3 model=$4 elog=$5 key=$6 n
CELL=$RUN/$arm/smoke-mini-r0
mkdir -p "$RUN/$arm"
E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout 1500 python3 -I "$Q/codex/delta/cell.py" --cell-dir "$CELL" --variant "$var" --task smoke-mini --rep 0 --tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit 900 --max-rounds 60 --engine-log "$elog" --active-dir "$RUN/active-$arm" --agents-md "$PAD" --config-extra "$CONFIG_EXTRA" >"$CELL.out" 2>&1
n=$(python3 -I -c "
import json,sys
r=[json.loads(l) for l in open('$CELL/proxy/rounds.jsonl')]
r=[x for x in r if str(x.get('path','')).endswith('/responses')]
print((r[0].get('resp') or {}).get('input_tokens') or 0 if r else 0, len(r))" 2>/dev/null)
log "smoke $arm: first request input tokens / requests: $n; $(tail -1 "$CELL.out" | cut -c1-160)"
[ "${n%% *}" -ge 120000 ] 2>/dev/null
}
run_cells() { # $1 arm label, $2 variant label, $3 upstream url, $4 upstream model, $5 engine log, $6 api key ('' = none)
local arm=$1 var=$2 url=$3 model=$4 elog=$5 key=$6 rep task t1 rc
mkdir -p "$RUN/$arm"
for rep in $REPS; do
for task in $TASKS; do
CELL=$RUN/$arm/$task-r$rep
t1=$(date +%s)
E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout $((WALL + 900)) python3 -I "$Q/codex/delta/cell.py" --cell-dir "$CELL" --variant "$var" --task "$task" --rep "$rep" \
--tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit "$WALL" --max-rounds "$ROUNDS" \
--engine-log "$elog" --active-dir "$RUN/active-$arm" --agents-md "$PAD" --config-extra "$CONFIG_EXTRA" >"$CELL.out" 2>&1; rc=$?
log "cell $arm $task r$rep rc=$rc $(( $(date +%s) - t1 )) s: $(tail -1 "$CELL.out" | cut -c1-200)"
python3 -I - "$CELL" <<'PY'
import json, os, sys
d = sys.argv[1]
try:
c = json.load(open(os.path.join(d, "cell.json")))
r = [json.loads(l) for l in open(os.path.join(d, "proxy", "rounds.jsonl"))]
rounds = [x for x in r if str(x.get("path", "")).endswith("/responses")]
print(" accepted=%s termination=%s wall=%.0fs requests=%d first_input_tokens=%s last_input_tokens=%s" % (
c.get("accepted"), c.get("termination"), c.get("wall_s", 0), len(rounds),
(rounds[0].get("resp") or {}).get("input_tokens") if rounds else None, (rounds[-1].get("resp") or {}).get("input_tokens") if rounds else None))
except Exception as e:
print(" (no summary: %s)" % e)
PY
done
done
}
if [ "$MODE" = ours ]; then
# ---- the release package, unpacked once; one `leleka up --foreground` per arm --------------------------------------------------------------
TARBALL=${QC_TARBALL:-/data/leleka-e2e/release-5090/leleka-0.1.0-17e372944279-5090-linux-x86_64.tar.xz}
mkdir -p "$RUN/pkg" && tar -xJf "$TARBALL" -C "$RUN/pkg" --strip-components=1 || { echo "unpack failed"; exit 5; }
P=$RUN/pkg; BIN=$P/bin
( cd "$P" && sha256sum --quiet -c SHA256SUMS && echo "SHA256SUMS ok" ); "$BIN/leleka" version | tee "$RUN/version.txt"
AS=$RUN/assets; mkdir -p "$AS/data"
ln -s "$A/model" "$AS/model"; ln -s "$A/tokenizer-assets" "$AS/tokenizer-assets"; ln -s "$A/qwen-iq3-s-l2-v4.kar" "$AS/qwen-iq3-s-l2-v4.kar"
cp "$A/qwen-iq3-s-l2-v4.kar.provenance.json" "$AS/qwen-iq3-s-l2-v4.kar.provenance.json"
cp -al "$A/data/iq3_s" "$AS/data/iq3_s"; cp -al "$A/data/mtp-rt" "$AS/data/mtp-rt"
ST=$RUN/state; PFX=$RUN/prefix
COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD"
timeout 3000 "$BIN/leleka" up --mode none $COMMON >"$RUN/up-prepare.txt" 2>&1; log "up --mode none rc=$?"
[ -f "$ST/leleka.json" ] || { echo "up did not prepare the state"; tail -20 "$RUN/up-prepare.txt"; exit 6; }
for ARM in ${QC_ARMS:-reply off}; do
FLAGS="" # `leleka up` has no --prefix-cache-tail flag: the off arm switches the tail with `leleka reconfigure` once the engine is up (below)
CAPENV=""; [ "${QC_CAPTURE:-0}" = 1 ] && [ "$ARM" = reply ] && { mkdir -p "$RUN/capture-$ARM"; CAPENV="$RUN/capture-$ARM"; }
ST_ARM=$RUN/$ARM; mkdir -p "$ST_ARM/stack"
log "arm $ARM: leleka up --foreground $FLAGS capture=[$CAPENV]"
t0=$(date +%s)
env ${CAPENV:+LELEKA_CAPTURE_DIR=$CAPENV} setsid "$BIN/leleka" up --foreground $COMMON --timeout-s 1800 $FLAGS >"$ST_ARM/stack/up-foreground.txt" 2>&1 &
SUP_PID=$!
ready=0
for _ in $(seq 1 700); do
if "$PFX/bin/leleka" status --state-dir "$ST" >/dev/null 2>&1; then ready=1; break; fi
kill -0 "$SUP_PID" 2>/dev/null || break
sleep 3
done
if [ $ready != 1 ]; then log "arm $ARM NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$ST_ARM/stack/up-foreground.txt" | cut -c1-240; stop_stack; continue; fi
log "arm $ARM ready after $(( $(date +%s) - t0 )) s"
if [ "$ARM" = off ]; then
"$PFX/bin/leleka" reconfigure --state-dir "$ST" --prefix-cache-tail off >"$ST_ARM/stack/reconfigure.txt" 2>&1; log "arm off: reconfigure --prefix-cache-tail off rc=$?"
cat "$ST_ARM/stack/reconfigure.txt" | head -5 | cut -c1-200
fi
"$PFX/bin/leleka" status --state-dir "$ST" >"$ST_ARM/stack/status.txt" 2>&1; "$PFX/bin/leleka" status --state-dir "$ST" --json >"$ST_ARM/stack/status.json" 2>&1
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$ST_ARM/stack/verify-quick.txt" 2>&1
grep -iE "tail|prefix" "$ST_ARM/stack/status.txt" | head -5 | cut -c1-200
KEY=$(cat "$ST/api-key")
smoke_check "$ARM" "Q-$ARM" http://127.0.0.1:8081 qwen-iq3 "$ST/logs/engine.log" "$KEY" || { log "arm $ARM: the pad did not reach the engine (or the smoke cell failed): skipping the arm"; stop_stack; continue; }
run_cells "$ARM" "Q-$ARM" http://127.0.0.1:8081 qwen-iq3 "$ST/logs/engine.log" "$KEY"
cp "$ST/logs/engine.log" "$ST_ARM/stack/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$ST_ARM/stack/requests.log" 2>/dev/null
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$ST_ARM/stack/verify-quick-end.txt" 2>&1
stop_stack
log "arm $ARM stack stopped"
sleep 20
done
else
# ---- vanilla Strata 0.2.6 (launcher + engine 0.1.50), both lossy defaults off, state redirected into the run directory -----------------------------
ARM=vanilla; ST_ARM=$RUN/$ARM; mkdir -p "$ST_ARM/stack"
export XDG_CONFIG_HOME=$ST_ARM/stack/xdg-config XDG_STATE_HOME=$ST_ARM/stack/xdg-state
mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"; cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/"
export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0
unset STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE
S=$HOME/work/vanilla-strata/control/bin/strata
{ sha256sum "$HOME/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata"; cat "$HOME/work/vanilla-strata/control/VERSION" "$HOME/work/vanilla-strata/control/COMMIT" 2>/dev/null; env | grep -E '^STRATA_' | sort; } >"$ST_ARM/stack/env.txt"
cd "$HOME/work/vanilla-strata/control"
t0=$(date +%s)
timeout 2400 "$S" launch --model iq3_s --family qwen --model-path "$A/model" --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes >"$ST_ARM/stack/launch.out" 2>&1
log "vanilla launch rc=$? ready after $(( $(date +%s) - t0 )) s"
if curl -fs http://127.0.0.1:8090/v1/models >"$ST_ARM/stack/models.json"; then
MODEL=$(python3 -c "import json;print(json.load(open('$ST_ARM/stack/models.json'))['data'][0]['id'])")
smoke_check "$ARM" "Q-vanilla" http://127.0.0.1:8090 "$MODEL" "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "" || log "vanilla: smoke cell failed or the pad was not in the first request: continuing anyway"
run_cells "$ARM" "Q-vanilla" http://127.0.0.1:8090 "$MODEL" "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" ""
cp "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "$ST_ARM/stack/engine.log" 2>/dev/null
else
log "vanilla did not become ready"
fi
"$S" launch --stop >>"$ST_ARM/stack/launch.out" 2>&1
sleep 8
fi
log "done"
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Report of the long-context Codex cells of the 245k study (docs/quality-gate.md). Offline; reads the cell directories written by q245_codex_job.sh
(cell.json, proxy/rounds.jsonl and the gzip request / response bodies of the logging proxy). Python >= 3.8, stdlib only.
usage: q245_codex_report.py RUN_DIR [RUN_DIR ...] [--json OUT] [--arms vanilla,reply,off]
Layout read: RUN_DIR/<arm>/<task>-r<rep>/ ; smoke cells (rep 0) are listed apart and never enter a table.
Per cell: accepted (the task's own acceptance), termination, wall time, model requests (rounds), failed rounds (HTTP status != 200, outcome != ok or a stream that does
not end in response.completed), function calls and how many are intact (arguments parse as a JSON object, the tool is one the request declared, a call id is present),
context peak (largest input_tokens) and the cached share of the input. Per (arm, task) the mean / sd / CV of the rounds and the completions; per arm the pooled
CV (rounds divided by the task's mean over all arms). Between arms the first round at which the action sequences of the same task and repetition differ, next to the
same measure between two repetitions of one arm (the run-to-run floor: greedy sessions are not reproducible with an adaptive tier and a prefix cache).
"""
import argparse, glob, json, math, os, sys
HERE = os.path.dirname(os.path.abspath(__file__))
for cand in (os.path.join(HERE, "..", "e2e", "codex", "delta"), "/data/leleka-e2e/quality-245k/codex/delta"):
if os.path.isdir(cand):
sys.path.insert(0, cand)
import index as ix # noqa: E402
def declared(req):
names = set()
for t in req.get("tools") or []:
if isinstance(t, dict):
if t.get("name"):
names.add(t["name"])
fn = t.get("function")
if isinstance(fn, dict) and fn.get("name"):
names.add(fn["name"])
for sub in t.get("tools") or []: # namespace tools
if isinstance(sub, dict) and sub.get("name"):
names.add(sub["name"])
return names
def cell_metrics(d):
info = json.load(open(os.path.join(d, "cell.json")))
rs = ix.cell_rounds(d)
acts = ix.build_actions(d, rs)
m = {"dir": d, "accepted": bool(info.get("accepted")), "termination": info.get("termination"), "wall_s": info.get("wall_s"), "rounds": len(rs),
"failed": 0, "calls": 0, "bad_json": 0, "unknown_tool": 0, "no_call_id": 0, "ctx_peak": 0, "first_in": None, "cached_share": [], "msgs": 0, "reasoning_only": 0}
for a in acts:
rec, u = a["rec"], (a["rec"].get("resp") or {})
if rec.get("status") != 200 or rec.get("outcome") not in (None, "ok") or u.get("terminal") not in (None, "response.completed"):
m["failed"] += 1
inp = u.get("input_tokens") or 0
m["ctx_peak"] = max(m["ctx_peak"], inp)
if m["first_in"] is None:
m["first_in"] = inp
elif inp and u.get("cached_tokens") is not None:
m["cached_share"].append(u["cached_tokens"] / inp)
names = declared(a["req"])
for it in a["out"]:
if it.get("type") == "function_call":
m["calls"] += 1
try:
args = json.loads(it.get("arguments") or "")
if not isinstance(args, dict):
raise ValueError("not an object")
except ValueError:
m["bad_json"] += 1
if names and it.get("name") not in names:
m["unknown_tool"] += 1
if not it.get("call_id"):
m["no_call_id"] += 1
elif it.get("type") == "message":
m["msgs"] += 1
m["cached_share_median"] = sorted(m["cached_share"])[len(m["cached_share"]) // 2] if m["cached_share"] else None
del m["cached_share"]
return m, acts
def mean(xs):
return sum(xs) / len(xs) if xs else float("nan")
def sd(xs):
if len(xs) < 2:
return float("nan")
mu = mean(xs)
return math.sqrt(sum((x - mu) ** 2 for x in xs) / (len(xs) - 1))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("runs", nargs="+")
ap.add_argument("--json", default="")
ap.add_argument("--arms", default="")
a = ap.parse_args()
want = [x for x in a.arms.split(",") if x]
cells, acts_of, smoke = {}, {}, []
for run in a.runs:
for cj in sorted(glob.glob(os.path.join(run, "*", "*-r*", "cell.json"))):
d = os.path.dirname(cj)
arm = os.path.basename(os.path.dirname(d))
if want and arm not in want:
continue
task, rep = os.path.basename(d).rsplit("-r", 1)
rep = int(rep)
m, acts = cell_metrics(d)
m.update({"arm": arm, "task": task, "rep": rep})
if rep == 0:
smoke.append(m)
continue
cells[(arm, task, rep)] = m
acts_of[(arm, task, rep)] = acts
arms = sorted({k[0] for k in cells})
tasks = sorted({k[1] for k in cells})
print("cells:", len(cells), "arms:", arms, "tasks:", tasks)
if smoke:
print("smoke cells (not in the tables):", [(s["arm"], s["first_in"], s["rounds"], s["accepted"]) for s in smoke])
print("\nPER CELL")
print("%-8s %-15s %3s %5s %-9s %6s %6s %6s %5s %5s %5s %7s %7s %6s" % ("arm", "task", "rep", "acc", "term", "wall_s", "rounds", "failed", "calls", "badJ", "unkT", "ctxpeak", "first", "cached"))
for k in sorted(cells):
m = cells[k]
print("%-8s %-15s %3d %5s %-9s %6.0f %6d %6d %5d %5d %5d %7d %7s %6s" % (m["arm"], m["task"], m["rep"], "yes" if m["accepted"] else "NO", m["termination"], m["wall_s"] or 0,
m["rounds"], m["failed"], m["calls"], m["bad_json"], m["unknown_tool"], m["ctx_peak"], m["first_in"], ("%.2f" % m["cached_share_median"]) if m["cached_share_median"] is not None else "-"))
print("\nPER ARM AND TASK (n, accepted, rounds mean +- sd (CV), failed rounds, intact calls)")
table = {}
for arm in arms:
for task in tasks:
cs = [cells[k] for k in sorted(cells) if k[0] == arm and k[1] == task]
if not cs:
continue
rd = [c["rounds"] for c in cs]
row = {"n": len(cs), "accepted": sum(c["accepted"] for c in cs), "rounds_mean": mean(rd), "rounds_sd": sd(rd), "rounds_cv": sd(rd) / mean(rd) if len(rd) > 1 else float("nan"),
"failed": sum(c["failed"] for c in cs), "calls": sum(c["calls"] for c in cs), "bad_json": sum(c["bad_json"] for c in cs), "unknown_tool": sum(c["unknown_tool"] for c in cs),
"ctx_peak_max": max(c["ctx_peak"] for c in cs), "terminations": sorted({c["termination"] for c in cs})}
table[(arm, task)] = row
print("%-8s %-15s n=%d accepted %d/%d rounds %.1f +- %.1f (CV %.0f%%) failed rounds %d calls %d bad JSON %d unknown tool %d ctx peak max %d %s" % (
arm, task, row["n"], row["accepted"], row["n"], row["rounds_mean"], row["rounds_sd"], 100 * row["rounds_cv"], row["failed"], row["calls"], row["bad_json"], row["unknown_tool"],
row["ctx_peak_max"], row["terminations"]))
print("\nPER ARM (pooled)")
task_mean = {t: mean([c["rounds"] for k, c in cells.items() if k[1] == t]) for t in tasks}
pooled = {}
for arm in arms:
cs = [c for k, c in cells.items() if k[0] == arm]
norm = [c["rounds"] / task_mean[c["task"]] for c in cs]
pooled[arm] = {"n": len(cs), "accepted": sum(c["accepted"] for c in cs), "rounds_rel_mean": mean(norm), "rounds_rel_cv": sd(norm) / mean(norm) if len(norm) > 1 else float("nan"),
"failed": sum(c["failed"] for c in cs), "calls": sum(c["calls"] for c in cs), "bad_json": sum(c["bad_json"] for c in cs), "unknown_tool": sum(c["unknown_tool"] for c in cs),
"no_call_id": sum(c["no_call_id"] for c in cs)}
p = pooled[arm]
print("%-8s cells %d accepted %d (%.0f%%) rounds relative to the task mean %.2f (pooled CV %.0f%%) failed rounds %d, function calls %d: bad JSON %d, unknown tool %d, no call id %d" % (
arm, p["n"], p["accepted"], 100.0 * p["accepted"] / max(1, p["n"]), p["rounds_rel_mean"], 100 * p["rounds_rel_cv"], p["failed"], p["calls"], p["bad_json"], p["unknown_tool"], p["no_call_id"]))
print("\nFIRST DIVERGENCE OF THE ACTION SEQUENCE (round number; same task)")
div = {}
for task in tasks:
for arm in arms:
reps = sorted(k[2] for k in cells if k[0] == arm and k[1] == task)
for i in range(len(reps)):
for j in range(i + 1, len(reps)):
r = ix.first_divergence(acts_of[(arm, task, reps[i])], acts_of[(arm, task, reps[j])])
div[("within", arm, task, reps[i], reps[j])] = r[0] if r else None
for i, a1 in enumerate(arms):
for a2 in arms[i + 1:]:
for rep in sorted({k[2] for k in cells if k[0] == a1 and k[1] == task} & {k[2] for k in cells if k[0] == a2 and k[1] == task}):
r = ix.first_divergence(acts_of[(a1, task, rep)], acts_of[(a2, task, rep)])
div[("between", a1 + "~" + a2, task, rep, rep)] = r[0] if r else None
for k, v in sorted(div.items(), key=lambda kv: str(kv[0])):
print(" %-8s %-14s %-15s r%d~r%d first differing round: %s" % (k[0], k[1], k[2], k[3], k[4], "none (identical)" if v is None else v))
if a.json:
json.dump({"cells": {"/".join(map(str, k)): v for k, v in cells.items()}, "table": {"/".join(k): v for k, v in table.items()}, "pooled": pooled,
"divergence": {"/".join(map(str, k)): v for k, v in div.items()}}, open(a.json, "w"), indent=1, default=str)
if __name__ == "__main__":
main()
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Freeze the inputs of the 245k equivalence test (rnr5090): build the two-source capture dir (cap-both = all prompts with the port's recorded replies, then all
# prompts with the Original's own free replies), write MANIFEST.sha256 (data, the job scripts, test binary; absolute paths, checked by every port job with `cd / && sha256sum -c`)
# and make the data read-only. Run once, after the Original's free pass has written r_orig<k>.ids. No hard delete: nothing is removed.
set -euo pipefail
Q=/data/leleka-e2e/quality-245k
cd "$Q/inputs"
for k in 1 2 3 4 5; do [ -s data/r_orig$k.ids ] || { echo "missing data/r_orig$k.ids (run the Original's free pass first)"; exit 3; }; done
chmod -R u+w data 2>/dev/null || true
python3 -I "$Q/tools/q245_prep.py" mkcap data port,orig both
{ find "$Q/inputs/data" -type f | sort | xargs sha256sum; sha256sum "$Q"/tools/q245_port.sh "$Q"/tools/q245_orig.py "$Q"/tools/q245_orig_job.sh "$Q"/bin/*; sha256sum "$Q"/inputs/night5-source.sha256; } > MANIFEST.sha256.new
mv MANIFEST.sha256.new MANIFEST.sha256
chmod -R a-w data
echo "frozen: $(wc -l < MANIFEST.sha256) files in $Q/inputs/MANIFEST.sha256"
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Driver of the Original (vanilla Strata at the pin) for the 245k equivalence test (docs/quality-gate.md, "245k equivalence").
Runs on the 5090 server inside a holder-free window; offline measurement tool, nothing here is part of serving.
One engine process (`strata --serve`, the launch line of the vanilla launcher, both lossy defaults switched off) is fed request by request
over its stdin protocol (`GEN n [key=value ...] <ids>`); the log-probability rows of the verify windows (STRATA_LOGPOS, top-16) are cut per
request by file offset into <out>/plan.json.
pass F (--free) for every prompt k (descending depth): `GEN 300 <prompt k>`, the Original's own greedy reply -> <data>/r_orig<k>.ids
pass R (--sources a,b) for every prompt k (descending): `GEN 1 <prompt k + reply of source a>`, then the same with source b, ...
The prompt is read batched up to its last `<|im_start|>` (a checkpoint is stored there), the assistant header and the
reply go through the verify windows (--short-read), which is the only way the Original exposes log-probabilities.
The second source resumes from that checkpoint, so the prompt state is the same object for both sources.
--keys k=v[,k=v]: after the sources, the reads are repeated with these request keys (e.g. pcie_frac=0, an in-process
perturbation that is part of the Original's own envelope).
A decoy request (short unrelated prompt) separates the passes and the prompts so that no request resumes from another prompt's checkpoint
(descending depth already guarantees it for one-slot checkpoint caches; RESUME is recorded per request and checked).
usage: q245_orig.py --data DIR --out DIR [--free] [--sources port,orig] [--keys pcie_frac=0] [--prefill auto|N] [--tag NAME]
[--ks 5,4,3,2,1] [--max-new 300] [--engine PATH] [--extra-flag FLAG ...]
"""
import argparse, json, os, subprocess, sys, threading, time
ENGINE = os.path.expanduser("~/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata")
SHARDS = "/home/para/work/leleka/models/leleka-gates/assets/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-0000%d-of-00002.gguf"
PACK = os.path.expanduser("~/.local/share/strata/Strata-data/packs/iq3_s")
MTP = os.path.expanduser("~/.local/share/strata/Strata-data/mtp/rt")
PROFILE = os.path.expanduser("~/work/vanilla-strata/control/data/expert-profile.bin")
IM_START = 248045
def ids_file(path):
return [int(x) for x in open(path).read().strip().split(",") if x]
class Engine:
def __init__(self, out, prefill, extra, engine, env_extra, kind="vanilla", ple="gguf"):
self.out = out
if kind == "old":
# the reference build of the earlier gate (docs/quality-gate.md): Strata engine 0.1.35 + local patches, static tier, 2048 per-layer slots from the placeholder
# profile, the flags of scripts/quality/q-common.sh orig_serve; PLE from the GGUF shard 2 (--ple gguf) or from the KAR archive file, level 2 (--ple kar)
assets = "/home/para/work/leleka/models/leleka-gates/assets"
cmd = [engine, "--pack", assets + "/data/iq3_s", "--native", SHARDS % 1, "--ple-gguf", SHARDS % 2, "--serve", "--mtp", assets + "/data/mtp-rt", "--kv", "int8",
"--spec", "4", "--suffix-draft", "3", "--spec-min-p", "0.5", "--expert-profile", os.path.expanduser("~/work/gpu-runs/baseline/profile.bin"),
"--pcie-frac", "0.55", "--prefill", "8192" if prefill == "auto" else prefill, "--max-context", "262144", "--kv-resident", "20480",
"--prompt-cache", "1", "--prompt-cache-every", "0", "--prompt-cache-root", "0", "--short-read", "1024", "--expert-cache", "2048",
"--expert-cache-per-layer", "--adapt-every", "0"] + list(extra)
if ple == "kar":
cmd += ["--ple-kar", assets + "/qwen-iq3-s-l2-v4.kar", "--ple-kar-level", "2"]
else:
cmd = [engine, "--serve", "--pack", PACK, "--native", SHARDS % 1, "--ple-gguf", SHARDS % 2, "--expert-profile", PROFILE,
"--expert-cache", "auto", "--prefill", prefill, "--spec", "4", "--spec-min-p", "0.5", "--mtp", MTP,
"--max-context", "262144", "--kv", "int8", "--ple-io", "ram", "--kv-resident", "32768",
# the checkpoint of the last turn boundary is the only cache: one slot, no periodic checkpoints, no parked conversations
"--prompt-cache", "1", "--prompt-cache-every", "0", "--prompt-cache-root", "0", "--conversation-cache-mib", "0",
"--short-read", "1024"] + list(extra)
self.cmd = cmd
env = dict(os.environ)
env.update({"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_PREFILL_CPU_SHARE": "0", "STRATA_LOGPOS": os.path.join(out, "logpos"),
"STRATA_LOGPOS_TOPK": "16"})
env.update(env_extra)
self.env = env
open(os.path.join(out, "cmd.txt"), "w").write(" ".join(cmd) + "\n" + "\n".join(f"{k}={env[k]}" for k in sorted(env) if k.startswith("STRATA_")) + "\n")
self.err = open(os.path.join(out, "engine.err"), "wb")
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.err, env=env, bufsize=0)
self.lines = []
self.cv = threading.Condition()
threading.Thread(target=self._reader, daemon=True).start()
def _reader(self):
buf = b""
while True:
chunk = self.proc.stdout.read1(1 << 16) if hasattr(self.proc.stdout, "read1") else self.proc.stdout.read(1 << 16)
if not chunk:
break
buf += chunk
while b"\n" in buf:
line, buf = buf.split(b"\n", 1)
with self.cv:
self.lines.append(line.decode("utf-8", "replace"))
self.cv.notify_all()
with self.cv:
self.lines.append("<<EOF>>")
self.cv.notify_all()
def next_line(self, timeout):
end = time.time() + timeout
with self.cv:
while not self.lines:
left = end - time.time()
if left <= 0:
return None
self.cv.wait(left)
return self.lines.pop(0)
def wait_ready(self, timeout=1800):
end = time.time() + timeout
while time.time() < end:
line = self.next_line(5)
if line is None:
continue
if line.startswith("READY"):
return line
if line == "<<EOF>>":
raise RuntimeError("engine exited before READY; see engine.err")
raise RuntimeError("engine not ready in %d s" % timeout)
def request(self, line, timeout=3600):
self.proc.stdin.write((line + "\n").encode())
self.proc.stdin.flush()
toks, info, end = [], {}, time.time() + timeout
while time.time() < end:
l = self.next_line(30)
if l is None:
continue
if l == "<<EOF>>":
raise RuntimeError("engine died during a request; see engine.err")
if l.startswith("T "):
toks.append(int(l.split()[1]))
elif l.startswith("RESUME"):
info["resume"] = int(l.split()[1])
elif l.startswith("REUSED"):
info["reused"] = int(l.split()[1])
elif l.startswith("DONE"):
info["done"] = l
return toks, info
elif l.startswith("ERR"):
info["err"] = l
return toks, info
raise RuntimeError("request timed out")
def quit(self):
try:
self.proc.stdin.write(b"QUIT\n")
self.proc.stdin.flush()
except Exception:
pass
try:
self.proc.wait(120)
except Exception:
self.proc.kill()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--free", action="store_true")
ap.add_argument("--sources", default="")
ap.add_argument("--keys", default="")
ap.add_argument("--prefill", default="auto")
ap.add_argument("--tag", default="orig")
ap.add_argument("--free-name", default="orig", help="the free replies are written to <data>/r_<free-name><k>.ids")
ap.add_argument("--ks", default="5,4,3,2,1")
ap.add_argument("--max-new", type=int, default=300)
ap.add_argument("--engine", default=ENGINE)
ap.add_argument("--kind", default="vanilla", choices=["vanilla", "old"])
ap.add_argument("--ple", default="gguf", choices=["gguf", "kar"])
ap.add_argument("--extra-flag", action="append", default=[])
ap.add_argument("--env", action="append", default=[], help="KEY=VALUE for the engine")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
ks = [int(x) for x in a.ks.split(",")]
sources = [s for s in a.sources.split(",") if s]
prompts = {k: ids_file(os.path.join(a.data, f"p{k}.ids")) for k in ks}
engine = a.engine
if a.kind == "old" and engine == ENGINE:
engine = "/home/para/work/leleka/models/leleka-gates/stra169-ladder/build-sm120/strata"
eng = Engine(a.out, a.prefill, a.extra_flag, engine, dict(e.split("=", 1) for e in a.env), a.kind, a.ple)
plan = {"tag": a.tag, "cmd": eng.cmd, "requests": []}
logpos = os.path.join(a.out, "logpos")
def size():
return os.path.getsize(logpos) if os.path.exists(logpos) else 0
def run(kind, k, source, keys, ids, gen):
before = size()
t0 = time.time()
toks, info = eng.request(f"GEN {gen} " + (" ".join(keys.split(",")) + " " if keys else "") + ",".join(map(str, ids)))
rec = {"kind": kind, "k": k, "source": source, "keys": keys, "n_ids": len(ids), "turn_at": max(i for i, t in enumerate(ids) if t == IM_START),
"off0": before, "off1": size(), "resume": info.get("resume"), "reused": info.get("reused"), "done": info.get("done"),
"err": info.get("err"), "wall_s": round(time.time() - t0, 1), "n_tokens": len(toks)}
plan["requests"].append(rec)
json.dump(plan, open(os.path.join(a.out, "plan.json"), "w"), indent=1)
print(json.dumps({x: rec[x] for x in ("kind", "k", "source", "keys", "n_ids", "resume", "wall_s", "n_tokens", "err")}), flush=True)
return toks
def decoy():
ids = [IM_START] + [1000 + (i * 7) % 5000 for i in range(1500)] + [IM_START, 872, 198, 4]
run("decoy", 0, "", "", ids, 1)
print("ready:", eng.wait_ready(), flush=True)
try:
if a.free:
decoy()
for k in ks:
toks = run("free", k, "", "", prompts[k], a.max_new)
open(os.path.join(a.data, f"r_{a.free_name}{k}.ids"), "w").write(",".join(map(str, toks)))
if sources:
decoy()
for k in ks:
for s in sources:
reply = ids_file(os.path.join(a.data, f"r_{s}{k}.ids"))
run("read", k, s, "", prompts[k] + reply, 1)
if a.keys:
for s in sources:
reply = ids_file(os.path.join(a.data, f"r_{s}{k}.ids"))
run("read", k, s, a.keys, prompts[k] + reply, 1)
finally:
eng.quit()
json.dump(plan, open(os.path.join(a.out, "plan.json"), "w"), indent=1)
print("done", flush=True)
if __name__ == "__main__":
main()
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# 245k equivalence test, Original side: a holder-free window payload (rnr5090). The Original (vanilla Strata 0.2.6 engine 0.1.50, the pin's code) needs the
# host RAM the lab holder's sealed archive occupies, so it never runs beside the holder (docs/quality-gate.md, "245k equivalence").
#
# stub ~/work/gpu-runs/holder2/jobs/<name>.sh:
# eval "exec ${LELEKA_STRA169_KAR_FD:-9}>&-"
# touch "$HOME/work/gpu-runs/holder2/jobs/STOP"
# Q_RUNS="<tag>|<flags>;..." setsid nohup bash /data/leleka-e2e/quality-245k/tools/q245_window.sh <label> > .../window-<label>.launch 2>&1 < /dev/null &
#
# Q_RUNS is a semicolon-separated list of Original processes, each TAG|FLAGS with FLAGS passed to q245_orig.py, e.g.
# Q_RUNS="oa|--free --sources port,orig --keys pcie_frac=0;ob|--sources port,orig"
# Output of process TAG: $Q/runs/orig-$TAG/ (cmd.txt, engine.err, logpos, plan.json, driver.out).
set -uo pipefail
Q=/data/leleka-e2e/quality-245k
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
notes() { echo "[$(date -u +%FT%TZ)] [DEV quality-245k] $*" >> /data/leleka-e2e/decode/notes.md; }
got=0
for _ in $(seq 1 4320); do
if mkdir "$LOCK" 2>/dev/null; then echo "quality-245k original $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
mkdir "$G/MODEL.lock" 2>/dev/null || { echo "MODEL.lock is held"; rm -f "$LOCK/owner"; rmdir "$LOCK"; exit 3; }
trap 'rmdir "$G/MODEL.lock" 2>/dev/null; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; notes "original window payload ended"' EXIT
notes "original window payload started: $Q_RUNS"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then echo "GPU busy"; exit 3; fi
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"
[ "$avail" -ge 90 ] || { echo "abort: MemAvailable $avail GiB < 90 (is the holder gone?)"; exit 4; }
for tool in q245_orig.py q_lib.py; do [ -r "$Q/tools/$tool" ] || { echo "missing $Q/tools/$tool"; exit 3; }; done
# frozen inputs that exist before the Original ran: prompts and the port's recorded replies
DATA=${Q_DATA:-$Q/inputs/data}
if [ -n "${Q_MANIFEST:-}" ]; then ( cd / && sha256sum --quiet -c "$Q_MANIFEST" ) || { echo "inputs differ from $Q_MANIFEST"; exit 3; }; fi
IFS=';' read -ra SPECS <<< "$Q_RUNS"
for spec in "${SPECS[@]}"; do
tag=${spec%%|*}; flags=${spec#*|}
d=$Q/runs/orig-$tag; mkdir -p "$d"
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; sha256sum ~/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata; free -g | sed -n 2p; } > "$d/header.txt"
notes "original process $tag: $flags"
python3 -I "$Q/tools/q245_orig.py" --data "$DATA" --out "$d" --tag "$tag" $flags > "$d/driver.out" 2>&1; rc=$?
notes "original process $tag ended rc=$rc ($d)"
tail -3 "$d/driver.out" | cut -c1-200
sleep 20
done
if [ "${Q_FREEZE:-0}" = 1 ]; then bash "$Q/tools/q245_freeze.sh" && notes "inputs frozen (cap-both, MANIFEST.sha256)"; fi
sha256sum "$Q"/runs/orig-*/plan.json "$Q"/runs/orig-*/logpos 2>/dev/null | tail -20
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Long-context pad for the Codex cells of the 245k study (docs/quality-gate.md): concatenates source files of the frozen corpus
(/data/leleka-e2e/decode/corpus/src/crates, read-only) in path order, each under a header line, up to about --chars characters
(whole files only). Codex reads $CODEX_HOME/AGENTS.md without the 32 KiB cap of the project document and sends it in the first request
as a user message (verified: an 810 kB file arrives whole), so every request of the session carries the pad: the same long-context
regime as the 245k corpus session, with the real Codex tool loop on top. The text is the same for every variant.
usage: q245_pad.py CORPUS_DIR OUT --chars 528000
"""
import os, sys, hashlib
HEADER = ("# Reference material (read-only background)\n\n"
"The sources below are a vendored snapshot of a Rust workspace that is unrelated to the task you are given. They are only here for "
"reference; do not edit them and ignore them unless the task asks about them.\n\n")
def main(argv):
root, out = argv[0], argv[1]
target = int(argv[argv.index("--chars") + 1]) if "--chars" in argv else 528000
parts, n = [HEADER], len(HEADER)
for d, dirs, files in os.walk(root):
dirs.sort()
for f in sorted(files):
if not f.endswith(".rs"):
continue
p = os.path.join(d, f)
text = open(p, encoding="utf-8", errors="replace").read()
block = "=== %s ===\n%s\n\n" % (os.path.relpath(p, root).replace(os.sep, "/"), text)
if n + len(block) > target:
continue
parts.append(block)
n += len(block)
data = "".join(parts)
open(out, "w", encoding="utf-8", newline="\n").write(data)
print(len(data), "chars,", len(parts) - 1, "files,", hashlib.sha256(data.encode("utf-8")).hexdigest())
if __name__ == "__main__":
main(sys.argv[1:])
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
# 245k equivalence test, port side: teacher-forced replay of a q245_prep capture dir by the port's replay smoke, production shape, top-16 logprobs of every row.
# HOLDER JOB payload (the stub in ~/work/gpu-runs/holder2/jobs/<name>.sh only sets the knobs and execs this; the holder passes the sealed KAR descriptor).
# Copy of the shape of windowpolicy-id.sh (docs/experiments/window-policy-5090.md): shipped `rtx5090-32g` engine environment, adaptive window, adaptive tier,
# upstream ranked expert profile, seed OFF, PCIe share 0.45, prefix cache 6144 MiB with the tail mode of the arm.
# Q_LABEL run name (output $Q/runs/$Q_LABEL/port.full) (required)
# Q_CAP capture dir name under $Q/inputs/$Q_DATA (cap-<name>) (required)
# Q_DATA data dir under $Q/inputs (default data; data-s3 = the Codex rounds) Q_MANIFEST its manifest (default $Q/inputs/MANIFEST.sha256)
# Q_ARMS LELEKA_REPLAY_ARMS, label=mode,...; the literal @PF@ expands to the production arm flags (required)
# Q_PREFIX_MIB prefix cache budget (default 6144; `none`: no prefix cache, every request prefills cold)
# Q_ENV extra KEY=VALUE words for the process (override the defaults below)
# Q_BIN test executable (default $Q/bin/rt-q245)
# Q_MAX_NEW cap on the forced tokens per request (default: the whole recorded reply)
# Every input is checked against $Q/inputs/MANIFEST.sha256 first.
set -uo pipefail
Q=/data/leleka-e2e/quality-245k
LOCK=/data/leleka-e2e/gpu.lock
LABEL=${Q_LABEL:?Q_LABEL}; CAP=${Q_CAP:?Q_CAP}; ARMS=${Q_ARMS:?Q_ARMS}
BIN=${Q_BIN:-$Q/bin/rt-q245}
PREFIX=${Q_PREFIX_MIB:-6144}
O=$Q/runs/$LABEL
mkdir -p "$O"
( cd / && sha256sum --quiet -c "${Q_MANIFEST:-$Q/inputs/MANIFEST.sha256}" ) || { echo "q245: MANIFEST.sha256 check failed" >&2; exit 3; }
[ -x "$BIN" ] || { echo "missing $BIN" >&2; exit 3; }
PF='!orig!fast!nocluster!store!qpf!gpool!mspan'
ARMS=${ARMS//@PF@/$PF}
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
A=$HOME/leleka-gates/assets
G=$HOME/work/gpu-runs
unset LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_SUFFIX LELEKA_SPEC_POLICY LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB \
LELEKA_FOOTPRINT_LEGACY LELEKA_SM120_ATTN_DAILY LELEKA_DRAFT_FUSED_COMMIT LELEKA_DRAFT_ROUND LELEKA_ROUTE_TAIL_SKIP
DEFAULTS=(
LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45
LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto LELEKA_CHAIN=all
LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=4 LELEKA_ORIGINAL_SERVE_SEED=off
LELEKA_SM120_ATTN_DAILY_MTP=1
LELEKA_SPEC_STATS=1 LELEKA_SPEC_TRACE=1 LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16
LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_REPLAY_DIR=$Q/inputs/${Q_DATA:-data}/cap-$CAP LELEKA_REPLAY_FORCE=1 "LELEKA_REPLAY_ARMS=$ARMS"
)
[ "$PREFIX" = none ] || DEFAULTS+=(LELEKA_REPLAY_PREFIX_MIB=$PREFIX)
[ -z "${Q_MAX_NEW:-}" ] || DEFAULTS+=(LELEKA_REPLAY_MAX_NEW=$Q_MAX_NEW)
got=0
for _ in $(seq 1 4320); do
if mkdir $LOCK 2>/dev/null; then echo "quality-245k $LABEL $(date -u +%FT%TZ)" >$LOCK/owner; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
trap 'rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null' EXIT
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo)
echo "=== $LABEL arms=[$ARMS] cap=$CAP prefix=$PREFIX extra=[${Q_ENV:-}] MemAvailable GiB: $avail"
if [ "$avail" -lt 60 ]; then echo "abort: less than 60 GiB available"; exit 4; fi
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,clocks.max.sm,power.limit --format=csv,noheader; sha256sum "$BIN"; cat $Q/inputs/MANIFEST.sha256 | wc -l
printf '%s\n' "${DEFAULTS[@]}" ${Q_ENV:-} | sed 's/^/ENV /'; } > $O/header.txt
echo "start $(date -u +%FT%TZ)"
env "${DEFAULTS[@]}" ${Q_ENV:-} nice -n 5 "$BIN" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke > $O/port.full 2>&1
echo "rc=$? label=$LABEL"; date -u +%FT%TZ
grep -a -E "^REPLAY #|REPLAY PASS|test result|panicked|FAILED|expert cache [0-9]+ slots|REPLAY-ARM" $O/port.full | cut -c1-230 | tail -60
sha256sum $O/port.full
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Inputs of the 245k equivalence test (docs/quality-gate.md, section "245k equivalence"). Offline; no runtime use.
q245_prep.py prep CAPTURE_DIR OUT split a capture dir (req-NNNNNN.json with prompt_ids / generated_ids) into
OUT/p<k>.ids (prompt), OUT/r_port<k>.ids (the recorded reply) and OUT/meta.json
q245_prep.py mkcap OUT SRC NAME [--max-new N]
OUT/cap-NAME/req-00000k.json: the prompts of OUT with the replies of source SRC
(OUT/r_<SRC><k>.ids) as the recorded reply; for the port's replay smoke
(LELEKA_REPLAY_DIR). With several SRC (comma list) the requests of the sources
follow each other (all prompts of SRC1, then all of SRC2).
q245_prep.py sha DIR sha256 of every file under DIR (for MANIFEST.sha256)
A request is the prompt (ends with the assistant header `<|im_start|>assistant\\n<think>\\n`, 5 tokens) and a forced reply. The same
token path is scored by the Original (prompt batched up to the last `<|im_start|>`, header and reply through the verify windows)
and by the port (prompt prefilled, reply decoded along the forced path).
"""
import glob, hashlib, json, os, sys
IM_START = 248045
def ids_of(doc, key):
return [int(x) for x in doc[key]]
def prep(capture, out):
os.makedirs(out, exist_ok=True)
files = sorted(glob.glob(os.path.join(capture, "req-*.json")))
meta = []
for k, path in enumerate(files, 1):
doc = json.load(open(path))
prompt, reply = ids_of(doc, "prompt_ids"), ids_of(doc, "generated_ids")
turn_at = max(i for i, t in enumerate(prompt) if t == IM_START)
open(os.path.join(out, f"p{k}.ids"), "w").write(",".join(map(str, prompt)))
open(os.path.join(out, f"r_port{k}.ids"), "w").write(",".join(map(str, reply)))
meta.append({"k": k, "prompt_len": len(prompt), "reply_len": len(reply), "turn_at": turn_at,
"header_len": len(prompt) - turn_at, "source_file": os.path.basename(path)})
json.dump({"capture": os.path.abspath(capture), "requests": meta}, open(os.path.join(out, "meta.json"), "w"), indent=1)
for m in meta:
print(m)
def mkcap(out, sources, name, max_new=None):
meta = json.load(open(os.path.join(out, "meta.json")))["requests"]
cap = os.path.join(out, "cap-" + name)
os.makedirs(cap, exist_ok=True)
n = 0
for src in sources.split(","):
for m in meta:
k = m["k"]
prompt = [int(x) for x in open(os.path.join(out, f"p{k}.ids")).read().strip().split(",")]
reply = [int(x) for x in open(os.path.join(out, f"r_{src}{k}.ids")).read().strip().split(",") if x]
n += 1
doc = {"index": n, "source": src, "k": k, "max_new": max_new or len(reply), "temperature_milli": 0, "top_p_micro": None, "top_k": None,
"min_p_micro": None, "repetition_penalty_micro": None, "frequency_penalty_micro": None, "presence_penalty_micro": None,
"penalty_last_n": None, "seed": None, "prompt_tokens": len(prompt), "reused": 0, "rounds": 0, "produced": len(reply),
"prompt_ids": prompt, "generated_ids": reply}
json.dump(doc, open(os.path.join(cap, "req-%06d.json" % n), "w"))
print(n, "requests ->", cap)
def sha(directory):
for root, _, names in sorted(os.walk(directory)):
for f in sorted(names):
p = os.path.join(root, f)
h = hashlib.sha256()
with open(p, "rb") as fh:
for block in iter(lambda: fh.read(1 << 20), b""):
h.update(block)
print(h.hexdigest() + " " + p)
def main(argv):
if not argv:
print(__doc__)
return 2
cmd = argv[0]
if cmd == "prep":
prep(argv[1], argv[2])
elif cmd == "mkcap":
mx = int(argv[argv.index("--max-new") + 1]) if "--max-new" in argv else None
mkcap(argv[1], argv[2], argv[3], mx)
elif cmd == "sha":
sha(argv[1])
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Regenerates the S1/S2 tables of docs/quality-gate.md section 13 from the run directories under /data/leleka-e2e/quality-245k/runs (offline, CPU only).
# usage: q245_report_s12.sh [OUT_DIR] (default analysis/)
set -uo pipefail
Q=/data/leleka-e2e/quality-245k
O=${1:-$Q/analysis}; mkdir -p "$O"; cd "$Q"
ARGS="--data inputs/data --orig oa=runs/orig-oa --orig ob=runs/orig-ob --orig oc=runs/orig-oc --orig olg=runs/orig-olg --orig olk=runs/orig-olk --orig olk2=runs/orig-olk2 \
--port pa=runs/pa/port.full:both:ship,shipb,tailoff --port pb=runs/pb/port.full:both:cold8192,cold2048 --port pc=runs/pc/port.full:both:ship --port pd=runs/pd/port.full:both:ship --port pe=runs/pe/port.full:both:ship"
ENV="--envelope oa:ob,oa:oa.pcie_frac=0,oa:oc,ob:oc"
J="oa:pa.ship,oa:pa.shipb,oa:pa.tailoff,oa:pb.cold8192,oa:pb.cold2048,oa:pc.ship,oa:pd.ship,oa:pe.ship,olk:pa.ship,olk:pa.shipb,olk:pa.tailoff,olk:pb.cold8192,olk:pb.cold2048,olk:pc.ship,olk:pd.ship,olk:pe.ship,oa:olk,oa:olg,olg:olk,pa.ship:pa.shipb,pa.ship:pa.tailoff,pa.ship:pb.cold8192,pb.cold8192:pb.cold2048,pa.ship:pc.ship,pa.ship:pd.ship,pa.ship:pe.ship"
python3 -I tools/q245_analyze.py $ARGS $ENV --judge $J --pair olk:olk2 --per-request --json "$O/s12.json" > "$O/s12-all.txt" 2>&1
for src in port orig; do python3 -I tools/q245_analyze.py $ARGS $ENV --judge $J --sources $src > "$O/s12-src-$src.txt" 2>&1; done
grep -E "^JUDGE|^TOLERANCE|^ \{" "$O/s12-all.txt" | cut -c1-260
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Rounds of a captured Codex session as a teacher-forced probe set (docs/quality-gate.md, "245k equivalence", set S3). Offline; no runtime use.
q245_s3.py CAPTURE_DIR OUT [--first N] [--count M] [--step S] [--max-reply T]
Takes the requests N, N+S, ... (1-based index in CAPTURE_DIR/req-NNNNNN.json, M of them) of a `LELEKA_CAPTURE_DIR` capture of the port (prompt_ids and
generated_ids of every served request) and writes the data-dir layout of q245_prep.py (p<k>.ids, r_port<k>.ids, meta.json) plus OUT/cap-s3 (the port's
replay input). A request qualifies when its prompt ends with a 5-token assistant header (`<|im_start|>` assistant \n <think> \n) and the reply is
not empty; the reply is cut to --max-reply tokens (default 400). The replies are the tool calls, reasoning text and messages the port itself produced
in the real Codex loop.
"""
import glob, json, os, sys
IM_START = 248045
def cell_range(arm_dir, cell_name):
"""(first, count): the 1-based capture indexes of the completed requests of one cell, from the cells of the arm in start order (the capture numbers the requests of the engine process)"""
cells = []
for name in os.listdir(arm_dir):
cj = os.path.join(arm_dir, name, "cell.json")
if os.path.exists(cj):
rounds = [json.loads(l) for l in open(os.path.join(arm_dir, name, "proxy", "rounds.jsonl")) if l.strip()]
ok = sum(1 for r in rounds if str(r.get("path", "")).endswith("/responses") and r.get("outcome") == "ok" and r.get("status") == 200)
cells.append((json.load(open(cj)).get("start_utc"), name, ok))
cells.sort()
first = 1
for _, name, ok in cells:
if name == cell_name:
return first, ok
first += ok
raise SystemExit("cell %s not found in %s" % (cell_name, arm_dir))
def main(argv):
cap, out = argv[0], argv[1]
opt = lambda name, d: int(argv[argv.index(name) + 1]) if name in argv else d
first, count, step, max_reply = opt("--first", 1), opt("--count", 10**9), opt("--step", 1), opt("--max-reply", 400)
if "--cell" in argv: # --cell ARM_DIR CELL_NAME
i = argv.index("--cell")
first, count = cell_range(argv[i + 1], argv[i + 2])
print("cell", argv[i + 2], "-> capture requests", first, "..", first + count - 1)
files = sorted(glob.glob(os.path.join(cap, "req-*.json")))
os.makedirs(out, exist_ok=True)
capdir = os.path.join(out, "cap-s3")
os.makedirs(capdir, exist_ok=True)
meta, k = [], 0
for idx in range(first - 1, len(files), step):
if k >= count:
break
doc = json.load(open(files[idx]))
prompt, reply = [int(x) for x in doc["prompt_ids"]], [int(x) for x in doc["generated_ids"]][:max_reply]
turn_at = max((i for i, t in enumerate(prompt) if t == IM_START), default=-1)
if turn_at < 0 or len(prompt) - turn_at != 5 or not reply:
print("skip request", idx + 1, "header", len(prompt) - turn_at, "reply", len(reply))
continue
k += 1
open(os.path.join(out, f"p{k}.ids"), "w").write(",".join(map(str, prompt)))
open(os.path.join(out, f"r_port{k}.ids"), "w").write(",".join(map(str, reply)))
meta.append({"k": k, "prompt_len": len(prompt), "reply_len": len(reply), "turn_at": turn_at, "header_len": 5, "source_file": os.path.basename(files[idx])})
json.dump({"index": k, "source": "port", "k": k, "max_new": len(reply), "temperature_milli": 0, "prompt_tokens": len(prompt), "prompt_ids": prompt, "generated_ids": reply,
"top_p_micro": None, "top_k": None, "min_p_micro": None, "repetition_penalty_micro": None, "frequency_penalty_micro": None, "presence_penalty_micro": None,
"penalty_last_n": None, "seed": None, "reused": 0, "rounds": 0, "produced": len(reply)}, open(os.path.join(capdir, "req-%06d.json" % k), "w"))
json.dump({"capture": os.path.abspath(cap), "requests": meta}, open(os.path.join(out, "meta.json"), "w"), indent=1)
print(len(meta), "requests; prompt lengths", [m["prompt_len"] for m in meta], "reply lengths", [m["reply_len"] for m in meta])
if __name__ == "__main__":
main(sys.argv[1:])
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Per-arm, per-request restore and timing lines of a port replay log (q245_port.sh): reused / re-prefilled tokens, TTFT, decode, tokens per round.
Offline; no runtime use. The arms of one process run the same requests in the same order on the same loaded model, which makes their TTFT a paired comparison
(the first request of each arm meets an empty cache).
usage: q245_ttft.py LOG [LOG ...]
"""
import re, sys
for path in sys.argv[1:]:
arm, rows = None, {}
for line in open(path, errors="replace"):
m = re.search(r"REPLAY-ARM start label=(\S+) mode=(\S+)", line)
if m:
arm = m.group(1)
rows[arm] = []
continue
m = re.match(r"REPLAY #(\d+) pass=\d+ \S+ arm=\S+ file=(\S+) prompt=(\d+) reused=(\d+) reprefill=(\d+) ttft_ms=([\d.]+) produced=(\d+) rounds=(\d+) tok_per_round=([\d.]+) decode_ms=([\d.]+) decode_tok_s=([\d.]+)", line)
if m and arm:
rows[arm].append(tuple(float(x) if "." in x else int(x) for x in m.groups()[2:]) + (m.group(2),))
print(path)
for arm, rs in rows.items():
if not rs:
continue
print(f" arm {arm}: requests {len(rs)} re-prefilled tokens {sum(r[2] for r in rs)} sum TTFT {sum(r[3] for r in rs) / 1000:.1f} s median TTFT {sorted(r[3] for r in rs)[len(rs) // 2] / 1000:.2f} s tokens/round {sum(r[4] for r in rs) / max(1, sum(r[5] for r in rs)):.2f}")
print(" per request (prompt, reused, re-prefilled, ttft_ms): " + "; ".join(f"{r[0]}/{r[1]}/{r[2]}/{r[3]:.0f}" for r in rs))
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# A holder-free window for q245_orig_job.sh, started DETACHED by a queue stub that has touched jobs/STOP and closed the holder's descriptor (the mechanism of
# the single-copy and service-validation windows): q245_window.sh LABEL (environment Q_RUNS is passed through)
# 1. waits until the lab holder has ended and its memfd is gone; 2. runs q245_orig_job.sh; 3. ALWAYS restarts the lab holder afterwards
# (single-copy-holder.sh, the O_DIRECT seal), so the queue goes on, whatever happened.
set -u
LABEL=${1:-window}
Q=/data/leleka-e2e/quality-245k
H=$HOME/work/gpu-runs/holder2
NOTES=/data/leleka-e2e/decode/notes.md
note() { echo "[$(date -u +%FT%TZ)] [DEV quality-245k] $*" >> "$NOTES"; }
restart_holder() {
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then echo "a holder is already running"; return; fi
rmdir "$HOME/work/gpu-runs/MODEL.lock" 2>/dev/null # ours, if the payload died holding it
rm -f "$H/jobs/STOP" "$H/jobs/READY"
( cd "$H" && setsid nohup bash /data/leleka-e2e/single-copy/tools/single-copy-holder.sh > "$H/holder3.out" 2>&1 < /dev/null & )
note "window $LABEL over: holder restarted with single-copy-holder.sh (holder3.out); queue open again"
}
trap restart_holder EXIT
note "window $LABEL: waiting for the holder to end (jobs/STOP is set), then ${Q_PAYLOAD:-q245_orig_job.sh}: ${Q_RUNS:-${QC_MODE:-}}"
for _ in $(seq 1 1440); do
if ! pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null && [ ! -d "$HOME/work/gpu-runs/MODEL.lock" ]; then break; fi
sleep 5
done
if pgrep -u "$USER" -f 'kar_holder2?\.py|single-copy-holder\.py' >/dev/null; then note "window $LABEL: the holder did not end in 2 h, giving up (holder left as it is)"; trap - EXIT; exit 3; fi
sleep 5
note "window $LABEL: holder gone, MemAvailable $(awk '/^MemAvailable:/{printf "%d GiB", $2/1048576}' /proc/meminfo); starting"
PAYLOAD=${Q_PAYLOAD:-q245_orig_job.sh}
bash "$Q/tools/$PAYLOAD" > "$Q/window-$LABEL.out" 2>&1
note "window $LABEL: $PAYLOAD ended rc=$?; log $Q/window-$LABEL.out"