Merge claude/codex-lossy-delta: four-variant Codex lossy-delta harness (tasks, logging proxy, index) and results record; 72-cell matrix done, ours lossy vs lossless +0.6% rounds (n=3, resolution ~35%), vanilla early-stop confound documented

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-31 17:52:17 +01:00
co-authored by Claude Sonnet 5.5
262 changed files with 22093 additions and 0 deletions
+4
View File
@@ -3,3 +3,7 @@
# and skips binary-looking files; it only stops CRLF from entering LF files at commit time.
crates/**/*.rs text=auto eol=lf
scripts/gpu-bringup/**/*.py text=auto eol=lf
# Codex lossy-delta study: task files are hashed byte for byte (no EOL conversion); the runner scripts are LF.
scripts/e2e/codex/tasks/** -text
scripts/e2e/codex/delta/** text eol=lf
+93
View File
@@ -0,0 +1,93 @@
# Codex lossy-vs-lossless delta study (vanilla Strata 0.2.6 and our port, RTX 5090)
Branch `claude/codex-lossy-delta` (from main `e1bd61f5`). Question of the owner: with the real Codex CLI on realistic tasks, how much worse is the
lossy mode (route tail skip) than the lossless one, for vanilla and for our port. The orchestrator judges the DELTA by re-reading the sessions:
"small" = the task still completes with less than 5 % extra agent rounds (rounds = model requests), "large" = 5 % or more extra rounds, or the
task fails where the lossless variant completes it. This page fixes the design; it contains no result. Numbers go to `runs/codex-lossy-delta/_index/`.
## 1. Variants (same machine `rnr5090`, RTX 5090, 256k context, same model files, Codex CLI 0.163.0 sha256 `399ff69c...c4215`)
| id | stack | setting | check before the first cell |
| --- | --- | --- | --- |
| V1 | vanilla Strata 0.2.6 (launcher `~/work/vanilla-strata/control`, engine 0.1.50 `ae49d5da...4776`, `launch --model iq3_s --context 256k --kv int8 --vision off --parallel 1 --tune skip`) | shipped defaults: `STRATA_ROUTE_TAIL_SKIP=7` ON by default, `STRATA_PREFILL_CPU_SHARE=auto` | engine.log has `STRATA_ROUTE_TAIL_SKIP=7 is ON (default)` (block.py stops the block otherwise) |
| V2 | same vanilla | `STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0` (both lossy defaults off, recorded in `stack.json`) | no `is ON` line; no `CPU share` line |
| V3 | our port, binaries `bin-main` = main `e1bd61f5` built in WSL (sha256 in `bin-main/COMMIT.txt`), `rtx5090-32g` profile shape (expert slots auto, GPU budget 32,819,404,800, spec-min-p 0, prefix cache auto/reply/8192, chain kernels, prompt-routing seed OFF, MTP draft vocabulary, ranked upstream expert profile `8f59b4aa...`) | `LELEKA_ROUTE_TAIL_SKIP=7` (EXPERIMENTAL, changes the output) | engine log (first decode) has `EXPERIMENTAL route tail skip is ON` |
| V4 | same binaries and shape | skip off (main default) | no such line |
Vanilla runs untraced (no `STRATA_DECODE_TIMING`), ours with `LELEKA_SERVE_PROFILE=1` only (the per-request `expert tier ... route tail skip` line carries our skip counters). The ours shape is the one of the paired A/B jobs
(`decode/dt/jobs/speedtrain3-ab.sh`, `ours()`), run through the same `run-e2e.sh` as the earlier Codex jobs 943d/945d (copy in `run-e2e/`, state dir `codex-lossy-delta/w`).
Sampling: Codex sends none. Vanilla would then use the model card's sampling (thinking: T 1.0, top_p 0.95, top_k 20) and ours is greedy. The logging proxy therefore
injects `"temperature": 0` into every `/v1/responses` request for ALL variants (greedy on both; recorded per request in `proxy/rounds.jsonl` as `fwd_sampling`). The proxy also maps the model name Codex sees (`qwen-local`,
identical in every variant, so Codex builds identical requests) to the engine's own id. The adaptive expert tier and the prefix cache are not bit-exact run to run, so greedy does not mean reproducible (measured by the pilot).
## 2. What is captured, identically for the four stacks
`scripts/e2e/codex/delta/logproxy.py` sits between Codex and the Responses endpoint of either stack. Per cell it writes `proxy/rounds.jsonl` (one line per HTTP request: timings, sizes, sha256, usage, output item summary) and, gzip-ed, every request body exactly as Codex
sent it, the forwarded body when the proxy changed it, and every response body exactly as received (`rounds/NNNN.{req.json,fwd.json,resp.sse}.gz`). Beside it: Codex's own rollout
(`codex-home/sessions/**/rollout-*.jsonl`), `codex-events.jsonl` (`codex exec --json` with arrival times), `codex.err`, the engine-log slice of the cell (`engine-slice.log`), the final workspace, `acceptance.log`, `cell.json`. The block directory
`V?/_stack-<tag>/` holds `inference.log` or `engine.log`, `strata-next.log`, `stack.json` (versions, env, warm-up, skip-state check, uptime, boot id), `mon.csv` (GPU temperature, clocks, power every 10 s), `memsample.txt`.
`delta/index.py` renders every session into `transcript.md` (round by round: new tool outputs, reasoning, calls, messages) and builds `_index/{index.csv,rounds.csv,index.md}`.
Round = one POST `/responses` (counted by the proxy, retries and failed attempts included; completed and failed ones are listed separately). Codex's own tool-call count is in the index too.
## 3. Tasks (`scripts/e2e/codex/tasks/`, frozen with `MANIFEST.sha256`, read-only on the server)
| id | kind | what the agent does | acceptance (`accept.py`, exit 0 = done) | author's round estimate |
| --- | --- | --- | --- | --- |
| ttt | create | Three.js tic-tac-toe in one file (prompt of jobs 943*, unchanged) | STATIC checks on the server (file, relative import of the vendored three, WebGL renderer, raycaster, `#status`, `#restart`, win/draw logic, no network). The six real-click browser checks (`hidden/check_ttt.mjs`) need Node + Playwright, which the server lacks: run later over the stored workspaces and reported separately | 15-60 |
| crm | create | CRM web app, two phases (prompt of jobs 945*, unchanged) | 21 REST checks + the app's own tests (`hidden/crm_acceptance.py` on a copy) | 60-110 |
| fixbug-ledger | bugfix | 6 seeded bugs in a 12-module bookkeeping library, 133 tests, 13 fail | pristine tests untouched and green + 34 hidden behaviour tests | 15-40 |
| feature-query | feature | implement the `where` query language of `SPEC.md` for a small table store, CLI flag, tests, README | existing tests, ~250 hidden spec cases, the agent's >= 25 tests pass, README | 20-45 |
| refactor-shop | refactor | 8-step refactor of a 22-module legacy shop library by `REFACTOR.md`, 119 tests stay green | pristine tests (with the `Cust` rename) + 26 static and behaviour checks | 35-60 |
| debuglog-sched | debug | find the id-reuse bug of a job scheduler from a 4,730-line (417 KB) log, fix, regression test, `FINDINGS.md` | visible + regression tests, two hidden stress simulations (zero lost jobs), `FINDINGS.md` content | 20-50 |
| smoke-mini | bugfix | 2 bugs in a 120-line package; pipeline smoke only, not in the matrix | pristine tests + hidden cases | 6-14 |
Every task has an exact prompt (between the marker lines of `task.md`), a seed workspace (copied byte for byte, digest `SEEDTREE` in the manifest, checked by `cell.py` before Codex starts), an acceptance script that does not know the variant, hidden files that never enter the workspace, and a reference
solution used only by `tasks/selftest.py` (acceptance FAILS on the bare seed and PASSES on seed + reference; verified for all 7 on Python 3.9 and 3.12, and it never modifies the workspace). The reference solutions are NOT installed on the server. The workspace Codex works in lives in
`codex-lossy-delta/_active/ws`, away from earlier results, and is moved into the cell afterwards. The Codex sandbox is `workspace-write` without network (`approval_policy = never`), as in the earlier jobs; it can still read the file system, which is a residual risk shared by all variants.
The Rust-crate idea of the owner's list was replaced by Python (the server has no Rust toolchain and the agent could not build); `gcc`/`make` exist but no C task was written.
Limits, identical for all variants and cells: wall limit 2,400 s per cell, cap 150 model requests (the proxy answers 503 beyond it and the runner stops Codex; the cell is recorded as `round_cap`), Codex `model_reasoning_effort = medium`, `model_context_window = 262144`.
A cell that hits a limit counts as not completed, its rounds are the rounds it used.
## 4. Order, repeats and the stack life
One block = one stack start of one variant (model load: ours about 7-8 min, vanilla about 4-5 min) followed by several cells, so a cell does not pay a load. The engine therefore carries its expert-tier history and its prefix cache from one cell to the next
(Codex's first ~9k tokens are common to all tasks); this is identical for the four variants but means cells are not independent. The warm-up request before the first cell is the same for all.
Block order per repetition is a small balanced design that keeps the lossy/lossless pair of an engine adjacent and alternates which comes first: rep 1 V1 V2 V3 V4, rep 2 V2 V1 V4 V3, rep 3 V3 V4 V1 V2, rep 4 V4 V3 V2 V1; the task order inside a block rotates with the repetition.
Server drift (vanilla was 13.5-16 ms/round at uptime 11-13 h on 2026-10-29 and 10.1-11.7 ms/round after fresh boots) is recorded per block (`uptime_s_at_block`, `boot_id`, GPU clocks), not removed.
## 5. GPU-hour estimate and the cut
Per cell (lossless, 130 tok/s): ttt 4-15 min (943d: 203 s), crm 15-25 min (945d: 871 s), the four new tasks 6-20 min each (author estimates, unmeasured on this model). Per block: model load 5-8 min, shutdown 1 min, warm-up 1 min.
| design | blocks | cell time per block | total |
| --- | --- | --- | --- |
| full: 6 tasks x 3 repeats x 4 variants | 12 | 65-130 min | 14-27 GPU-h |
| pilot + smoke (queued first): smoke-mini x1 + fixbug-ledger x2 per variant | 4 | 20-30 min | about 2 GPU-h |
The full design exceeds the 10 h budget, so the matrix is cut AFTER the pilot, from measured cell times, by this rule: keep every task but give each cell the n that fits 8 GPU-h (pilot excluded): first drop CRM to n=1 per variant, then the long tasks to n=2, never below n=3 for the
short tasks (fixbug-ledger, ttt, feature-query) unless the pilot shows bit-identical repeats. What was cut is stated in the second report.
## 6. What delta the data can resolve
A 5 % difference of the mean round count is not resolvable with 2-3 repeats of agent sessions unless the sessions are reproducible. The index prints the measured run-to-run CV of the round count (same variant, same task) and the relative difference two cell means of n repeats can resolve
(`2.8 * CV * sqrt(2/n)`, two-sided alpha 0.05, power 0.8). With a CV of 25 % that is about 57 % at n=3 for one task, about 23 % when the six tasks are pooled; with sessions that repeat exactly the per-cell delta is exact but is a statement about one trajectory. The index therefore reports, for each task, the lossy
and lossless round counts of every repeat, the paired difference by repeat, the completion counts, and the first round where the lossy and lossless sessions differ (with transcript line numbers), so the orchestrator can read both the numbers and the sessions. No quality verdict is computed.
## 7. How to run and read
```sh
bash scripts/e2e/codex/delta/install.sh # laptop: freeze + check + install on the server (read-only), nothing is hard-deleted
# server: stub ~/work/gpu-runs/holder2/jobs/<name>.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/<name>.sh`, add <name> to jobs/PRIORITY
python3 -I ~/work/leleka/codex-lossy-delta/delta/index.py ~/work/leleka/runs/codex-lossy-delta # index.csv, rounds.csv, index.md, transcripts
```
Layout: `~/work/leleka/runs/codex-lossy-delta/<V1..V4>/<task>-r<k>/` (matrix cells), `_smoke/V?/...` (smoke), `V?/_stack-<tag>/` (stack logs), `_index/`. Incomplete cells are renamed `*.incomplete-<time>`, never deleted.
## 8. Execution record (2026-10-31)
Measured cell times were far below the pre-pilot estimate (fixbug-ledger 1.5-3 min, crm 5-20 min), so nothing was cut: 6 tasks x 3 repeats x 4 variants = 72 matrix cells, about 5.1 GPU-h for the three matrix jobs plus about 1 GPU-h of pilots (`_pilot0` superseded, `_smoke`, pilot2 = repeats 1-2 of fixbug-ledger).
Changes made after the first pilot, all recorded in git: fixed CODEX_HOME path while Codex runs and a fixed prompt `<current_date>` (the per-cell path made prompts differ, so the first pilot is not comparable), acceptance run from a writable copy of the task files (the read-only install broke refactor-shop and feature-query
verdicts; every stored cell was re-accepted with `delta/reaccept.py`, previous logs kept as `acceptance.log.prev`). Index: `runs/codex-lossy-delta/_index/{index.md,index.csv,rounds.csv}`, transcripts in each cell directory.
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Run a list of cells inside ONE running stack (test tooling, stdlib only). Called by block.sh, once the stack is up.
block.py --variant V3 --tag TAG --cells "fixbug-ledger:1 fixbug-ledger:2 smoke-mini:1:_smoke" --runs-root R --tasks-root T
--upstream http://127.0.0.1:8081 --model qwen-iq3|auto --engine-log PATH --expect-skip on|off --stack-dir D
--codex-bin C --wall-limit 2400 --max-rounds 150
A cell token is `task:rep[:set]`; the cell directory is R/[set/]VARIANT/task-rREP. Cells that already hold a cell.json are skipped.
Before the first cell it sends one warm-up request straight to the engine (not part of any cell) and checks that the route tail skip
state the variant is supposed to have is what the engine log says; if not it stops without running a cell.
"""
import argparse
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
SKIP_ON = re.compile(r"ROUTE_TAIL_SKIP=\d+ is ON|EXPERIMENTAL route tail skip is ON")
SKIP_OFF_OURS = re.compile(r"route tail skip \d+ is OFF")
def post(url, body, key, timeout=900):
req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read()
def read_log(path):
try:
return open(path, "r", errors="replace").read()
except OSError:
return ""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--variant", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--cells", required=True)
ap.add_argument("--runs-root", required=True)
ap.add_argument("--tasks-root", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--model", default="auto")
ap.add_argument("--engine-log", required=True)
ap.add_argument("--expect-skip", choices=["on", "off"], required=True)
ap.add_argument("--stack-dir", required=True)
ap.add_argument("--codex-bin", required=True)
ap.add_argument("--wall-limit", type=int, default=2400)
ap.add_argument("--max-rounds", type=int, default=150)
ap.add_argument("--active-dir", required=True)
a = ap.parse_args()
key = os.environ.get("E2E_API_KEY", "none")
model = a.model
if model == "auto":
with urllib.request.urlopen(urllib.request.Request(a.upstream + "/v1/models", headers={"Authorization": "Bearer " + key}), timeout=60) as r:
model = json.loads(r.read())["data"][0]["id"]
blog = open(os.path.join(a.stack_dir, "block.log"), "a", buffering=1)
def say(msg):
line = "%s %s" % (time.strftime("%H:%M:%SZ", time.gmtime()), msg)
print(line, flush=True)
blog.write(line + "\n")
# --- warm-up (graph capture, first-request costs), identical for every variant
t0 = time.time()
body = {"model": model, "input": [{"role": "user", "content": [{"type": "input_text", "text": "Reply with the single word OK."}]}],
"max_output_tokens": 48, "temperature": 0, "stream": False}
try:
st, raw = post(a.upstream + "/v1/responses", body, key)
warm = {"status": st, "seconds": round(time.time() - t0, 1), "reply_bytes": len(raw)}
except Exception as e: # noqa: BLE001
warm = {"status": "error", "error": str(e)[:300]}
say("warm-up: %s" % json.dumps(warm))
time.sleep(2)
log = read_log(a.engine_log)
on_lines = [l for l in log.splitlines() if SKIP_ON.search(l)]
off_lines = [l for l in log.splitlines() if SKIP_OFF_OURS.search(l)]
skip_state = {"expect": a.expect_skip, "on_lines": on_lines[:3], "off_lines": off_lines[:3],
"prefill_cpu_share_lines": [l.strip()[:300] for l in log.splitlines() if "CPU share" in l][:3]}
ok = bool(on_lines) if a.expect_skip == "on" else not on_lines
say("route tail skip check expect=%s: %s" % (a.expect_skip, "OK" if ok else "MISMATCH"))
for l in (on_lines + off_lines)[:3]:
say(" engine log: " + l.strip()[:300])
stack = {}
sp = os.path.join(a.stack_dir, "stack.json")
if os.path.exists(sp):
stack = json.load(open(sp))
stack.update({"variant": a.variant, "tag": a.tag, "upstream_model": model, "warmup": warm, "skip_state": skip_state,
"engine_log": a.engine_log, "block_start_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"uptime_s_at_block": float(open("/proc/uptime").read().split()[0]),
"boot_id": open("/proc/sys/kernel/random/boot_id").read().strip()})
json.dump(stack, open(sp, "w"), indent=1)
if not ok:
say("STOP: the engine log does not show the expected route tail skip state; no cell is run")
open(os.path.join(a.stack_dir, "BLOCK_FAILED"), "w").write("route tail skip state mismatch\n")
return 5
import hashlib
h = hashlib.sha256()
with open(a.codex_bin, "rb") as f:
for chunk in iter(lambda: f.read(1 << 22), b""):
h.update(chunk)
codex_sha = h.hexdigest()
for tok in a.cells.split():
parts = tok.split(":")
task, rep = parts[0], int(parts[1])
sset = parts[2] if len(parts) > 2 else ""
cell_dir = os.path.join(a.runs_root, sset, a.variant, "%s-r%d" % (task, rep))
if os.path.exists(os.path.join(cell_dir, "cell.json")):
say("skip %s (done)" % cell_dir)
continue
if os.path.exists(cell_dir):
garbage = cell_dir + ".incomplete-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime())
os.rename(cell_dir, garbage)
say("renamed an incomplete cell to %s" % garbage)
os.makedirs(os.path.dirname(cell_dir), exist_ok=True)
for leftover in ("ws", "codex-home"):
left = os.path.join(a.active_dir, leftover)
if os.path.exists(left):
moved = os.path.join(a.runs_root, "_incomplete-%s-%s" % (leftover, time.strftime("%Y%m%dT%H%M%S", time.gmtime())))
os.rename(left, moved)
say("moved a leftover active %s to %s" % (leftover, moved))
say("cell %s" % cell_dir)
cmd = [sys.executable, "-I", os.path.join(HERE, "cell.py"), "--cell-dir", cell_dir, "--variant", a.variant, "--task", task, "--rep", str(rep),
"--tasks-root", a.tasks_root, "--upstream", a.upstream, "--upstream-model", model, "--codex-bin", a.codex_bin, "--codex-sha256", codex_sha,
"--wall-limit", str(a.wall_limit), "--max-rounds", str(a.max_rounds), "--engine-log", a.engine_log, "--stack-meta", sp, "--active-dir", a.active_dir]
r = subprocess.run(cmd, capture_output=True, text=True)
say("cell done rc=%d %s %s" % (r.returncode, r.stdout.strip()[-300:], r.stderr.strip()[-300:]))
time.sleep(5)
return 0
if __name__ == "__main__":
sys.exit(main())
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env bash
# One block of the Codex lossy-delta study: start the stack of ONE variant, run a list of cells in it, stop the stack. HOLDER JOB part (ours variants
# need the sealed KAR memfd of the holder; run it from a stub in ~/work/gpu-runs/holder2/jobs/, see delta/jobs/). Test tooling, never in production.
#
# block.sh VARIANT TAG "task:rep[:set] task:rep ..."
#
# V1 vanilla Strata 0.2.6, shipped defaults (route tail skip 7 ON by default, STRATA_PREFILL_CPU_SHARE=auto)
# V2 vanilla Strata 0.2.6, STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 (both lossy defaults off)
# V3 our port (binaries bin-main), shipped profile shape, LELEKA_ROUTE_TAIL_SKIP=7 (EXPERIMENTAL, output changes)
# V4 our port (binaries bin-main), shipped profile shape, route tail skip off (default)
#
# Same machine, same 256k context, same model files, same Codex CLI, same logging proxy (temperature 0 injected for all).
# Takes /data/leleka-e2e/gpu.lock for the whole block (the protocol of the other jobs), waits up to 90 minutes for it.
set -uo pipefail
V=${1:?variant V1..V4}; TAG=${2:?tag}; CELLS=${3:?cells}
ROOT=${CLD_ROOT:-/data/leleka-e2e/codex-lossy-delta}
RUNS=${CLD_RUNS:-/data/leleka-e2e/runs/codex-lossy-delta}
DELTA=$ROOT/delta; TASKS=$ROOT/tasks
CODEX=${CLD_CODEX:-/home/para/work/codex-e2e/bin/codex}
LOCK=/data/leleka-e2e/gpu.lock
WALL=${CLD_WALL_LIMIT:-2400}; CAP=${CLD_MAX_ROUNDS:-150}
A=/home/para/work/leleka/models/leleka-gates/assets
STACK=$RUNS/$V/_stack-$TAG
mkdir -p "$STACK"
log() { echo "[block $V $TAG $(date -u +%T)] $*" | tee -a "$STACK/block.sh.log"; }
# ---- guards -----------------------------------------------------------------------------------------------------
[ "$(df --output=avail -B1G /data | tail -1 | tr -d ' ')" -ge 20 ] || { log "refusing: less than 20 GB free on /data"; exit 3; }
python3 -I "$DELTA/taskfile.py" check "$TASKS" >"$STACK/tasks-check.txt" 2>&1 || { log "refusing: task files differ from MANIFEST.sha256"; cat "$STACK/tasks-check.txt"; exit 3; }
[ -x "$CODEX" ] || { log "no codex binary at $CODEX"; exit 3; }
case $V in V1|V2) KIND=vanilla ;; V3|V4) KIND=ours ;; *) log "unknown variant $V"; exit 2 ;; esac
got=0
for _ in $(seq 1 1080); do
if mkdir "$LOCK" 2>/dev/null; then echo "codex-lossy-delta $V $TAG $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { log "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
MON=; SAMP=
cleanup() {
[ -n "$MON" ] && kill "$MON" 2>/dev/null
[ -n "$SAMP" ] && kill "$SAMP" 2>/dev/null
if grep -q "codex-lossy-delta $V $TAG" "$LOCK/owner" 2>/dev/null; then rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; fi
}
trap cleanup EXIT
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then log "GPU busy, giving up"; exit 3; fi
# ---- monitors (small appends only) -----------------------------------------------------------------------------
( while true; do echo "$(date +%T),$(nvidia-smi --query-gpu=temperature.gpu,utilization.gpu,power.draw,clocks.sm,memory.used --format=csv,noheader)" >>"$STACK/mon.csv"; sleep 10; done ) & MON=$!
( while sleep 10; do echo "$(date +%T) $(grep -E "MemAvailable|Shmem:|Dirty" /proc/meminfo | tr -s ' ' | tr '\n' ' ') $(head -1 /proc/pressure/io) $(head -1 /proc/pressure/memory)"; done >>"$STACK/memsample.txt" 2>/dev/null ) & SAMP=$!
COMMON="--variant $V --tag $TAG --cells \"$CELLS\" --runs-root $RUNS --tasks-root $TASKS --stack-dir $STACK --codex-bin $CODEX --wall-limit $WALL --max-rounds $CAP --active-dir $ROOT/_active"
write_stack_json() {
python3 - "$STACK/stack.json" "$V" "$KIND" <<'PY'
import json, sys, subprocess, os
d = {"variant": sys.argv[2], "kind": sys.argv[3], "host": os.uname().nodename, "kernel": os.uname().release, "env": {}}
for k, v in sorted(os.environ.items()):
if k.startswith(("STRATA_", "LELEKA_")) and "TOKEN" not in k and "KEY" not in k:
d["env"][k] = v
d["gpu"] = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total,clocks.max.sm", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip()
d["codex_version"] = subprocess.run([os.environ.get("CLD_CODEX", "/home/para/work/codex-e2e/bin/codex"), "--version"], capture_output=True, text=True).stdout.strip()
json.dump(d, open(sys.argv[1], "w"), indent=1)
PY
}
if [ "$KIND" = ours ]; then
# ---- our port: the shape of the shipped profile rtx5090-32g.json and of the paired A/B jobs (decode/dt/jobs/speedtrain3-ab.sh), no bring-up tracing
export E2E_BIN=$ROOT/bin-main E2E_OUT=$STACK
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=32819404800
export E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"
export E2E_SAMPLE_S=10 LELEKA_CHAIN=all LELEKA_ORIGINAL_SERVE_SEED=off
unset LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF \
LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_DRAFT_VOCAB \
LELEKA_BRINGUP_TRACE LELEKA_PREFIX_TRACE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED
if [ "$V" = V3 ]; then export LELEKA_ROUTE_TAIL_SKIP=7; EXPECT=on; else EXPECT=off; fi
write_stack_json
{ echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime
sha256sum "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next "$A/data/expert-profile.bin"
cat "$ROOT/bin-main/COMMIT.txt" 2>/dev/null
env | grep -E '^(LELEKA_|STRATA_|E2E_)' | grep -v -E 'TOKEN|KEY' | sort; } >"$STACK/env-arm.txt"
export CLD_CODEX=$CODEX
export E2E_RUN_CMD="python3 -I $DELTA/block.py $COMMON --upstream http://127.0.0.1:8081 --model qwen-iq3 --engine-log $STACK/inference.log --expect-skip $EXPECT"
bash "$ROOT/run-e2e/run-e2e.sh" 2>&1 | grep -a -v '^$' | cut -c1-300 | tee -a "$STACK/block.sh.log"
RC=${PIPESTATUS[0]}
log "run-e2e rc=$RC"
else
# ---- vanilla Strata 0.2.6 (launcher ~/work/vanilla-strata/control, engine 0.1.50), as in the paired A/B jobs; launcher state redirected into the block directory
export XDG_CONFIG_HOME=$STACK/xdg-config XDG_STATE_HOME=$STACK/xdg-state
mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"
cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/"
unset STRATA_ROUTE_TAIL_SKIP STRATA_PREFILL_CPU_SHARE STRATA_DECODE_TIMING STRATA_VERIFY_PROFILE
if [ "$V" = V2 ]; then export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; EXPECT=off; else EXPECT=on; fi
write_stack_json
S=$HOME/work/vanilla-strata/control/bin/strata
{ echo "variant=$V tag=$TAG"; date -u +%FT%TZ; free -g | sed -n 2p; uptime
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_|LELEKA_)' | sort; } >"$STACK/env-arm.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 >"$STACK/launch.out" 2>&1
echo "launch_rc=$? ready_wall_s=$(( $(date +%s) - T0 ))" >>"$STACK/env-arm.txt"
ENGLOG=$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log
if curl -fs http://127.0.0.1:8090/v1/models >"$STACK/models.json"; then
export CLD_CODEX=$CODEX E2E_API_KEY=none
python3 -I "$DELTA/block.py" --variant "$V" --tag "$TAG" --cells "$CELLS" --runs-root "$RUNS" --tasks-root "$TASKS" --stack-dir "$STACK" --codex-bin "$CODEX" \
--wall-limit "$WALL" --max-rounds "$CAP" --active-dir "$ROOT/_active" --upstream http://127.0.0.1:8090 --model auto --engine-log "$ENGLOG" --expect-skip "$EXPECT" 2>&1 | tee -a "$STACK/block.sh.log"
RC=${PIPESTATUS[0]}
cp "$ENGLOG" "$STACK/engine.log"
else
log "vanilla did not become ready"; RC=6
fi
"$S" launch --stop >>"$STACK/launch.out" 2>&1
sleep 8
log "vanilla block rc=$RC"
fi
date -u +%FT%TZ >"$STACK/block.end"
exit "${RC:-0}"
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Run the six real-click browser checks of check_ttt.mjs over the stored tic-tac-toe workspaces (needs Node + Playwright + Chromium in PLAYWRIGHT_DIR;
# the server has none, so run this on a machine that has them, over a copy of the runs). Prints one line per cell: variant, repeat, checks passed.
#
# PLAYWRIGHT_DIR=/path/with/node_modules bash browser_check_ttt.sh RUNS_ROOT
set -uo pipefail
RUNS=${1:?runs root}
PW=${PLAYWRIGHT_DIR:?directory with node_modules/playwright}
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
CHECK=$HERE/../tasks/ttt/hidden/check_ttt.mjs
for ws in "$RUNS"/V?/ttt-r*/workspace; do
[ -f "$ws/index.html" ] || continue
cell=$(dirname "$ws")
out=$(cd "$PW" && node "$CHECK" "$ws/index.html" 2>&1 | tail -1)
echo "$(basename "$(dirname "$cell")") $(basename "$cell") $out" | tee -a "$RUNS/_index/browser-check-ttt.txt"
done
+277
View File
@@ -0,0 +1,277 @@
#!/usr/bin/env python3
"""Run ONE cell (variant, task, repeat) of the Codex lossy-delta study against an already running stack (test tooling, stdlib only).
cell.py --cell-dir D --variant V1 --task fixbug-ledger --rep 1 --tasks-root TASKS --upstream http://127.0.0.1:8081
--upstream-model qwen-iq3 --codex-bin CODEX --wall-limit 2400 --max-rounds 150 [--engine-log PATH] [--stack-meta FILE]
Refuses to start when the task md / seed / acceptance files differ from MANIFEST.sha256. Writes into D:
workspace/ the final workspace (seed copied byte for byte before the run, then whatever Codex did)
codex-home/ CODEX_HOME of the run: config.toml and sessions/**/rollout-*.jsonl (Codex's own record of the session)
codex-events.jsonl `codex exec --json` events with the wall-clock time they were read (t_unix_ms)
codex.err Codex stderr
proxy/ logproxy output: rounds.jsonl and one gzip file per request and response (every byte Codex sent and received)
engine-slice.log the part of the engine log written during the cell (when --engine-log is given)
acceptance.log, acceptance.rc, workspace.sha256, prompt.txt, cell.json (metadata and outcome)
"""
import argparse
import json
import os
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import taskfile # noqa: E402
def utc():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def copy_tree(src, dst):
"""Copy a tree byte for byte with default (writable) permissions: the task files on the server are read-only."""
os.makedirs(dst, exist_ok=True)
for root, dirs, files in os.walk(src):
rel = os.path.relpath(root, src)
for d in dirs:
os.makedirs(os.path.join(dst, rel, d) if rel != "." else os.path.join(dst, d), exist_ok=True)
for n in files:
shutil.copyfile(os.path.join(root, n), os.path.join(dst, rel, n) if rel != "." else os.path.join(dst, 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"""
acc_dir = os.path.join(scratch, "accept-task")
if os.path.exists(acc_dir):
shutil.rmtree(acc_dir, ignore_errors=True)
os.makedirs(acc_dir)
for n in os.listdir(tdir):
src = os.path.join(tdir, n)
if os.path.isdir(src):
copy_tree(src, os.path.join(acc_dir, n))
else:
shutil.copyfile(src, os.path.join(acc_dir, n))
acc_rc = -1
try:
r = subprocess.run([sys.executable, os.path.join(acc_dir, "accept.py"), ws], capture_output=True, text=True, timeout=900)
acc_rc = r.returncode
open(os.path.join(cell, "acceptance.log"), "w", encoding="utf-8").write(r.stdout + ("\n--- stderr ---\n" + r.stderr if r.stderr.strip() else ""))
except subprocess.TimeoutExpired:
open(os.path.join(cell, "acceptance.log"), "w").write("acceptance timed out\n")
shutil.rmtree(acc_dir, ignore_errors=True)
return acc_rc
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cell-dir", required=True)
ap.add_argument("--variant", required=True)
ap.add_argument("--task", required=True)
ap.add_argument("--rep", type=int, required=True)
ap.add_argument("--tasks-root", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--upstream-model", required=True)
ap.add_argument("--codex-bin", required=True)
ap.add_argument("--codex-sha256", default="")
ap.add_argument("--wall-limit", type=int, default=2400)
ap.add_argument("--max-rounds", type=int, default=150)
ap.add_argument("--effort", default="medium")
ap.add_argument("--temperature", type=float, default=0.0)
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("--active-dir", default="", help="directory in which the workspace lives while Codex runs (moved into the cell afterwards)")
a = ap.parse_args()
cell = os.path.abspath(a.cell_dir)
if os.path.exists(os.path.join(cell, "cell.json")):
print("refusing: %s already holds a finished cell" % cell, file=sys.stderr)
return 3
# --- the task files must be byte-identical to the frozen manifest
problems = taskfile.check(a.tasks_root, [a.task])
if problems:
print("refusing to start: task %s differs from MANIFEST.sha256:\n %s" % (a.task, "\n ".join(problems[:10])), file=sys.stderr)
return 3
meta = taskfile.read_task(a.tasks_root, a.task)
prompt = meta["prompt"]
tdir = os.path.join(a.tasks_root, a.task)
os.makedirs(cell, exist_ok=True)
final_ws = os.path.join(cell, "workspace")
active = os.path.abspath(a.active_dir) if a.active_dir else cell
ws = os.path.join(active, "ws") if a.active_dir else final_ws
if os.path.exists(ws) or os.path.exists(final_ws):
print("refusing: workspace exists", file=sys.stderr)
return 3
os.makedirs(active, exist_ok=True)
seed = os.path.join(tdir, "seed")
if os.path.isdir(seed):
copy_tree(seed, ws)
else:
os.makedirs(ws)
for rel, sha, _n in meta["externals"]:
src = os.path.join(a.tasks_root, "_external", rel)
if not os.path.isfile(src) or taskfile.sha256_file(src) != sha:
print("refusing: external seed file %s missing or differs (%s)" % (rel, src), file=sys.stderr)
shutil.rmtree(ws, ignore_errors=True)
return 3
shutil.copyfile(src, os.path.join(ws, rel))
want = [l for l in open(os.path.join(a.tasks_root, "MANIFEST.sha256")).read().splitlines() if l.startswith("SEEDTREE %s " % a.task)]
have = taskfile.tree_digest(taskfile.workspace_lines(ws))
if not want or want[0].split()[2] != have:
print("refusing: the installed workspace digest %s differs from the manifest (%s)" % (have, want), file=sys.stderr)
shutil.rmtree(ws, ignore_errors=True)
return 3
seed_digest = have
with open(os.path.join(cell, "prompt.txt"), "w", encoding="utf-8", newline="") as f:
f.write(prompt)
# --- Codex home with the config (same template for all variants; the model name Codex sees is fixed)
port = free_port()
# CODEX_HOME lives at a fixed path while Codex runs (its skills text in the prompt contains the path, so a per-cell path would make the prompts differ); moved into the cell afterwards
final_chome = os.path.join(cell, "codex-home")
chome = os.path.join(active, "codex-home") if a.active_dir else final_chome
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)
open(os.path.join(chome, "config.toml"), "w", encoding="utf-8").write(cfg)
# --- logging proxy
pdir = os.path.join(cell, "proxy")
os.makedirs(pdir)
perr = open(os.path.join(cell, "proxy.err"), "w")
proxy = subprocess.Popen([sys.executable, os.path.join(HERE, "logproxy.py"), "--listen", "127.0.0.1:%d" % port, "--upstream", a.upstream,
"--out", pdir, "--temperature", str(a.temperature), "--model-map", "qwen-local=" + a.upstream_model,
"--max-rounds", str(a.max_rounds), "--fix-date", a.fix_date], stdout=perr, stderr=perr)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
break
except OSError:
time.sleep(0.1)
elog_start = os.path.getsize(a.engine_log) if a.engine_log and os.path.exists(a.engine_log) else 0
env = dict(os.environ)
env.update({"CODEX_HOME": chome})
if "E2E_API_KEY" not in env:
env["E2E_API_KEY"] = "none"
cmd = [a.codex_bin, "exec", "--json", "--skip-git-repo-check", "-C", ws, prompt]
t0 = time.time()
start_utc = utc()
events = open(os.path.join(cell, "codex-events.jsonl"), "w", encoding="utf-8", buffering=1)
errf = open(os.path.join(cell, "codex.err"), "w")
p = subprocess.Popen(cmd, cwd=ws, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=errf, start_new_session=True)
final_msg = {"text": ""}
def reader():
for raw in p.stdout:
line = raw.decode("utf-8", errors="replace").rstrip("\n")
tms = int(time.time() * 1000)
try:
d = json.loads(line)
if isinstance(d, dict):
d["t_unix_ms"] = tms
it = d.get("item") or {}
if d.get("type") == "item.completed" and it.get("type") == "agent_message":
final_msg["text"] = it.get("text") or ""
line = json.dumps(d, separators=(",", ":"))
else:
line = json.dumps({"t_unix_ms": tms, "value": d})
except ValueError:
line = json.dumps({"t_unix_ms": tms, "raw": line})
events.write(line + "\n")
th = threading.Thread(target=reader, daemon=True)
th.start()
termination = "exited"
cap_path = os.path.join(pdir, "cap.reached")
while True:
rc = p.poll()
if rc is not None:
break
if time.time() - t0 > a.wall_limit:
termination = "wall_limit"
elif os.path.exists(cap_path):
termination = "round_cap"
if termination != "exited":
try:
os.killpg(p.pid, signal.SIGTERM)
except OSError:
pass
for _ in range(20):
if p.poll() is not None:
break
time.sleep(0.5)
if p.poll() is None:
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
rc = p.wait()
break
time.sleep(0.5)
th.join(timeout=10)
wall = time.time() - t0
end_utc = utc()
events.close()
errf.close()
# a stray child of the agent (a server it started) must not outlive the cell
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
time.sleep(1)
proxy.terminate()
try:
proxy.wait(10)
except subprocess.TimeoutExpired:
proxy.kill()
perr.close()
if a.engine_log and os.path.exists(a.engine_log):
with open(a.engine_log, "rb") as f:
f.seek(elog_start)
data = f.read()
with open(os.path.join(cell, "engine-slice.log"), "wb") as f:
f.write(data)
if ws != final_ws:
shutil.move(ws, final_ws)
ws = final_ws
if chome != final_chome:
shutil.move(chome, final_chome)
# --- objective acceptance (on the final workspace; the script copies it first)
acc_rc = run_acceptance(tdir, ws, cell, a.active_dir or cell)
open(os.path.join(cell, "acceptance.rc"), "w").write("%d\n" % acc_rc)
open(os.path.join(cell, "workspace.sha256"), "w").write("\n".join(taskfile.workspace_lines(ws)) + "\n")
stack = {}
if a.stack_meta and os.path.exists(a.stack_meta):
stack = json.load(open(a.stack_meta))
info = {"variant": a.variant, "task": a.task, "rep": a.rep, "start_utc": start_utc, "end_utc": end_utc, "wall_s": round(wall, 1),
"codex_rc": rc, "termination": termination, "accepted": acc_rc == 0, "acceptance_rc": acc_rc,
"wall_limit_s": a.wall_limit, "max_rounds_cap": a.max_rounds, "effort": a.effort, "temperature_injected": a.temperature, "fixed_date": a.fix_date,
"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}
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"))
print("cell %s %s r%d: codex_rc=%s %s wall=%.0fs accepted=%s" % (a.variant, a.task, a.rep, rc, termination, wall, acc_rc == 0), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Generate the holder job scripts of the matrix (one job per repetition, so the other agents' jobs can run between them).
gen_jobs.py --plan "fixbug-ledger:3,ttt:3,feature-query:3,debuglog-sched:2,refactor-shop:2,crm:1" --out DIR [--order "ttt,crm,fixbug-ledger,..."]
--plan is task:n (n repeats). Repetition k contains every task with n >= k. Variant order per repetition (the lossy/lossless pair of an engine stays adjacent):
rep 1 V1 V2 V3 V4, rep 2 V2 V1 V4 V3, rep 3 V3 V4 V1 V2, rep 4 V4 V3 V2 V1 (then repeating). The task order inside a block is the --order list rotated by (k - 1).
Cells that already exist (the pilot's fixbug-ledger r1 and r2) are skipped by block.py.
"""
import argparse
import os
ROWS = [["V1", "V2", "V3", "V4"], ["V2", "V1", "V4", "V3"], ["V3", "V4", "V1", "V2"], ["V4", "V3", "V2", "V1"]]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--plan", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--order", default="ttt,fixbug-ledger,feature-query,debuglog-sched,refactor-shop,crm")
ap.add_argument("--prefix", default="cld-matrix")
a = ap.parse_args()
plan = {}
for tok in a.plan.split(","):
t, n = tok.split(":")
plan[t] = int(n)
order = [t for t in a.order.split(",") if t in plan]
assert set(order) == set(plan), "every planned task must appear in --order"
os.makedirs(a.out, exist_ok=True)
for k in range(1, max(plan.values()) + 1):
tasks = [t for t in order if plan[t] >= k]
shift = (k - 1) % len(tasks) if tasks else 0
tasks = tasks[shift:] + tasks[:shift]
cells = " ".join("%s:%d" % (t, k) for t in tasks)
name = "%s-r%d" % (a.prefix, k)
body = ["#!/usr/bin/env bash",
"# Generated by delta/gen_jobs.py: repetition %d of the matrix. Stub in ~/work/gpu-runs/holder2/jobs: exec bash <this file>." % k,
"set -uo pipefail",
"B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh",
"for V in %s; do" % " ".join(ROWS[(k - 1) % 4]),
" bash \"$B\" \"$V\" r%d \"%s\"" % (k, cells),
" echo \"=== block $V done rc=$? $(date -u +%FT%TZ)\"",
" sleep 20",
"done", ""]
with open(os.path.join(a.out, name + ".sh"), "w", newline="\n") as f:
f.write("\n".join(body))
print(name, cells)
if __name__ == "__main__":
main()
+464
View File
@@ -0,0 +1,464 @@
#!/usr/bin/env python3
"""Index, transcripts and deltas of the Codex lossy-delta runs (test tooling, stdlib only, Python 3.9+).
index.py RUNS_ROOT [--out DIR] [--no-transcripts]
Reads every cell under RUNS_ROOT (`[set/]V?/<task>-r<k>/cell.json`) and writes into --out (default RUNS_ROOT/_index):
index.csv one row per cell (variant, task, repeat, rounds, accepted, token distributions, wall, tok/s, skip counters, final message tail, paths)
rounds.csv one row per model request (input / cached / output / reasoning tokens, times, status, the actions the model took)
index.md the same as a table, the per-task lossy-minus-lossless round deltas (V1-V2 vanilla, V3-V4 ours, cross deltas), the spread across repeats,
the first point where lossy and lossless sessions diverge, and the greedy-determinism check (same variant, repeat 1 against repeat 2)
and, unless --no-transcripts, CELL/transcript.md: the session in reading order (every round: new tool outputs, the model's reasoning, calls, messages).
It makes NO quality judgement; it only computes numbers and points to where to read.
"""
import csv
import glob
import gzip
import json
import math
import os
import re
import statistics
import sys
LABEL = {"V1": "vanilla lossy", "V2": "vanilla lossless", "V3": "ours lossy", "V4": "ours lossless"}
PAIRS = [("V1", "V2", "vanilla"), ("V3", "V4", "ours")]
CROSS = [("V3", "V1", "lossy: ours minus vanilla"), ("V4", "V2", "lossless: ours minus vanilla")]
# ---------------------------------------------------------------------------------------------------------------- reading
def jl(path):
out = []
try:
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line:
try:
out.append(json.loads(line))
except ValueError:
pass
except OSError:
pass
return out
def gz_json(path):
try:
return json.loads(gzip.open(path, "rb").read().decode("utf-8", errors="replace"))
except (OSError, ValueError):
return None
def gz_text(path):
try:
return gzip.open(path, "rb").read().decode("utf-8", errors="replace")
except OSError:
return ""
def find_cells(root):
cells = []
for cj in sorted(glob.glob(os.path.join(root, "**", "cell.json"), recursive=True)):
d = os.path.dirname(cj)
if "/_index" in d.replace(os.sep, "/"):
continue
rel = os.path.relpath(d, root).replace(os.sep, "/")
parts = rel.split("/")
sset = "/".join(parts[:-2])
cells.append((sset, d, json.load(open(cj))))
return cells
def sse_items(text):
"""Output items (from response.output_item.done) and the terminal response object of an SSE body."""
items, final = [], None
for line in text.splitlines():
if line.startswith("data:"):
try:
d = json.loads(line[5:].strip())
except ValueError:
continue
t = d.get("type")
if t == "response.output_item.done":
items.append(d.get("item") or {})
elif t in ("response.completed", "response.incomplete", "response.failed"):
final = d.get("response") or d
if not items and final:
items = final.get("output") or []
if not items and text.lstrip().startswith("{"):
try:
items = json.loads(text).get("output") or []
except ValueError:
pass
return items, final
def action_of(item):
t = item.get("type")
if t == "function_call":
return "call %s %s" % (item.get("name"), (item.get("arguments") or "").strip())
if t == "message":
txt = "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict))
return "message %s" % txt.strip()
if t == "reasoning":
return None # reasoning text is not an action
return "%s %s" % (t, json.dumps(item, sort_keys=True)[:200])
def item_text(item):
t = item.get("type")
if t == "function_call":
return "CALL %s(%s)" % (item.get("name"), item.get("arguments"))
if t == "message":
return "MESSAGE: " + "".join(c.get("text") or "" for c in item.get("content") or [] if isinstance(c, dict))
if t == "reasoning":
summ = " ".join((s.get("text") or "") for s in item.get("summary") or [] if isinstance(s, dict))
cont = " ".join((s.get("text") or "") for s in item.get("content") or [] if isinstance(s, dict))
enc = len(item.get("encrypted_content") or "")
return "REASONING: %s%s%s" % (summ, cont, (" [encrypted %d bytes]" % enc) if enc else "")
if t == "function_call_output":
out = item.get("output")
return "TOOL OUTPUT (%s): %s" % (item.get("call_id"), out if isinstance(out, str) else json.dumps(out))
if t == "message" or item.get("role"):
c = item.get("content")
if isinstance(c, list):
c = "".join(x.get("text") or "" for x in c if isinstance(x, dict))
return "%s: %s" % (item.get("role"), c)
return json.dumps(item)[:1000]
# ---------------------------------------------------------------------------------------------------------------- one cell
def cell_rounds(d):
return [r for r in jl(os.path.join(d, "proxy", "rounds.jsonl")) if r.get("round")]
def counters(d, info):
"""Route tail skip counters of the cell from the engine log slice (ours: per request lines; vanilla: cumulative lines)."""
out = {"skip_entries": None, "skip_experts": None, "skip_source": ""}
p = os.path.join(d, "engine-slice.log")
try:
text = open(p, errors="replace").read()
except OSError:
return out
if re.search(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text):
# cumulative since the engine start: the value at the start of the cell is the last one logged before it (read from the stack log)
base_e = base_x = 0
stack_log = (info.get("stack") or {}).get("engine_log")
off = info.get("engine_log_start_offset") or 0
if stack_log and os.path.exists(stack_log) and off:
with open(stack_log, "rb") as f:
head = f.read(off).decode("utf-8", errors="replace")
prev = re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", head)
if prev:
base_x, base_e = int(prev[-1][0]), int(prev[-1][1])
last_x, last_e = [(int(a), int(b)) for a, b in re.findall(r"route tail skip: (\d+) missed experts skipped \((\d+) entries\)", text)][-1]
out.update({"skip_entries": last_e - base_e, "skip_experts": last_x - base_x, "skip_source": "vanilla cumulative delta"})
return out
pat = r"expert tier:.*?route tail skip (\d+) entries / (\d+) experts"
ours = re.findall(pat, text)
tiers = re.findall(r"leleka-serve expert tier:", text)
if ours:
# the counters are cumulative since the engine start: last value of the cell minus the last value logged before it
base_e = base_x = 0
stack_log = (info.get("stack") or {}).get("engine_log")
off = info.get("engine_log_start_offset") or 0
if stack_log and os.path.exists(stack_log) and off:
with open(stack_log, "rb") as f:
head = f.read(off).decode("utf-8", errors="replace")
prev = re.findall(pat, head)
if prev:
base_e, base_x = int(prev[-1][0]), int(prev[-1][1])
le, lx = int(ours[-1][0]), int(ours[-1][1])
out.update({"skip_entries": le - base_e, "skip_experts": lx - base_x, "skip_source": "ours cumulative delta (entries, distinct-expert count as logged)"})
elif tiers:
out.update({"skip_entries": 0, "skip_experts": 0, "skip_source": "ours: %d tier lines, none with a tail skip" % len(tiers)})
return out
def pct(xs, p):
if not xs:
return None
xs = sorted(xs)
return xs[min(len(xs) - 1, int(p * len(xs)))]
def summarize(sset, d, info):
rs = cell_rounds(d)
ok = [r for r in rs if (r.get("resp") or {}).get("terminal") == "response.completed"]
inp = [(r.get("resp") or {}).get("input_tokens") for r in rs]
outt = [(r.get("resp") or {}).get("output_tokens") for r in rs]
inp = [x for x in inp if isinstance(x, int)]
outt = [x for x in outt if isinstance(x, int)]
dec_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_first_byte_ms") or r.get("t_end_ms") or 0) for r in ok)
tot_out = sum(outt)
model_ms = sum((r.get("t_end_ms") or 0) - (r.get("t_start_ms") or 0) for r in rs)
events = jl(os.path.join(d, "codex-events.jsonl"))
tool_calls = sum(1 for e in events if e.get("type") == "item.completed" and (e.get("item") or {}).get("type") == "command_execution")
c = counters(d, info)
row = {
"set": sset, "variant": info["variant"], "label": LABEL.get(info["variant"], ""), "task": info["task"], "rep": info["rep"],
"rounds": len(rs), "rounds_completed": len(ok), "rounds_failed": len(rs) - len(ok),
"accepted": "yes" if info.get("accepted") else "no", "termination": info.get("termination"), "codex_rc": info.get("codex_rc"),
"wall_s": info.get("wall_s"), "model_s": round(model_ms / 1000, 1),
"in_tokens_total": sum(inp), "out_tokens_total": tot_out, "ctx_peak": max(inp) if inp else None,
"in_per_round_p50": pct(inp, .5), "in_per_round_p90": pct(inp, .9), "out_per_round_p50": pct(outt, .5), "out_per_round_p90": pct(outt, .9), "out_per_round_max": max(outt) if outt else None,
"cached_tokens_total": sum((r.get("resp") or {}).get("cached_tokens") or 0 for r in rs),
"decode_tok_s": round(tot_out / (dec_ms / 1000), 1) if dec_ms > 0 else None,
"tool_calls": tool_calls, "skip_entries": c["skip_entries"], "skip_experts": c["skip_experts"], "skip_source": c["skip_source"],
"final_message_tail": re.sub(r"\s+", " ", info.get("final_message_tail") or "")[-240:],
"cell_dir": d, "session_log": os.path.join(d, "proxy", "rounds.jsonl"), "transcript": os.path.join(d, "transcript.md"),
"codex_rollout": (glob.glob(os.path.join(d, "codex-home", "sessions", "**", "rollout-*.jsonl"), recursive=True) or [""])[0],
"start_utc": info.get("start_utc"), "uptime_s_at_block": (info.get("stack") or {}).get("uptime_s_at_block"),
}
return row, rs
# ---------------------------------------------------------------------------------------------------------------- transcript
def build_actions(d, rs):
"""Per round: (new input items, output items, terminal). Reads the gzip request / response bodies."""
acts, prev_in, prev_out = [], None, []
for r in rs:
s = "%04d" % r["seq"]
req = gz_json(os.path.join(d, "proxy", "rounds", s + ".req.json.gz")) or {}
inp = req.get("input") if isinstance(req.get("input"), list) else []
items, final = sse_items(gz_text(os.path.join(d, "proxy", "rounds", s + ".resp.sse.gz")))
if prev_in is None:
new = inp
note = "first request"
else:
base = len(prev_in) + len(prev_out)
if len(inp) >= base and inp[:len(prev_in)] == prev_in:
new = inp[base:]
note = ""
else:
new = inp
note = "history was rewritten (retry or compaction): all %d input items shown" % len(inp)
acts.append({"seq": r["seq"], "round": r["round"], "req": req, "new": new, "note": note, "out": items, "final": final, "rec": r})
prev_in, prev_out = inp, items
return acts
def write_transcript(d, acts, info):
lines = []
lines.append("# %s %s r%s (%s)" % (info["variant"], info["task"], info["rep"], LABEL.get(info["variant"], "")))
lines.append("accepted=%s termination=%s wall=%ss rounds=%d" % (info.get("accepted"), info.get("termination"), info.get("wall_s"), len(acts)))
lines.append("")
for a in acts:
rec, u = a["rec"], (a["rec"].get("resp") or {})
lines.append("## round %d (proxy seq %d) status=%s in=%s cached=%s out=%s reasoning=%s t=%s..%s ms" % (
a["round"], a["seq"], rec.get("status"), u.get("input_tokens"), u.get("cached_tokens"), u.get("output_tokens"), u.get("reasoning_tokens"),
rec.get("t_start_ms"), rec.get("t_end_ms")))
if a["note"]:
lines.append("(%s)" % a["note"])
for it in a["new"]:
txt = item_text(it) if isinstance(it, dict) else str(it)
if a["round"] == 1 and isinstance(it, dict) and it.get("role") in ("developer", "system") and len(txt) > 3000:
txt = txt[:600] + " ... [%d chars, cut: see the request file]" % len(txt)
elif len(txt) > 2500:
txt = txt[:2000] + "\n... [%d chars cut: full text in proxy/rounds/%04d.req.json.gz]" % (len(txt), a["seq"])
lines.append("IN " + txt.replace("\n", "\n "))
for it in a["out"]:
lines.append("OUT " + item_text(it).replace("\n", "\n "))
if rec.get("outcome") not in (None, "ok") or u.get("error"):
lines.append("!! outcome=%s error=%s" % (rec.get("outcome"), json.dumps(u.get("error"))[:300]))
lines.append("")
text = "\n".join(lines) + "\n"
p = os.path.join(d, "transcript.md")
with open(p + ".part", "w", encoding="utf-8") as f:
f.write(text)
os.replace(p + ".part", p)
# line numbers of every round's OUT lines, for the divergence report
idx = {}
for n, line in enumerate(text.splitlines(), 1):
m = re.match(r"## round (\d+) ", line)
if m:
idx[int(m.group(1))] = n
return idx
def action_seq(a):
return [x for x in (action_of(i) for i in a["out"]) if x]
def first_divergence(acts_a, acts_b):
"""-> (round, action_a, action_b) of the first round whose actions differ, or None when the common prefix is identical."""
for k in range(min(len(acts_a), len(acts_b))):
sa, sb = action_seq(acts_a[k]), action_seq(acts_b[k])
if sa != sb:
return k + 1, sa, sb
if len(acts_a) != len(acts_b):
k = min(len(acts_a), len(acts_b))
return k + 1, ["(session A ends)"] if len(acts_a) == k else action_seq(acts_a[k]), ["(session B ends)"] if len(acts_b) == k else action_seq(acts_b[k])
return None
# ---------------------------------------------------------------------------------------------------------------- statistics
def mean(xs):
return sum(xs) / len(xs) if xs else float("nan")
def sd(xs):
return statistics.stdev(xs) if len(xs) > 1 else float("nan")
def fmt(x, nd=1):
return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else ("%.*f" % (nd, x))
def rounds_by(rows):
g = {}
for r in rows:
if r["set"] != "":
continue
g.setdefault((r["task"], r["variant"]), []).append(r)
return g
def delta_table(rows, tasks, pairs, title):
g = rounds_by(rows)
out = ["### " + title, "", "| task | A | B | n(A) | n(B) | rounds A (mean, sd, min-max) | rounds B (mean, sd, min-max) | A-B rounds | A/B-1 | completed A | completed B | paired A-B by repeat |", "|---|---|---|---|---|---|---|---|---|---|---|---|"]
allrel = {}
for (a, b, name) in pairs:
for t in tasks:
ra, rb = g.get((t, a), []), g.get((t, b), [])
if not ra or not rb:
continue
xa, xb = [r["rounds"] for r in ra], [r["rounds"] for r in rb]
ca = sum(1 for r in ra if r["accepted"] == "yes")
cb = sum(1 for r in rb if r["accepted"] == "yes")
by_b = {r["rep"]: r["rounds"] for r in rb}
paired = ["r%s:%+d" % (r["rep"], r["rounds"] - by_b[r["rep"]]) for r in ra if r["rep"] in by_b]
rel = mean(xa) / mean(xb) - 1 if mean(xb) else float("nan")
allrel.setdefault(name, []).append(rel)
out.append("| %s | %s | %s | %d | %d | %s, %s, %d-%d | %s, %s, %d-%d | %s | %s | %d/%d | %d/%d | %s |" % (
t, a, b, len(xa), len(xb), fmt(mean(xa)), fmt(sd(xa)), min(xa), max(xa), fmt(mean(xb)), fmt(sd(xb)), min(xb), max(xb),
"%+.1f" % (mean(xa) - mean(xb)), "%+.1f%%" % (100 * rel), ca, len(ra), cb, len(rb), " ".join(paired)))
out.append("")
for name, rels in allrel.items():
rels = [x for x in rels if not math.isnan(x)]
if rels:
out.append("%s: mean of the per-task relative deltas %+.1f%% (sd across tasks %s, %d tasks); the per-task rows above are the evidence, this line is only a summary." % (
name, 100 * mean(rels), fmt(100 * sd(rels)) + "%", len(rels)))
out.append("")
return out
def noise_section(rows, tasks):
g = rounds_by(rows)
cvs = []
out = ["### Run-to-run noise of the round count (same variant, same task, different repeat)", "", "| task | variant | n | rounds | mean | sd | CV |", "|---|---|---|---|---|---|---|"]
for t in tasks:
for v in ("V1", "V2", "V3", "V4"):
rs = g.get((t, v), [])
if len(rs) >= 2:
x = [r["rounds"] for r in rs]
cv = sd(x) / mean(x) if mean(x) else float("nan")
cvs.append(cv)
out.append("| %s | %s | %d | %s | %s | %s | %s |" % (t, v, len(x), " ".join(map(str, x)), fmt(mean(x)), fmt(sd(x)), fmt(100 * cv) + "%"))
out.append("")
cvs = [c for c in cvs if not math.isnan(c)]
if cvs:
cv = math.sqrt(mean([c * c for c in cvs]))
out.append("Pooled CV of rounds across the cells with >= 2 repeats: %.0f%% (%d cells)." % (100 * cv, len(cvs)))
out.append("Resolvable relative difference of two cell means with n repeats each (two-sided alpha 0.05, power 0.8, pooled CV; normal approximation 2.8 * CV * sqrt(2/n)):")
for n in (2, 3, 4, 6, 9, 12):
out.append("- n=%d: about %.0f%%" % (n, 280 * cv * math.sqrt(2.0 / n)))
out.append("")
return out
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
root = os.path.abspath(args[0])
outdir = os.path.abspath(sys.argv[sys.argv.index("--out") + 1]) if "--out" in sys.argv else os.path.join(root, "_index")
do_tr = "--no-transcripts" not in sys.argv
os.makedirs(outdir, exist_ok=True)
rows, per_cell, round_rows = [], {}, []
for sset, d, info in find_cells(root):
row, rs = summarize(sset, d, info)
rows.append(row)
acts = build_actions(d, rs)
if do_tr:
idx = write_transcript(d, acts, info)
else:
idx = {}
per_cell[(sset, info["variant"], info["task"], info["rep"])] = (d, acts, idx, row)
for a in acts:
rec, u = a["rec"], a["rec"].get("resp") or {}
ttft = (rec.get("t_first_byte_ms") or 0) - (rec.get("t_start_ms") or 0)
dec = (rec.get("t_end_ms") or 0) - (rec.get("t_first_byte_ms") or rec.get("t_end_ms") or 0)
round_rows.append({"set": sset, "variant": info["variant"], "task": info["task"], "rep": info["rep"], "round": a["round"], "seq": a["seq"],
"status": rec.get("status"), "terminal": u.get("terminal"), "input_tokens": u.get("input_tokens"), "cached_tokens": u.get("cached_tokens"),
"output_tokens": u.get("output_tokens"), "reasoning_tokens": u.get("reasoning_tokens"), "ttft_ms": ttft, "decode_ms": dec,
"tok_s": round(u["output_tokens"] / (dec / 1000), 1) if u.get("output_tokens") and dec > 0 else None,
"actions": " | ".join(x[:120].replace("\n", " ") for x in action_seq(a))})
rows.sort(key=lambda r: (r["set"], r["task"], r["variant"], r["rep"]))
if rows:
with open(os.path.join(outdir, "index.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
if round_rows:
with open(os.path.join(outdir, "rounds.csv"), "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(round_rows[0].keys()))
w.writeheader()
w.writerows(round_rows)
tasks = sorted(set(r["task"] for r in rows if r["set"] == ""))
md = ["# Codex lossy-delta: index of %d cells" % len(rows), "", "Variants: " + "; ".join("%s = %s" % (k, v) for k, v in LABEL.items()), ""]
md += ["## Cells", "", "| set | variant | task | rep | rounds (ok/failed) | accepted | termination | wall s | ctx peak | in/round p50 | out/round p50 (max) | decode tok/s | skip entries | final message tail | transcript |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in rows:
md.append("| %s | %s | %s | %s | %d (%d/%d) | %s | %s | %s | %s | %s | %s (%s) | %s | %s | %s | %s |" % (
r["set"] or "-", r["variant"], r["task"], r["rep"], r["rounds"], r["rounds_completed"], r["rounds_failed"], r["accepted"], r["termination"], fmt(r["wall_s"], 0),
r["ctx_peak"], r["in_per_round_p50"], r["out_per_round_p50"], r["out_per_round_max"], fmt(r["decode_tok_s"]), r["skip_entries"],
r["final_message_tail"][-100:].replace("|", "/"), r["transcript"]))
md.append("")
md += ["## Round deltas (lossy minus lossless; A-B rows are computed from the cells above, the matrix set only)", ""]
md += delta_table(rows, tasks, PAIRS, "Lossy minus lossless per engine: V1-V2 (vanilla), V3-V4 (ours)")
md += delta_table(rows, tasks, CROSS, "Cross deltas: ours minus vanilla (V3-V1 lossy, V4-V2 lossless)")
md += noise_section(rows, tasks)
md += ["## First divergence of lossy and lossless sessions (same task and repeat; first round whose actions differ)", "",
"Actions = the model's tool calls (name + arguments) and messages of that round; reasoning text is not compared. Lines refer to each cell's transcript.md.", "",
"| task | engine | rep | lossy cell | lossless cell | first differing round | transcript line (lossy / lossless) | lossy action | lossless action |", "|---|---|---|---|---|---|---|---|---|"]
for t in tasks:
for (lossy, lossless, name) in PAIRS:
for key, (d, acts, idx, row) in sorted(per_cell.items()):
sset, v, tt, rep = key
if v != lossy or tt != t or sset != "":
continue
other = per_cell.get((sset, lossless, t, rep))
if not other:
continue
dv = first_divergence(acts, other[1])
if dv is None:
md.append("| %s | %s | %d | %s | %s | none: identical actions in all %d common rounds | - | - | - |" % (t, name, rep, d, other[0], min(len(acts), len(other[1]))))
else:
k, sa, sb = dv
md.append("| %s | %s | %d | %s | %s | %d | %s / %s | %s | %s |" % (t, name, rep, d, other[0], k, idx.get(k, "-"), other[2].get(k, "-"),
(" ; ".join(sa))[:160].replace("|", "/"), (" ; ".join(sb))[:160].replace("|", "/")))
md += ["", "## Determinism check (same variant, same task, repeat i against repeat j; greedy decoding is requested but the adaptive expert tier and the prefix cache state are not bit-exact run to run)", "",
"| variant | task | reps | first differing round | rounds A / B | accepted A / B |", "|---|---|---|---|---|---|"]
by_vt = {}
for key in per_cell:
sset, v, t, rep = key
if sset == "":
by_vt.setdefault((v, t), []).append(rep)
for (v, t), reps in sorted(by_vt.items()):
reps = sorted(reps)
for i in range(len(reps)):
for j in range(i + 1, len(reps)):
a = per_cell[("", v, t, reps[i])] if ("", v, t, reps[i]) in per_cell else None
b = per_cell[("", v, t, reps[j])] if ("", v, t, reps[j]) in per_cell else None
if not a or not b:
continue
dv = first_divergence(a[1], b[1])
md.append("| %s | %s | r%d vs r%d | %s | %d / %d | %s / %s |" % (v, t, reps[i], reps[j], "identical" if dv is None else dv[0], len(a[1]), len(b[1]), a[3]["accepted"], b[3]["accepted"]))
with open(os.path.join(outdir, "index.md"), "w", encoding="utf-8") as f:
f.write("\n".join(md) + "\n")
print("wrote %d cells, %d rounds into %s" % (len(rows), len(round_rows), outdir))
if __name__ == "__main__":
main()
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Install the Codex lossy-delta study on rnr5090 from the laptop worktree (small writes only: scripts and task files, no model data).
#
# bash scripts/e2e/codex/delta/install.sh
#
# Server layout (all inside the work folder ~/work/leleka = /data/leleka-e2e):
# codex-lossy-delta/tasks/ frozen task set (read-only), without reference/ solutions; tasks/_external/ holds the third-party seed file
# codex-lossy-delta/delta/ runner scripts (read-only)
# codex-lossy-delta/run-e2e/ run-e2e.sh (state dir patched to codex-lossy-delta/w) + helpers
# codex-lossy-delta/config.toml.tmpl, INSTALL.sha256
# codex-lossy-delta/bin-main/ our binaries (uploaded separately, see COMMIT.txt)
# 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
E2E_DIR=$(cd "$CODEX_DIR/.." && pwd) # scripts/e2e
python3 "$CODEX_DIR/tasks/freeze.py" >/dev/null
python3 "$HERE/taskfile.py" check "$CODEX_DIR/tasks" >/dev/null
R=work/leleka/codex-lossy-delta
STAGE=$R/_stage
ssh rnr5090 bash -s "$R" <<'REMOTE'
set -euo pipefail
R=$1
mkdir -p "$HOME/$R"; cd "$HOME/$R"
chmod -R u+w tasks delta run-e2e config.toml.tmpl 2>/dev/null || true
if [ -e _stage ]; then G=$HOME/work/leleka/garbage/codex-lossy-delta-stage-$(date -u +%Y%m%dT%H%M%S); mkdir -p "$G"; mv _stage "$G/"; echo "$(date -u +%FT%TZ) codex-lossy-delta: leftover _stage moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt"; fi
mkdir -p _stage/delta _stage/tasks _stage/run-e2e
REMOTE
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 "$E2E_DIR" -cf - run-e2e.sh sample_env.sh status_writer.sh | ssh rnr5090 "tar -xf - -C $STAGE/run-e2e"
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"
sed -i 's|^W=.*|W=/data/leleka-e2e/codex-lossy-delta/w|' run-e2e/run-e2e.sh
grep -n '^W=' run-e2e/run-e2e.sh
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-lossy-delta-prev-$(date -u +%Y%m%dT%H%M%S)
mkdir -p "$G"
for x in delta tasks run-e2e config.toml.tmpl; do [ -e "$x" ] && mv "$x" "$G/"; done
echo "$(date -u +%FT%TZ) codex-lossy-delta: previous install moved to $G" >> "$HOME/work/leleka/garbage/LOG.txt"
mv _stage/delta delta; mv _stage/tasks tasks; mv _stage/run-e2e run-e2e; mv _stage/config.toml.tmpl config.toml.tmpl; rmdir _stage
mkdir -p w _active
chmod -R a-w tasks delta run-e2e config.toml.tmpl
( find tasks delta run-e2e -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
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Generated by delta/gen_jobs.py: repetition 1 of the matrix. Stub in ~/work/gpu-runs/holder2/jobs: exec bash <this file>.
set -uo pipefail
B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh
for V in V1 V2 V3 V4; do
bash "$B" "$V" r1 "ttt:1 fixbug-ledger:1 feature-query:1 debuglog-sched:1 refactor-shop:1 crm:1"
echo "=== block $V done rc=$? $(date -u +%FT%TZ)"
sleep 20
done
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Generated by delta/gen_jobs.py: repetition 2 of the matrix. Stub in ~/work/gpu-runs/holder2/jobs: exec bash <this file>.
set -uo pipefail
B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh
for V in V2 V1 V4 V3; do
bash "$B" "$V" r2 "fixbug-ledger:2 feature-query:2 debuglog-sched:2 refactor-shop:2 crm:2 ttt:2"
echo "=== block $V done rc=$? $(date -u +%FT%TZ)"
sleep 20
done
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Generated by delta/gen_jobs.py: repetition 3 of the matrix. Stub in ~/work/gpu-runs/holder2/jobs: exec bash <this file>.
set -uo pipefail
B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh
for V in V3 V4 V1 V2; do
bash "$B" "$V" r3 "feature-query:3 debuglog-sched:3 refactor-shop:3 crm:3 ttt:3 fixbug-ledger:3"
echo "=== block $V done rc=$? $(date -u +%FT%TZ)"
sleep 20
done
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Holder job: smoke (smoke-mini once) + determinism pilot (fixbug-ledger twice) for the four variants, one stack start per variant.
# The fixbug-ledger cells are matrix cells (repeats 1 and 2 of the study); smoke-mini goes to the set _smoke.
# Install: stub ~/work/gpu-runs/holder2/jobs/cld-pilot.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/cld-pilot.sh`.
set -uo pipefail
B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh
for V in V1 V2 V3 V4; do
bash "$B" "$V" pilot "smoke-mini:1:_smoke fixbug-ledger:1 fixbug-ledger:2"
echo "=== block $V done rc=$? $(date -u +%FT%TZ)"
sleep 20
done
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Holder job (second pilot, after the fixed CODEX_HOME path and date): smoke (smoke-mini once) + determinism pilot2 (fixbug-ledger twice) for the four variants, one stack start per variant.
# The fixbug-ledger cells are matrix cells (repeats 1 and 2 of the study); smoke-mini goes to the set _smoke.
# Install: stub ~/work/gpu-runs/holder2/jobs/cld-pilot2.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/cld-pilot2.sh`.
set -uo pipefail
B=/data/leleka-e2e/codex-lossy-delta/delta/block.sh
for V in V1 V2 V3 V4; do
bash "$B" "$V" pilot2 "smoke-mini:1:_smoke fixbug-ledger:1 fixbug-ledger:2"
echo "=== block $V done rc=$? $(date -u +%FT%TZ)"
sleep 20
done
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env python3
"""Logging reverse proxy between the Codex CLI and a Responses endpoint (test tooling, stdlib only, Python 3.9+).
logproxy.py --listen 127.0.0.1:PORT --upstream http://127.0.0.1:8081 --out DIR
[--temperature 0] [--model-map LOCAL=UPSTREAM] [--max-rounds N] [--fix-date YYYY-MM-DD]
The same proxy sits in front of vanilla Strata and of our stack, so every request and response is captured identically:
DIR/rounds.jsonl one line per HTTP request: seq, path, status, timings (ms since proxy start), sizes, sha256 of the body Codex sent
and of the body forwarded, the sampling fields forwarded, the usage and the output item summary of the response
DIR/rounds/NNNN.req.json.gz the request body exactly as Codex sent it (gzip)
DIR/rounds/NNNN.fwd.json.gz only when the proxy changed the body (temperature injection, model name mapping): the body forwarded
DIR/rounds/NNNN.resp.sse.gz the response body exactly as received from the engine (SSE stream or JSON), gzip
DIR/cap.reached created when more than --max-rounds POST .../responses requests arrived (later ones get a 503, nothing reaches the engine)
Round = a POST whose path ends in /responses (a model request). Authorization is forwarded and never logged.
The injected `temperature` makes the sampling identical for every variant (Codex sends none; vanilla Strata would otherwise use the model card's
sampling, our server greedy).
"""
import argparse
import gzip
import hashlib
import http.client
import json
import os
import re
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "host", "content-length"}
SECRET_HEADERS = {"authorization", "x-api-key", "cookie", "proxy-authorization"}
class State:
def __init__(self, args):
self.args = args
u = urlsplit(args.upstream)
self.up_host, self.up_port = u.hostname, u.port or 80
self.out = args.out
os.makedirs(os.path.join(self.out, "rounds"), exist_ok=True)
self.log = open(os.path.join(self.out, "rounds.jsonl"), "a", encoding="utf-8", buffering=1)
self.lock = threading.Lock()
self.seq = 0
self.rounds = 0
self.t0 = time.time()
self.model_map = dict(m.split("=", 1) for m in args.model_map)
def ms(self):
return int((time.time() - self.t0) * 1000)
def next_seq(self, is_round):
with self.lock:
self.seq += 1
if is_round:
self.rounds += 1
return self.seq, self.rounds
def write(self, rec):
with self.lock:
self.log.write(json.dumps(rec, separators=(",", ":"), ensure_ascii=False) + "\n")
def gz_write(path, data):
tmp = path + ".part"
with open(tmp, "wb") as f:
f.write(gzip.compress(data, 6, mtime=0))
os.replace(tmp, path)
def summarize_sse(body):
"""Usage, status and a short summary of the output items from an SSE body or a JSON body."""
out = {"events": 0}
text = body.decode("utf-8", errors="replace")
final = None
items = []
if text.lstrip().startswith("{"):
try:
final = json.loads(text)
except ValueError:
final = None
else:
ev = None
for line in text.splitlines():
if line.startswith("event:"):
ev = line[6:].strip()
elif line.startswith("data:"):
out["events"] += 1
try:
d = json.loads(line[5:].strip())
except ValueError:
continue
t = d.get("type") or ev
if t in ("response.completed", "response.incomplete", "response.failed"):
final = d.get("response") or d
out["terminal"] = t
elif t == "response.output_item.done":
items.append(d.get("item") or {})
elif t == "error":
out["error"] = d
if final:
out["status"] = final.get("status")
u = final.get("usage") or {}
out["input_tokens"] = u.get("input_tokens")
out["output_tokens"] = u.get("output_tokens")
out["cached_tokens"] = (u.get("input_tokens_details") or {}).get("cached_tokens")
out["reasoning_tokens"] = (u.get("output_tokens_details") or {}).get("reasoning_tokens")
if final.get("error"):
out["error"] = final["error"]
if final.get("incomplete_details"):
out["incomplete"] = final["incomplete_details"]
if not items:
items = final.get("output") or []
summ = []
for it in items:
k = {"type": it.get("type")}
if it.get("type") == "function_call":
k["name"] = it.get("name")
k["arg_bytes"] = len(it.get("arguments") or "")
elif it.get("type") == "message":
k["text_bytes"] = sum(len(c.get("text") or "") for c in it.get("content") or [] if isinstance(c, dict))
summ.append(k)
out["items"] = summ
return out
def summarize_req(body, headers):
out = {"content_encoding": headers.get("content-encoding"), "content_type": headers.get("content-type")}
if headers.get("content-encoding"):
return out
try:
d = json.loads(body)
except ValueError:
out["not_json"] = True
return out
if not isinstance(d, dict):
return out
inp = d.get("input")
out.update({"model": d.get("model"), "stream": d.get("stream"), "n_input_items": len(inp) if isinstance(inp, list) else None,
"n_tools": len(d.get("tools") or []), "previous_response_id": d.get("previous_response_id"),
"temperature": d.get("temperature"), "top_p": d.get("top_p"), "max_output_tokens": d.get("max_output_tokens"),
"reasoning": d.get("reasoning"), "tool_choice": d.get("tool_choice"), "parallel_tool_calls": d.get("parallel_tool_calls"),
"store": d.get("store"), "keys": sorted(d.keys())})
if isinstance(inp, list):
last = inp[-1] if inp else {}
out["last_item_type"] = last.get("type") or last.get("role") if isinstance(last, dict) else None
return out
def make_handler(st):
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "logproxy/1"
def log_message(self, *a):
pass
def _body(self):
if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
data = b""
while True:
size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
if size == 0:
self.rfile.readline()
break
data += self.rfile.read(size)
self.rfile.readline()
return data
n = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(n) if n else b""
def _handle(self):
t_start = st.ms()
body = self._body()
path = self.path
is_round = self.command == "POST" and urlsplit(path).path.endswith("/responses")
seq, rounds = st.next_seq(is_round)
sname = "%04d" % seq
rec = {"seq": seq, "method": self.command, "path": path, "round": rounds if is_round else None, "t_start_ms": t_start,
"req_bytes": len(body), "req_sha256": hashlib.sha256(body).hexdigest(),
"req": summarize_req(body, {k.lower(): v for k, v in self.headers.items()}),
"req_headers": {k: v for k, v in self.headers.items() if k.lower() not in SECRET_HEADERS}}
if body:
gz_write(os.path.join(st.out, "rounds", sname + ".req.json.gz"), body)
if is_round and st.args.max_rounds and rounds > st.args.max_rounds:
open(os.path.join(st.out, "cap.reached"), "w").write("round %d > cap %d\n" % (rounds, st.args.max_rounds))
msg = json.dumps({"error": {"message": "round cap reached", "type": "server_error", "code": "round_cap"}}).encode()
self.send_response(503)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
rec.update({"status": 503, "outcome": "cap", "t_end_ms": st.ms()})
st.write(rec)
return
fwd = body
if is_round and not self.headers.get("Content-Encoding"):
text_body = body.decode("utf-8", errors="replace")
dated = text_body
if st.args.fix_date:
dated = re.sub(r"<current_date>[^<]*</current_date>", "<current_date>%s</current_date>" % st.args.fix_date, text_body)
try:
d = json.loads(dated)
except ValueError:
d = None
if isinstance(d, dict):
changed = dated != text_body
if changed:
rec["date_fixed"] = st.args.fix_date
if st.args.temperature is not None and "temperature" not in d:
d["temperature"] = st.args.temperature
changed = True
if d.get("model") in st.model_map:
d["model"] = st.model_map[d["model"]]
changed = True
if changed:
fwd = json.dumps(d, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
gz_write(os.path.join(st.out, "rounds", sname + ".fwd.json.gz"), fwd)
rec["fwd_sha256"] = hashlib.sha256(fwd).hexdigest()
rec["fwd_sampling"] = {"temperature": d.get("temperature"), "model": d.get("model")}
elif is_round:
rec["fwd_note"] = "body has a Content-Encoding; forwarded unchanged (no temperature injected)"
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
headers["Host"] = "%s:%d" % (st.up_host, st.up_port)
headers["Content-Length"] = str(len(fwd))
resp_buf = bytearray()
t_first = None
outcome = "ok"
conn = http.client.HTTPConnection(st.up_host, st.up_port, timeout=None)
try:
conn.request(self.command, path, body=fwd if (fwd or self.command in ("POST", "PUT")) else None, headers=headers)
resp = conn.getresponse()
rec["status"] = resp.status
rh = {k: v for k, v in resp.getheaders()}
rec["resp_headers"] = {k: v for k, v in rh.items() if k.lower() not in SECRET_HEADERS}
self.send_response(resp.status)
streaming = "text/event-stream" in (rh.get("Content-Type") or rh.get("content-type") or "").lower() or resp.getheader("Content-Length") is None
for k, v in resp.getheaders():
if k.lower() in HOP or k.lower() in ("date", "server"):
continue
self.send_header(k, v)
if streaming:
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
while True:
chunk = resp.read1(65536) if streaming else resp.read(65536)
if not chunk:
break
if t_first is None:
t_first = st.ms()
resp_buf += chunk
if streaming:
self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n")
else:
self.wfile.write(chunk)
self.wfile.flush()
if streaming:
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
outcome = "client_disconnected"
except Exception as e: # upstream failure
outcome = "proxy_error: %s: %s" % (type(e).__name__, e)
if "status" not in rec:
msg = json.dumps({"error": {"message": outcome, "type": "server_error"}}).encode()
try:
self.send_response(502)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
except OSError:
pass
rec["status"] = 502
finally:
conn.close()
rec.update({"t_first_byte_ms": t_first, "t_end_ms": st.ms(), "resp_bytes": len(resp_buf), "outcome": outcome})
if resp_buf:
gz_write(os.path.join(st.out, "rounds", sname + ".resp.sse.gz"), bytes(resp_buf))
rec["resp"] = summarize_sse(bytes(resp_buf))
st.write(rec)
if outcome != "ok":
self.close_connection = True
do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = _handle
return H
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--listen", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--temperature", type=float, default=None)
ap.add_argument("--model-map", action="append", default=[])
ap.add_argument("--max-rounds", type=int, default=0)
ap.add_argument("--fix-date", default="", help="rewrite <current_date>..</current_date> in the prompt (Codex puts the wall-clock date there)")
args = ap.parse_args()
st = State(args)
host, port = args.listen.rsplit(":", 1)
srv = ThreadingHTTPServer((host, int(port)), make_handler(st))
srv.daemon_threads = True
print("logproxy listening on %s -> %s, out %s" % (args.listen, args.upstream, args.out), flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Re-run the acceptance script over stored cells (same bytes of the task files, writable copy), e.g. after an acceptance infrastructure error.
reaccept.py RUNS_ROOT TASKS_ROOT [task ...]
The old acceptance.log / acceptance.rc are kept as *.prev, cell.json gets `accepted`, `acceptance_rc` and `reaccepted_utc`. Prints cells whose verdict changed.
"""
import glob
import json
import os
import shutil
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
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 not taskfile.check(tasks_root), "task files differ from the manifest"
for cj in sorted(glob.glob(os.path.join(runs, "V?", "*-r*", "cell.json"))):
d = os.path.dirname(cj)
info = json.load(open(cj))
if only and 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())})
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 ""))
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Task files of the Codex lossy-delta study: parse task.md, hash trees, manifest (test tooling, stdlib only, Python 3.9+).
taskfile.py prompt TASKS_ROOT ID print the exact prompt text (no trailing newline)
taskfile.py check TASKS_ROOT [ID ...] verify MANIFEST.sha256 against the files; exit 1 on any difference
Manifest lines: `<sha256> <task>/<relpath>` for every file under tasks/<id>/ (sorted), `EXTERNAL <id> <relpath> <sha256> <bytes>`,
`PROMPT <id> <sha256 of the extracted prompt>`, `SEEDTREE <id> <digest>` (digest of the workspace the runner builds: seed/ plus external files)
and `TASK <id> <digest of the task's file lines>`.
"""
import hashlib
import os
import re
import sys
BEGIN = "<!-- PROMPT BEGIN -->"
END = "<!-- PROMPT END -->"
SKIP_DIRS = {"__pycache__"}
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def sha256_text(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def read_task(tasks_root, task_id):
"""-> dict(front matter fields, prompt, externals=[(relpath, sha256, bytes)])"""
with open(os.path.join(tasks_root, task_id, "task.md"), encoding="utf-8", newline="") as f:
text = f.read()
if "\r" in text:
raise ValueError("%s/task.md contains CR characters" % task_id)
m = re.match(r"---\n(.*?)\n---\n", text, re.S)
if not m:
raise ValueError("%s/task.md has no front matter" % task_id)
meta = {}
for line in m.group(1).splitlines():
if ":" in line:
k, v = line.split(":", 1)
meta[k.strip()] = v.strip()
if text.count(BEGIN) != 1 or text.count(END) != 1:
raise ValueError("%s/task.md needs exactly one prompt block" % task_id)
body = text.split(BEGIN, 1)[1].split(END, 1)[0]
meta["prompt"] = body.strip("\n")
ext = []
if "## External seed files" in text:
for line in text.split("## External seed files", 1)[1].splitlines():
parts = line.split()
if len(parts) == 3 and re.fullmatch(r"[0-9a-f]{64}", parts[1]):
ext.append((parts[0], parts[1], int(parts[2])))
meta["externals"] = ext
if meta.get("id") != task_id:
raise ValueError("%s/task.md has id %r" % (task_id, meta.get("id")))
return meta
def task_ids(tasks_root):
return sorted(d for d in os.listdir(tasks_root) if os.path.isfile(os.path.join(tasks_root, d, "task.md")))
def task_files(tasks_root, task_id, reference=False):
"""Files of a task directory. The reference solution (reference/) is not installed on the server (the agent could find it), so it is not part of
the checked file list; `reference=True` lists only it."""
base = os.path.join(tasks_root, task_id)
out = []
for root, dirs, files in os.walk(base):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
in_ref = os.path.relpath(root, base).replace(os.sep, "/").split("/")[0] == "reference"
if in_ref != reference:
continue
for n in sorted(files):
if n.endswith(".pyc"):
continue
p = os.path.join(root, n)
out.append((os.path.relpath(p, tasks_root).replace(os.sep, "/"), p))
return sorted(out)
def tree_digest(lines):
return hashlib.sha256(("\n".join(lines) + "\n").encode()).hexdigest()
def seed_tree_lines(seed_dir, externals):
"""Lines `relpath sha256` of a workspace: the files of seed_dir plus the external files (sha256 from the task)."""
lines = []
if os.path.isdir(seed_dir):
for root, dirs, files in os.walk(seed_dir):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for n in sorted(files):
p = os.path.join(root, n)
lines.append("%s %s" % (os.path.relpath(p, seed_dir).replace(os.sep, "/"), sha256_file(p)))
for rel, sha, _n in externals:
lines.append("%s %s" % (rel, sha))
return sorted(lines)
def workspace_lines(ws):
return seed_tree_lines(ws, [])
def manifest_lines(tasks_root, ids=None):
out = []
for tid in ids or task_ids(tasks_root):
meta = read_task(tasks_root, tid)
file_lines = []
for rel, p in task_files(tasks_root, tid):
file_lines.append("%s %s" % (sha256_file(p), rel))
out.extend(file_lines)
for rel, sha, n in meta["externals"]:
out.append("EXTERNAL %s %s %s %d" % (tid, rel, sha, n))
out.append("PROMPT %s %s" % (tid, sha256_text(meta["prompt"])))
out.append("SEEDTREE %s %s" % (tid, tree_digest(seed_tree_lines(os.path.join(tasks_root, tid, "seed"), meta["externals"]))))
out.append("TASK %s %s" % (tid, tree_digest(file_lines)))
ref = ["%s %s" % (sha256_file(p), rel) for rel, p in task_files(tasks_root, tid, reference=True)]
out.append("REFERENCE %s %s" % (tid, tree_digest(ref)))
return out
def _task_of(line):
parts = line.split()
if parts and parts[0] in ("EXTERNAL", "PROMPT", "SEEDTREE", "TASK", "REFERENCE"):
return parts[1]
return parts[-1].split("/", 1)[0] if parts else ""
def check(tasks_root, ids=None):
"""-> list of problems (empty = the files match MANIFEST.sha256)."""
mpath = os.path.join(tasks_root, "MANIFEST.sha256")
if not os.path.isfile(mpath):
return ["MANIFEST.sha256 missing"]
recorded = [l for l in open(mpath, encoding="utf-8").read().splitlines() if l]
ids = ids or task_ids(tasks_root)
want = set(l for l in manifest_lines(tasks_root, ids) if not l.startswith("REFERENCE "))
have = set(l for l in recorded if _task_of(l) in ids and not l.startswith("REFERENCE ") and "/reference/" not in l)
return ["differs: " + l for l in sorted(want - have)] + ["recorded but not on disk: " + l for l in sorted(have - want)]
if __name__ == "__main__":
if len(sys.argv) >= 4 and sys.argv[1] == "prompt":
sys.stdout.write(read_task(sys.argv[2], sys.argv[3])["prompt"])
elif len(sys.argv) >= 3 and sys.argv[1] == "check":
probs = check(sys.argv[2], sys.argv[3:] or None)
for p in probs:
print(p)
print("manifest OK" if not probs else "manifest MISMATCH (%d)" % len(probs))
sys.exit(1 if probs else 0)
else:
print(__doc__)
sys.exit(2)
+203
View File
@@ -0,0 +1,203 @@
6f413777d0e2cd1003de7c7ca802ff4d1a90b9ba96975a68e8e45407e49df2cb crm/accept.py
59b9cf609770519c12ab9bfbeb3bb1707e65b7c9f97c03a853fac79cc7c4aad2 crm/hidden/crm_acceptance.py
b453724cde02032447adb07ddec17f56dbc66dc11fefbf7129160c90fc7c7022 crm/task.md
PROMPT crm 50875f4a1552713139637db8724134768014424ff297cffa61f688397ffa8e0d
SEEDTREE crm 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b
TASK crm 4f21e987b1b80c88e10d2ab6cafeeb85df3788289d0c2698705c859b959f645d
REFERENCE crm 04f3bd297f88413c42588bde73b8bd0c8e9fe3227122ffa0ce1ff60165c85e11
79cf9245ef49a2d152a0d46cff54ba451cbf38d78f75c5bd36598de73eccfb4a debuglog-sched/accept.py
a95e880e9c2a7e7df2f7106d43aa86e6d88eb309bb3637621bb4818bae9830b8 debuglog-sched/gen_log.py
816560cc32fecb0c4212c4526291dffc84aab0b6285103ecf1606fe66490c200 debuglog-sched/hidden/evidence.json
ffc6d8f9032bb7587a6c15736511b2b294bf6cad48447a77affe8c9c1fd717cb debuglog-sched/hidden/orig/sched/__init__.py
b2c5b733771d2bc3dd99bee690d9c602e4fbf2c3da3c8cf493e7989e3ce57714 debuglog-sched/hidden/orig/sched/clock.py
083a19f8ef4bbe2d04649ed44b3c4957d342e00ee53b1e525c4f5e5417451765 debuglog-sched/hidden/orig/sched/dedupe.py
333cf47efc624ac9dd877cdbd397c84181734b3abb212b3346e66480cd1a88d1 debuglog-sched/hidden/orig/sched/ids.py
c3d6153b0beb3be3ba69465b188a72cc4e768eca78719cf12676a7fe032501be debuglog-sched/hidden/orig/sched/lease.py
671b1c32e743cc8d78baf5c7accb65fb147abc40742d1534b7e9f8ac507ec3a8 debuglog-sched/hidden/orig/sched/logs.py
f95ce6592df16bd17e6f482b73a406ef5779347e6c308898b3de67dde915baa5 debuglog-sched/hidden/orig/sched/metrics.py
3315e3042a0e449c043c4468586fcf0d430199a054b368d215ed1a4407ee1fff debuglog-sched/hidden/orig/sched/model.py
a0e58243893026e9bd455ebe09ca4a260dd5de892d1a99b9774e9a12105edf25 debuglog-sched/hidden/orig/sched/queue.py
95756c44cc4cf8a66d0640a78a3a48a74a3ef3a40d9489cacbf16c1422ed273d debuglog-sched/hidden/orig/sched/retry.py
603e3053a0fe7a7c214b17416e3b8e735c0a15fb36487db95347e2a11b3d102e debuglog-sched/hidden/orig/sched/service.py
9b70fd4bec746d0756a989ba1d6bd6955c975e187f5bf8a656fb5956094ca9af debuglog-sched/hidden/orig/sched/sim.py
9e72b1d44e1534c5be399698248f098676dfadf75cbff7a42844a7e4137d6f1f debuglog-sched/hidden/orig/sched/store.py
16712ffc0bbb65a45aaf8af618091d5e1b796ccc71397ff5842544618a6549de debuglog-sched/hidden/orig/sched/worker.py
c102a3d6fe2592bf1bc09ddc08b62d5565304f8987e0e66a4a3ef880eac584c7 debuglog-sched/hidden/stress.py
c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched/hidden/tests/helpers.py
5f86ecbbfd0b2bd0ae9c7b2e6e2e7d5049b1f2e0f902c063a6128a062f5703ea debuglog-sched/hidden/tests/test_ids.py
37e86a97afb6ca565757600734cd5db75ff3cc86d01bcb8a9f30d72255f7231f debuglog-sched/hidden/tests/test_lease_dedupe.py
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
083a19f8ef4bbe2d04649ed44b3c4957d342e00ee53b1e525c4f5e5417451765 debuglog-sched/seed/sched/dedupe.py
333cf47efc624ac9dd877cdbd397c84181734b3abb212b3346e66480cd1a88d1 debuglog-sched/seed/sched/ids.py
c3d6153b0beb3be3ba69465b188a72cc4e768eca78719cf12676a7fe032501be debuglog-sched/seed/sched/lease.py
671b1c32e743cc8d78baf5c7accb65fb147abc40742d1534b7e9f8ac507ec3a8 debuglog-sched/seed/sched/logs.py
f95ce6592df16bd17e6f482b73a406ef5779347e6c308898b3de67dde915baa5 debuglog-sched/seed/sched/metrics.py
3315e3042a0e449c043c4468586fcf0d430199a054b368d215ed1a4407ee1fff debuglog-sched/seed/sched/model.py
a0e58243893026e9bd455ebe09ca4a260dd5de892d1a99b9774e9a12105edf25 debuglog-sched/seed/sched/queue.py
95756c44cc4cf8a66d0640a78a3a48a74a3ef3a40d9489cacbf16c1422ed273d debuglog-sched/seed/sched/retry.py
603e3053a0fe7a7c214b17416e3b8e735c0a15fb36487db95347e2a11b3d102e debuglog-sched/seed/sched/service.py
9b70fd4bec746d0756a989ba1d6bd6955c975e187f5bf8a656fb5956094ca9af debuglog-sched/seed/sched/sim.py
9e72b1d44e1534c5be399698248f098676dfadf75cbff7a42844a7e4137d6f1f debuglog-sched/seed/sched/store.py
16712ffc0bbb65a45aaf8af618091d5e1b796ccc71397ff5842544618a6549de debuglog-sched/seed/sched/worker.py
c1843cfa16b38717bb7702dea59262ed41856a96f84a8303854389d13a876442 debuglog-sched/seed/tests/helpers.py
5f86ecbbfd0b2bd0ae9c7b2e6e2e7d5049b1f2e0f902c063a6128a062f5703ea debuglog-sched/seed/tests/test_ids.py
37e86a97afb6ca565757600734cd5db75ff3cc86d01bcb8a9f30d72255f7231f debuglog-sched/seed/tests/test_lease_dedupe.py
691ed0b32061a5bff822a7816d3856f39f6bb532f927b1e35018e8149828f956 debuglog-sched/seed/tests/test_service.py
3d6624767165d46c961f724824135f1cbb0f07588d3240301e0eb8c1eda2cca7 debuglog-sched/seed/tests/test_sim.py
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
REFERENCE debuglog-sched 0069c1f700e546bb692b14698c888742ea4dc82ae2aa3bc20f64701a5cb16026
fa439d6b0c7e68cc66cb3cde833200cceb7c9d6cca60172680e9b172b7f41e0c feature-query/accept.py
d1f85a4c31091f1b862791927fb35929a20b95f5b64fa2ff0fb7dd8f9f370d07 feature-query/hidden/pristine_tests/test_csv_cli.py
ea62abaad8643e3d2e693983e9b543a665d5c4f940a3d270278d66a27ebee38f feature-query/hidden/pristine_tests/test_index_storage.py
2b54bed24f1e6b59ae7a3a1c46003d7b5ae194b08f55801371d41f45cbfbf702 feature-query/hidden/pristine_tests/test_schema.py
eb7d33c2e80835f87044a332ba875d2b8254b6345068a05cca5b30a817c2c9ae feature-query/hidden/pristine_tests/test_table.py
5f46ab44226bb7ecce6a36b36573876ae1a17c05995e59941df73e99587000e5 feature-query/hidden/test_hidden_spec.py
8e6a9509564adfdc4a0266b4dce93acfc455561c1b4db1e442f63ea63d740443 feature-query/seed/README.md
48028e8680af0fecf4a40034d1f61ca040376626f0025ef726638826fd0a6ef5 feature-query/seed/SPEC.md
bacc892fc5bd1fa73dff55c077841b1e23c45dbf7545def1db7767beffc22e37 feature-query/seed/minidb/__init__.py
6f8f61e59b4f1d95f2b7590c1ce4c1615cf02f09cbd494cd972e881186d4ae57 feature-query/seed/minidb/cli.py
bcd0c4cf542818fe61db4312b6f13dafb2aba118ab7118dc82dbeebaf7f4248f feature-query/seed/minidb/csvio.py
33a611456ab581e686894146e852bba53ba651982c46780ff762bf5c6b60a805 feature-query/seed/minidb/errors.py
5606d3e56a4c25fb2d4203c8d3d6b3fc547a561041e621f568a6abcccf7a850d feature-query/seed/minidb/index.py
8a5f133424959676e700158afe2c609a44985715d7d01cebce92ca7cb69aa381 feature-query/seed/minidb/schema.py
53db1e3cbe473b89ab6609784dc7d3872d3397a6582f16c613b5cd076f57dd90 feature-query/seed/minidb/storage.py
2783bf79d1ac8579fd5f9ef2566e7129d5699a603babdbce661d465593d09144 feature-query/seed/minidb/table.py
d1f85a4c31091f1b862791927fb35929a20b95f5b64fa2ff0fb7dd8f9f370d07 feature-query/seed/tests/test_csv_cli.py
ea62abaad8643e3d2e693983e9b543a665d5c4f940a3d270278d66a27ebee38f feature-query/seed/tests/test_index_storage.py
2b54bed24f1e6b59ae7a3a1c46003d7b5ae194b08f55801371d41f45cbfbf702 feature-query/seed/tests/test_schema.py
eb7d33c2e80835f87044a332ba875d2b8254b6345068a05cca5b30a817c2c9ae feature-query/seed/tests/test_table.py
f890a99921dc2a0f89f02791523a2f0d1316517612010f1bff774d502040deca feature-query/task.md
PROMPT feature-query b3c584256138f3a8315afce9beaa85271d0c2250add5a495a9787f03289cbbfd
SEEDTREE feature-query 5cf442da8591285881f72bbe06c34753924b319c55351da3da7a7b407a662440
TASK feature-query f986b4fece91b1f7cb0722c0dcf45f9d5d3bc11591f0535dc18eb06fc3a983bc
REFERENCE feature-query fbed87863e199b1ed079caf7a00c3e0542512130bf31f4e49173c7b1e1a24958
5c1b869972046b68422bdff0d251ad3abd393c4cdeec6c36ba2239683046c0ac fixbug-ledger/accept.py
999831ccbb0f03803cb81f6259bfbd6af98c972152c69252e051fa5a8e218cb2 fixbug-ledger/hidden/pristine_tests/helpers.py
85347be643d1edfae1cecb20eb5801d1be2038df94f579742c6482687f7c6b73 fixbug-ledger/hidden/pristine_tests/test_accounts.py
1034e8c1774082cf57af911fe50ec63c36c90ed9f1d2a4474851e5c61fed66a7 fixbug-ledger/hidden/pristine_tests/test_calendar.py
1f27195c3eca3858ad8c4c6c3f5d9f073d18ea35210bd77b8637e5bd62521e6c fixbug-ledger/hidden/pristine_tests/test_cli.py
ad44f94405a2ce4d0eb0953ce1e459d35da6e2d34181b49b7c53079a0671b495 fixbug-ledger/hidden/pristine_tests/test_exporter.py
fb320fbb0e5184cc968a60d0360a39c26a0db99220cb113743f3640f4e2925f2 fixbug-ledger/hidden/pristine_tests/test_fx.py
bd4bc42feb77648f95dc7a7829751b475ee824fda55c478237d3fc162aebc716 fixbug-ledger/hidden/pristine_tests/test_importer.py
c9a40606ecdaf27885e87645151716020a3e41f25a9ba840cb4b3ca3d42abf22 fixbug-ledger/hidden/pristine_tests/test_journal.py
113385a1dc93280bfe9c7a5b11acfbecb56519a35aee2a383a375a918569a299 fixbug-ledger/hidden/pristine_tests/test_money.py
2d7e5198a77951b4e12e9435536f03c80aa22e70309b8be6cf00470482357e87 fixbug-ledger/hidden/pristine_tests/test_reports.py
484bd8022f30ffa38a5114a924e693d5de9455dd2c22ef83d2f5aff6ce1e6859 fixbug-ledger/hidden/pristine_tests/test_rounding.py
97460a4e3ac323fdd4d36fb41f6e2bf1f809ab37faa2015615c59a64839c6e2d fixbug-ledger/hidden/pristine_tests/test_transactions.py
fbf1353ed4b7c7e7b2761287da82c34fd8e787d325278f0dcac199424c72be9d fixbug-ledger/hidden/pristine_tests/test_utils.py
6332fcbc1ad6f0feef36b7c80d47549b563d60f978de381da0ac1585150f86a6 fixbug-ledger/hidden/test_hidden.py
f405559a2ebaac0191a9b232eba29e9f8ba3785ca17e06c2b0bf7d8ce93a5ecd fixbug-ledger/seed/ledger/__init__.py
3ea21efe62ba31d237afa99c71f06fa662e3517db40085bc43a15c86d8c479aa fixbug-ledger/seed/ledger/accounts.py
248523398719790d5f063fdda022756a477edb2b44fa59e0c4c8ac181c2decdf fixbug-ledger/seed/ledger/calendar.py
110c2af6cccbd8be471b3752896248abc20346c83f8204d02642625e372dd783 fixbug-ledger/seed/ledger/cli.py
298f3b70386e08155efd4fd36f1354b9ef56275151702285bda78194eead7e46 fixbug-ledger/seed/ledger/exporter.py
6767538fa447d46749ec70d6d650e381f6de0ec4ac926673506cda708a7e5d16 fixbug-ledger/seed/ledger/fx.py
e8d215aa1898bd874044318b1c146dd8a0974de31a9a7a7fc03bb602dd197aab fixbug-ledger/seed/ledger/importer.py
72568bdefd99979e4f7119ee6bb8db32299b51543c5d4959e24496c6e9dbba07 fixbug-ledger/seed/ledger/journal.py
e14efa7a3f30957ff76512f36dcd96ab8202e59526f1d3228a6c3b808e4ba5ee fixbug-ledger/seed/ledger/money.py
a8da923eb120dc46730c697e0d3eb75dd59b9b99587bd7ae8ccd078736ca7d85 fixbug-ledger/seed/ledger/reports.py
9583515f9ad5e54db3164b0859f18e37a2f14e28e7b11940bcb86420e0ddfe00 fixbug-ledger/seed/ledger/rounding.py
bcd285a53587b9b9c64b8b5fe9974793db83eb48f0b1f7476caa83ef0e6b0945 fixbug-ledger/seed/ledger/transactions.py
18cbf5a1da40d9e50e9735535623d3c1393f23c76660d4e69ffaefabb34d4de2 fixbug-ledger/seed/ledger/utils.py
999831ccbb0f03803cb81f6259bfbd6af98c972152c69252e051fa5a8e218cb2 fixbug-ledger/seed/tests/helpers.py
85347be643d1edfae1cecb20eb5801d1be2038df94f579742c6482687f7c6b73 fixbug-ledger/seed/tests/test_accounts.py
1034e8c1774082cf57af911fe50ec63c36c90ed9f1d2a4474851e5c61fed66a7 fixbug-ledger/seed/tests/test_calendar.py
1f27195c3eca3858ad8c4c6c3f5d9f073d18ea35210bd77b8637e5bd62521e6c fixbug-ledger/seed/tests/test_cli.py
ad44f94405a2ce4d0eb0953ce1e459d35da6e2d34181b49b7c53079a0671b495 fixbug-ledger/seed/tests/test_exporter.py
fb320fbb0e5184cc968a60d0360a39c26a0db99220cb113743f3640f4e2925f2 fixbug-ledger/seed/tests/test_fx.py
bd4bc42feb77648f95dc7a7829751b475ee824fda55c478237d3fc162aebc716 fixbug-ledger/seed/tests/test_importer.py
c9a40606ecdaf27885e87645151716020a3e41f25a9ba840cb4b3ca3d42abf22 fixbug-ledger/seed/tests/test_journal.py
113385a1dc93280bfe9c7a5b11acfbecb56519a35aee2a383a375a918569a299 fixbug-ledger/seed/tests/test_money.py
2d7e5198a77951b4e12e9435536f03c80aa22e70309b8be6cf00470482357e87 fixbug-ledger/seed/tests/test_reports.py
484bd8022f30ffa38a5114a924e693d5de9455dd2c22ef83d2f5aff6ce1e6859 fixbug-ledger/seed/tests/test_rounding.py
97460a4e3ac323fdd4d36fb41f6e2bf1f809ab37faa2015615c59a64839c6e2d fixbug-ledger/seed/tests/test_transactions.py
fbf1353ed4b7c7e7b2761287da82c34fd8e787d325278f0dcac199424c72be9d fixbug-ledger/seed/tests/test_utils.py
c4f1d1d57783eda804ead793bac585c2da7ecacc1750aa209f495e32901bed7a fixbug-ledger/task.md
PROMPT fixbug-ledger 08f5c2fd63c199fa24274a7d36099354b27b7e2bde1e126a833a3a973073716b
SEEDTREE fixbug-ledger 41ba1db9dedeae30d1c189d70e45660639cb8e798bdf94dfb9a27e54bdb18c56
TASK fixbug-ledger c6e7743467badd427a94bad605e972b9f19c78b3cd54b141501c1dee59417302
REFERENCE fixbug-ledger 08eb07de9e7f22a9266478af9ed3643cf7bc956e32a867e903d69f2e7777f68c
2c01fffcdf4a1e959d9d3adbbd5965cf8d59e69dd330a3568966812b2f672432 refactor-shop/accept.py
f4bf75da964c784234c685b44b41c98846c6c03d46f8277115cb756d224d5f4c refactor-shop/hidden/behaviour.py
99546b78de332fc57d310eb3d0699b9d8110f662032e216c4ab886377e5588e2 refactor-shop/hidden/helpers_h.py
42fe54c2512025b108307dc77bd2da3383e18c903f546627576b8c0606692884 refactor-shop/hidden/tests/helpers.py
04834f5874086826d49418ff32b7fd25fab27c26ce033ed6af8fe9ef4df7c969 refactor-shop/hidden/tests/test_discounts.py
bdca9bbe816a81ff09edc4c74ff5d6d37b4cbc6d4f7d351e5edc77e35bcda0aa refactor-shop/hidden/tests/test_extras.py
aea1ce4cb823c6d829ef3449494a0eda439f3dc4196831c88950b787a898c1ca refactor-shop/hidden/tests/test_invoices.py
223c705dcda5eee296e136781afc2996e34d6969955d55ff9363891eaa7b2126 refactor-shop/hidden/tests/test_orders_customers.py
6754eedaee1c70fc2c209ab28dc2609589493ffc7736fb83a012213c4237a8f4 refactor-shop/hidden/tests/test_reports_cli.py
13553aa52621f19c8c9c0890f816db6b43832aa54e0936d734136716b99af08d refactor-shop/hidden/tests/test_services.py
c586c85c49c545ff2d7e343a930b4707e9f6ef100c7c86173627cf097713bed1 refactor-shop/hidden/tests/test_tax_shipping.py
7e27be2b3aae93ad60d3a586a5267470fe992c3c9dfd9eebea107092262b4da3 refactor-shop/seed/REFACTOR.md
d074cf8dc2888d831a514c242865ac4acf7adc0b6ba38a6b17fb92599bb2225a refactor-shop/seed/docs/ARCHITECTURE.md
374c39d3fa613fb5fb7de96cdcc75811d05745c474c723f553cebb021f58c0fb refactor-shop/seed/shop/__init__.py
5fb255ecdf2c9efac6cab26115724a936fc71c7eb5c776ac6a6174b4bc8f62a9 refactor-shop/seed/shop/analytics.py
e410140f39434f70d7ead874cb419173e180b002b8a68025395ddc386b373c3e refactor-shop/seed/shop/cart.py
9d58bcfe248800e1da6810e942d5c2a97a5bbb5a7264ed9a5c59e32c949d31fb refactor-shop/seed/shop/cli.py
d6273a339799bc94bcbe34892378252a8c1326ee95b17b9426553342dd167bd9 refactor-shop/seed/shop/currency.py
2b0083c86d20297265942ceed5ad29aa8845046cc229148e49f6b9200433d65a refactor-shop/seed/shop/customers.py
ecd7225da505b3f25724c861e8238193c858236a305385ebc1e2e3787bf9de50 refactor-shop/seed/shop/discounts.py
9f0d4d969b8bead49a53a0c3aaa88f9ecf6ceb97bf2fe265a1682b59bd09a211 refactor-shop/seed/shop/export.py
51adaf1b0792bf2de4156cd3a0ceb6693faae562b8d750fc66eb98860e9a709c refactor-shop/seed/shop/inventory.py
cc5c92e18cae0de9d683bd0ad2b6bf5b62343ef6094b06785ab25c7789ffc4c0 refactor-shop/seed/shop/invoices.py
189d40032fc0d6dd935f7a7c6115b4126c0241f6b45c25f76e8e27439afae11f refactor-shop/seed/shop/loyalty.py
eba38ca2d0bf635219326328d42cb9dae04ccfc00330a4936bfdb39be76dc46d refactor-shop/seed/shop/notifications.py
ceb779b89b29f7a191a1afcd988935a33ed4b34a0abdc911be1e3f7a129d865a refactor-shop/seed/shop/orders.py
3030bf82b9c200f70e65e17d955c9d8f7a7e3c3761a9f8106e4f236347d1d078 refactor-shop/seed/shop/products.py
0289e20c5744b88fd8790f1de2b77f9c09d72bb815e6aeb4697c17f5bda2935f refactor-shop/seed/shop/reports.py
226d3a79394f39fe9ddcb987538406bf1b8d37b086faa70a468fcc1e7b9b8900 refactor-shop/seed/shop/returns.py
f6112efca473e904c3af77b5759d7f57343268475054fedfdbbe159025e77ffc refactor-shop/seed/shop/sample.py
f4984646245b7996466cde4d28a26d9e4407358f33432e37459b60c902163a9c refactor-shop/seed/shop/shipping.py
7b38c2ba18b1dad2d875abd8254b8bed0467cac296c070b9f2a7336e7d1b0dc2 refactor-shop/seed/shop/storage.py
ca465f263e960368f644ea343273b3dfb47bc3f2fcd3df5af39dd4894eb7213f refactor-shop/seed/shop/tax.py
40f184a30984fef9c41f806223d43c0d3aba9096e994968d56564a0a998047aa refactor-shop/seed/shop/util.py
ed7c2bcb90e383a08451d6c0eef1f2a27ce7d06fec21510d4aec3594c58ac055 refactor-shop/seed/shop/validation.py
42fe54c2512025b108307dc77bd2da3383e18c903f546627576b8c0606692884 refactor-shop/seed/tests/helpers.py
04834f5874086826d49418ff32b7fd25fab27c26ce033ed6af8fe9ef4df7c969 refactor-shop/seed/tests/test_discounts.py
bdca9bbe816a81ff09edc4c74ff5d6d37b4cbc6d4f7d351e5edc77e35bcda0aa refactor-shop/seed/tests/test_extras.py
aea1ce4cb823c6d829ef3449494a0eda439f3dc4196831c88950b787a898c1ca refactor-shop/seed/tests/test_invoices.py
223c705dcda5eee296e136781afc2996e34d6969955d55ff9363891eaa7b2126 refactor-shop/seed/tests/test_orders_customers.py
6754eedaee1c70fc2c209ab28dc2609589493ffc7736fb83a012213c4237a8f4 refactor-shop/seed/tests/test_reports_cli.py
13553aa52621f19c8c9c0890f816db6b43832aa54e0936d734136716b99af08d refactor-shop/seed/tests/test_services.py
c586c85c49c545ff2d7e343a930b4707e9f6ef100c7c86173627cf097713bed1 refactor-shop/seed/tests/test_tax_shipping.py
0cb5c48a2d66b60c7de0f0db49310114421f3349dd034f133767e7957008d6c5 refactor-shop/task.md
PROMPT refactor-shop c5bdf450059292ab350151798b10315e2b85d44cfa7ab6ec4c22813ba7dbddb4
SEEDTREE refactor-shop e6517cfcb2303615554e51c4ea806adb8bc31e13016ed4c0e76a6bee4b06f686
TASK refactor-shop cb8966c83d87829ab3478355334c501f6fb52d91bc3b2dbcc1a6913ede79d5ac
REFERENCE refactor-shop 76768c5e9e356874ec4b28484cba9480f00ca2dc31ac2365efc4dc8a989a0c1a
073dce45b71fa4dea202cdbaa5c578b28d964db8ebf3f8a24747139d65860d53 smoke-mini/accept.py
2e1ee69a33c09bfe85108018756eec15f3a21edc2ac0a2e860ef88d5043de8a9 smoke-mini/hidden/pristine_tests/test_casing_stats.py
ae2f79e47cffea88b9d72f3846e833a0c0fa0afffbc2a1114f189e123c98deae smoke-mini/hidden/pristine_tests/test_words.py
367f96fb7e02c383e9956ea7e0cbed3515e61249b4008a0070afbef33826b745 smoke-mini/hidden/pristine_tests/test_wrap.py
4fcac38395af8bfc3b37eddff4e46435fa201d7116488056f131a26ff5f02459 smoke-mini/hidden/test_hidden.py
2e1ee69a33c09bfe85108018756eec15f3a21edc2ac0a2e860ef88d5043de8a9 smoke-mini/seed/tests/test_casing_stats.py
ae2f79e47cffea88b9d72f3846e833a0c0fa0afffbc2a1114f189e123c98deae smoke-mini/seed/tests/test_words.py
367f96fb7e02c383e9956ea7e0cbed3515e61249b4008a0070afbef33826b745 smoke-mini/seed/tests/test_wrap.py
bbd0aeea85b41e2435a93920cfe03daa51caa15ba2910b2978d24fae40f6952b smoke-mini/seed/textkit/__init__.py
293ef1e9a9281e5b6a14943184df43fa61c2dcc9f4774c35c61fd83c88bc2249 smoke-mini/seed/textkit/casing.py
d2e2ac08bdf24f1649444c4e44e833446dd713b8346b5940c89db11a8e7f063b smoke-mini/seed/textkit/stats.py
f7cd4b573b271cee61f7ef6bfdbdabe535bf195a3a9d7428f35016f6f991bf12 smoke-mini/seed/textkit/words.py
0614ff3004772633817a1c8726be605e574c6f3520b1b5c7cd488e740c857744 smoke-mini/seed/textkit/wrap.py
5ab0df296876874c879083a73742ec364270266e0cb3e5055b84f0824c8082a9 smoke-mini/task.md
PROMPT smoke-mini 007998d3609081db375ef8bb86238e86db2fdc2562663852f09cf133380b5866
SEEDTREE smoke-mini 6fd0b235b5dbf4266000326071d5a2de8c71b66b1324aa2943528ce5cfe1e521
TASK smoke-mini ec3f8b6cc156f43537cea083ddc3c37b257550f57766d7120300ab83219d68c3
REFERENCE smoke-mini 56439ed22f5f5f29cf755bb64a7974d7fe93b963476a3a342221364cf5f59b50
393134ef201e268df1c414f8ad337474f775a0c9f1e1bcd187ac3daa40e2e517 ttt/accept.py
995eee5321145dc74d6b379a50e5f35fb146fdf6d0faf9dc576e58bbdedbbe6a ttt/hidden/check_ttt.mjs
817e364533410c30040eb3fd9c8822d99dbd7ac2a8c79105a16a0e58451b78a0 ttt/task.md
EXTERNAL ttt three.module.min.js 08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7 691648
PROMPT ttt 2991e6aa15ef837cf77328c0b0fd7612bac74a47b8bdccc3b7e28c7a9a8cdfaa
SEEDTREE ttt ffe51d18c45dfdc8cb62ed8ff501b7a9391f3faf83b7a2cc3b8cefe91b0d6bd1
TASK ttt 834d7f9f074c78d13e4490ec39274b1b17553ab96839698d9c9bf077fda8101f
REFERENCE ttt 6d584d44a8c57716c4bc818193036c1315cf70ee8422665c4b3b6864d004d46f
+56
View File
@@ -0,0 +1,56 @@
# Codex task set for the lossy-vs-lossless delta study
Task set of the study `claude/codex-lossy-delta` (runner: `scripts/e2e/codex/delta/`, plan: `docs/experiments/codex-lossy-delta.md`).
Every task is run by the real Codex CLI 0.163.0 against four stacks (vanilla Strata lossy / lossless, our port lossy / lossless).
The prompt, the seed workspace and the acceptance script are byte-identical for all four variants and are checked against `MANIFEST.sha256`
before every run (`scripts/e2e/codex/delta/verify_tasks.py`); a mismatch stops the runner.
## Layout of one task (`tasks/<id>/`)
```text
task.md exact prompt text between the two marker lines (see below), plus notes for the orchestrator (never sent to Codex)
seed/ the frozen seed workspace: copied byte for byte into an empty directory before every run (may be empty; files that are too
big or third-party are listed in task.md under "External seed files" with their sha256 and are copied by the runner)
accept.py objective acceptance: `python3 accept.py WORKSPACE` -> exit 0 = task done, any other exit = not done. Prints one
`PASS name` / `FAIL name :: detail` line per check. It never depends on the variant, never reads the network, finishes in < 120 s,
uses only the Python 3 standard library (must run on Python 3.9 and 3.14) and copies the workspace to a temporary directory
before running anything of it (it must not modify the workspace).
hidden/ files only the acceptance script uses (hidden tests, golden data). Never copied into the workspace.
reference/ `overlay/` = files that, copied over `seed/`, make `accept.py` pass. Used only by `selftest.py` (the acceptance must FAIL on the
bare seed and PASS on seed + overlay). Never given to Codex.
```
`task.md` format (the runner extracts the prompt with `delta/taskfile.py`):
```text
---
id: <id>
title: <one line>
kind: <bugfix | feature | refactor | debug | create | multifile>
expected_rounds: <low>-<high> (the author's estimate of model requests; not enforced)
---
# <title>
(any notes for the orchestrator, free text; not sent to Codex)
## Prompt
<!-- PROMPT BEGIN -->
the exact prompt text; Codex receives everything between the two marker lines, without the line breaks directly after BEGIN / before END
<!-- PROMPT END -->
## External seed files
(optional) `relative/path sha256 bytes` per line
```
Rules for the prompt: self-contained, English, ends with an instruction to reply with a short summary when done, does not mention the study,
the variants or the acceptance script by name. The workspace is the current directory of Codex; there is no network; the machine has Python 3
(standard library only, no pytest), `gcc` and `make`, no Rust, no Node.
## Selftest
`python3 scripts/e2e/codex/tasks/selftest.py [task-id ...]` checks, for each task, that the manifest matches, that `accept.py` fails on the bare seed and
passes on seed + `reference/overlay`, and that `accept.py` does not modify the workspace. Run it before `freeze.py`.
## Freeze
`python3 scripts/e2e/codex/tasks/freeze.py` rewrites `MANIFEST.sha256` (sha256 of every file under every task directory, plus one `TASK <id> <digest>` line
per task, plus the external files). The runner verifies the same list on the server copy (read-only, `chmod a-w`) before every cell.
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Acceptance for the CRM task: the REST checks of crm_acceptance.py (21 checks) run on a COPY of the workspace.
accept.py WORKSPACE exit 0 = every check passed
"""
import os
import shutil
import subprocess
import sys
import tempfile
ws = os.path.abspath(sys.argv[1])
here = os.path.dirname(os.path.abspath(__file__))
check = os.path.join(here, "hidden", "crm_acceptance.py")
tmp = tempfile.mkdtemp(prefix="crm-ws-")
try:
copy = os.path.join(tmp, "ws")
shutil.copytree(ws, copy, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.db"))
rc = subprocess.call([sys.executable, check, copy], timeout=600)
finally:
shutil.rmtree(tmp, ignore_errors=True)
sys.exit(rc)
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Acceptance script for the CRM the agent builds (offline test driver, not shipped).
crm_acceptance.py WORKSPACE
Starts `python3 server.py` in WORKSPACE on a free port with a fresh database, drives the REST API of prompt-crm.txt and runs
the app's own tests. Exit status 0 when every check passed.
"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
ws = os.path.abspath(sys.argv[1])
results = []
def check(name, ok, detail=""):
results.append(bool(ok))
print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" :: {str(detail)[:300]}"), flush=True)
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
port = free_port()
db = os.path.join(tempfile.mkdtemp(prefix="crm-acc-"), "crm.db")
env = dict(os.environ, PORT=str(port), CRM_DB=db)
server = subprocess.Popen([sys.executable, "server.py"], cwd=ws, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
base = f"http://127.0.0.1:{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"})
try:
with urllib.request.urlopen(req, timeout=10) as r:
raw = r.read()
try:
return r.status, (json.loads(raw) if raw else None)
except ValueError:
return r.status, raw
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw) if raw else None
except ValueError:
return e.code, raw
try:
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
break
except OSError:
time.sleep(0.1)
st, _ = call("GET", "/")
check("GET / serves the front-end", st == 200, st)
st, co = call("POST", "/api/companies", {"name": "Acme Corp", "website": "https://acme.test", "industry": "tools"})
check("create company 201 with id", st == 201 and isinstance(co, dict) and isinstance(co.get("id"), int), (st, co))
cid = co["id"] if isinstance(co, dict) and "id" in co else 0
st, ct = call("POST", "/api/contacts", {"name": "Wile E. Coyote", "email": "wile@acme.test", "company_id": cid})
check("create contact 201", st == 201 and isinstance(ct, dict) and ct.get("company_id") == cid, (st, ct))
ctid = ct.get("id") if isinstance(ct, dict) else None
st, d = call("POST", "/api/deals", {"title": "Anvil order", "amount": 1500.5, "company_id": cid, "contact_id": ctid})
check("create deal 201 default stage lead", st == 201 and isinstance(d, dict) and d.get("stage") == "lead", (st, d))
did = d.get("id") if isinstance(d, dict) else 0
st, lst = call("GET", "/api/companies?q=acme")
check("search companies (case-insensitive)", st == 200 and isinstance(lst, list) and any(c.get("id") == cid for c in lst), (st, lst))
st, lst = call("GET", "/api/contacts?q=WILE@")
check("search contacts by email", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst))
st, d2 = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "proposal", "company_id": cid, "contact_id": ctid})
check("update deal stage", st == 200 and isinstance(d2, dict) and d2.get("stage") == "proposal" and d2.get("amount") == 2000, (st, d2))
st, _ = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "bogus"})
check("invalid stage is 400", st == 400, st)
st, lst = call("GET", "/api/deals?stage=proposal&q=anvil")
check("deals filter by stage and q", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst))
st, lst = call("GET", "/api/deals?stage=won")
check("deals filter by stage (empty)", st == 200 and lst == [], (st, lst))
st, n = call("POST", f"/api/deals/{did}/notes", {"body": "Called, wants a quote"})
check("add note 201", st == 201 and isinstance(n, dict) and n.get("body") == "Called, wants a quote", (st, n))
st, ns = call("GET", f"/api/deals/{did}/notes")
check("list notes", st == 200 and isinstance(ns, list) and len(ns) == 1, (st, ns))
st, p = call("GET", "/api/pipeline")
check("pipeline summary per stage", st == 200 and isinstance(p, dict) and set(p) == {"lead", "qualified", "proposal", "won", "lost"}
and p["proposal"]["count"] == 1 and p["proposal"]["amount"] == 2000, (st, p))
st, _ = call("POST", "/api/companies", {"website": "x"})
check("missing name is 400", st == 400, st)
st, _ = call("GET", "/api/deals/99999")
check("unknown id is 404", st == 404, st)
st, _ = call("DELETE", f"/api/companies/{cid}")
check("delete company 204", st == 204, st)
st, d3 = call("GET", f"/api/deals/{did}")
check("deleting the company keeps the deal and clears the reference", st == 200 and isinstance(d3, dict) and d3.get("company_id") in (None, 0), (st, d3))
st, _ = call("DELETE", f"/api/deals/{did}")
check("delete deal 204", st == 204, st)
st, _ = call("GET", f"/api/deals/{did}")
check("deleted deal is 404", st == 404, st)
finally:
server.terminate()
try:
server.wait(10)
except subprocess.TimeoutExpired:
server.kill()
t = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], cwd=ws, capture_output=True, text=True, timeout=300)
check("the app's own tests pass (unittest discover -s tests)", t.returncode == 0, t.stderr[-300:])
check("README.md exists", os.path.exists(os.path.join(ws, "README.md")))
print(f"SUMMARY {sum(results)}/{len(results)}")
sys.exit(0 if all(results) else 1)
@@ -0,0 +1,78 @@
# Code review
Phase 2 review of the whole tree. Every source and test file was read again
(`server.py`, `router.py`, `handlers.py`, `db.py`, `models.py`, `validation.py`,
`responses.py`, `errors.py`, `static/index.html` and all ten test modules).
The full list of weaknesses is below, then the three most important ones that
were fixed, with the tests that now cover them. The suite went from 125 to 137
tests during this pass and stays green.
## Weaknesses found
| # | Where | Problem | Severity | Status |
|---|-------|---------|----------|--------|
| 1 | `handlers.read_body` | `Content-Length` was trusted blindly: no upper bound, negative values accepted, so one request could allocate unbounded memory | High | **Fixed** |
| 2 | `handlers.handle_one` | The catch-all answered `500 {"error": "internal server error: <exception>"}`, leaking SQL, paths and library internals to the client; `sqlite3` failures were indistinguishable from bugs | High | **Fixed** |
| 3 | `router` + `db` | A mutation and its activity entry were two separate commits, and a failed statement left an open transaction on the shared connection, so a later unrelated write could commit half a change and the log could drift from the data | High | **Fixed** |
| 4 | `validation.clean_reference` | The message used `table[:-1]`, producing "does not reference an existing companie" | Low | Fixed (caught by the new validation unit tests) |
| 5 | `db.Store.update` / `delete` | The existence check ran outside the lock, so a concurrent delete could turn a request into a 500 instead of a 404 | Medium | Fixed together with #3 |
| 6 | `db.Store._filters` | `?q=` is interpolated into a `LIKE` pattern without escaping, so `%` and `_` in a search behave as wildcards | Low | Not fixed (no injection risk, only fuzzy matching); worth an `ESCAPE` clause |
| 7 | `router.pagination` | `limit` has no upper bound, so `?limit=100000000` is allowed | Medium | Not fixed; a cap (say 1000) plus a `Retry-After`-free 400 would be the fix |
| 8 | `db` schema | The `activity` table is append-only with no retention, and there are no indexes on `deals.stage`, `notes.deal_id` or `activity.deal_id` | Medium | Not fixed; fine at this size, would matter on a long-lived server |
| 9 | `router.serve_static` | Static files are read fully into memory per request, with no `ETag`/`Last-Modified`/caching | Low | Not fixed |
| 10 | `db.Store` | One shared connection serialises every write; no WAL mode | Low | Not fixed; adequate for a single-user local tool |
| 11 | `router.handle` and `handlers.handle_one` | Both mapped exceptions to statuses independently, so a new error type had to be handled twice | Medium | Fixed as part of #2 (`responses.error_response`) |
| 12 | API semantics | `PUT` replaces every editable field, so a partial body silently clears the rest. Required by the spec, but easy to misuse from a client | Low | Documented, not changed |
| 13 | `static/index.html` | No optimistic concurrency: two tabs editing the same deal overwrite each other; `fillForm` also has a hard-to-read nested ternary | Low | Not fixed |
| 14 | `tests/test_live_server.py` | The only test that touches a real socket is skipped in sandboxes that forbid `bind()`, so end-to-end coverage is environment dependent | Medium | Accepted; the in-process harness still drives the real handler class |
| 15 | Security overall | No authentication, CSRF protection or rate limiting; the server binds to 127.0.0.1 only | n/a | Accepted for a local tool |
## The three fixes
### 1. Request body limits (`handlers.py`)
`read_body` now rejects a missing-looking or negative `Content-Length` with a
400 and refuses any body larger than `handlers.MAX_BODY_BYTES` (1 MB) with a
new `PayloadTooLargeError` mapped to **413**. Notes are capped at 4000
characters, so the limit is far above any legitimate payload.
Covered by `tests/test_robustness.py::BodyLimitTest` (oversized body, body at
the limit, negative and non-numeric `Content-Length`).
### 2. One error mapping, no internal leakage (`responses.py`, `router.py`, `handlers.py`)
`responses.error_response(exc)` is now the single place that turns an
application error into a status (400 validation, 409 conflict, 413 payload,
404 not found, 405 method), and both the router and the HTTP adapter use it.
Anything unexpected is logged with a full traceback on the server side and
answered with the fixed body `{"error": "internal server error"}`;
`sqlite3.IntegrityError` becomes **409** "the change conflicts with existing
data" instead of a 500. A dropped client connection (`BrokenPipeError`,
`ConnectionResetError`) no longer triggers a second send attempt.
Covered by `tests/test_robustness.py::ErrorMappingTest`, which asserts that a
forced `sqlite3.OperationalError` produces a 500 whose body does not contain
the failing SQL text.
### 3. Atomic mutations and transaction hygiene (`db.py`, `router.py`)
`Store.transaction()` is a context manager that holds the lock, commits on
success and rolls back on any exception. `create`, `update`, `delete` and
`add_note` each take a `log_action` argument and write their activity row
inside that same transaction, so a record and its log entry can never drift
apart. The existence checks moved inside the lock, which also removes the
check-then-act race that used to turn a concurrent delete into a 500. The
router no longer writes to the log separately.
Covered by `tests/test_robustness.py::AtomicActivityTest`: exactly one entry
per successful mutation, none for a rejected request, a foreign key violation
leaves both the row and the log untouched, and no transaction is left open
after a failure.
## Deliberately left alone
Items 6 to 15 above are recorded rather than fixed: they are either mandated
by the specification (`PUT` semantics), acceptable for a loopback-only local
tool (no auth, one connection), or performance work that needs a real workload
to justify. Item 4 was a genuine bug and was fixed as a side effect of the
validation unit tests.
@@ -0,0 +1,144 @@
# Mini CRM
A small CRM web application written with the Python 3 standard library only
(`http.server`, `sqlite3`, `json`, `unittest`, `urllib`). No third-party
packages, no network access required.
## Run
```sh
python3 server.py # http://127.0.0.1:8000
PORT=8080 CRM_DB=crm.db python3 server.py
```
| Variable | Default | Meaning |
|----------|------------|-------------------------------|
| `PORT` | `8000` | TCP port, always on 127.0.0.1 |
| `CRM_DB` | `crm.db` | SQLite database file |
Tables are created on first start. The single page app is served at `GET /`.
## Test
```sh
python3 -m unittest discover -s tests
```
The suite runs offline. Most tests drive the real request handler in process;
`tests/test_live_server.py` additionally starts a listening server and is
skipped automatically when the environment forbids opening a socket.
## Data model
| Table | Columns |
|-----------|----------------------------------------------------------------|
| companies | `id`, `name` (required), `website`, `industry` |
| contacts | `id`, `name` (required), `email`, `phone`, `company_id` → companies |
| deals | `id`, `title` (required), `amount` (number ≥ 0, default 0), `stage` (default `lead`), `company_id` → companies, `contact_id` → contacts, `created_at` |
| notes | `id`, `deal_id` → deals, `body` (required), `created_at` |
| activity | `id`, `created_at`, `action` (create/update/delete), `entity`, `entity_id`, `deal_id`, `summary` |
Every create, update and delete appends one `activity` row in the same SQLite
transaction as the change itself, so the log can never drift from the data.
Deal stages are exactly `lead`, `qualified`, `proposal`, `won`, `lost`.
Foreign keys use `ON DELETE SET NULL`, so deleting a company or contact keeps
the deals and only clears the reference; deleting a deal removes its notes.
## API
All bodies and responses are JSON (`Content-Type: application/json`).
Unknown ids answer `404 {"error": "..."}`, invalid input answers
`400 {"error": "..."}`, and a known route used with the wrong verb answers
`405 {"error": "..."}`. An oversized body answers `413 {"error": "..."}` and a
database conflict answers `409 {"error": "..."}`; unexpected failures return a
generic `500` and are logged with a traceback on the server side.
For each resource `companies`, `contacts`, `deals`:
| Method & path | Behaviour |
|-------------------|----------------------------------------------------------|
| `GET /api/<r>` | list all; `?q=text` case-insensitive substring match on name/title/email, deals also accept `?stage=<stage>` |
| `POST /api/<r>` | create, `201` + the record including its integer `id` |
| `GET /api/<r>/{id}` | fetch one record |
| `PUT /api/<r>/{id}` | replace the editable fields, `200` + the record |
| `DELETE /api/<r>/{id}` | delete, `204` with no body |
Every list endpoint also accepts `?limit=N&offset=M` (no limit and `offset=0`
by default) and always answers with an `X-Total-Count` header holding the
number of records matching the filters, ignoring the page.
Notes:
| Method & path | Behaviour |
|----------------------------|-------------------------------------------------------|
| `GET /api/deals/{id}/notes` | list the notes of a deal, oldest first |
| `POST /api/deals/{id}/notes` | create a note, body `{"body": "text"}` is required |
Pipeline:
| Method & path | Behaviour |
|-------------------|----------------------------------------------------------------------|
| `GET /api/pipeline` | `{"lead": {"count": n, "amount": total}, ...}` for every stage |
CSV export (same `q`, `stage`, `limit` and `offset` parameters, header row,
RFC 4180 quoting, `Content-Disposition: attachment`):
| Method & path | Behaviour |
|----------------------------|---------------------------------------------|
| `GET /api/companies.csv` | companies as `text/csv` |
| `GET /api/contacts.csv` | contacts as `text/csv` |
| `GET /api/deals.csv` | deals as `text/csv` |
Activity log:
| Method & path | Behaviour |
|----------------------|-----------------------------------------------------------------------|
| `GET /api/activity` | newest entries first; `?limit=N`, `?offset=M`, `?entity=<r>`, `?deal_id=<id>`, plus `X-Total-Count` |
### Examples
```sh
curl -s -X POST localhost:8000/api/companies \
-H 'Content-Type: application/json' \
-d '{"name":"Acme","industry":"tools"}'
curl -s -X POST localhost:8000/api/deals \
-H 'Content-Type: application/json' \
-d '{"title":"Rollout","amount":4200,"stage":"qualified","company_id":1}'
curl -s 'localhost:8000/api/deals?stage=qualified&q=roll'
curl -s -X POST localhost:8000/api/deals/1/notes -d '{"body":"kickoff call booked"}'
curl -s localhost:8000/api/pipeline
curl -s -D - -o /dev/null 'localhost:8000/api/companies?limit=2' # X-Total-Count
curl -s localhost:8000/api/deals.csv
curl -s 'localhost:8000/api/activity?deal_id=1&limit=5'
```
## Front-end
`static/index.html` is a dependency free single page app: companies list,
contacts list, a deals board with one column per stage, a search box that
filters every list through the API, create/edit/delete forms for the three
resources, and a deal detail panel showing the notes (with an add-note form)
and the activity of that deal. Keyboard shortcuts: `/` focuses the search box,
`Esc` closes the deal panel.
## Layout
```
server.py entry point: env config, server class, re-exports
router.py routes → responses, pagination, CSV, static files
handlers.py http.server adapter (bytes in, bytes out)
db.py SQLite schema and access, atomic activity logging
models.py resource registry, stages, validators per resource
validation.py shared input validation helpers
responses.py Response/FileResponse and the error → status mapping
errors.py the exception types behind 400/404/405/413
static/index.html single page front-end
tests/ unittest suite (one module per area of the API)
CODE_REVIEW.md phase 2 review: weaknesses found and the fixes applied
```
`python3 server.py` is still the only entry point; the modules above are
imported by it and `import server` still exposes them.
@@ -0,0 +1,264 @@
"""SQLite access layer."""
import os
import sqlite3
import threading
from contextlib import contextmanager
from errors import NotFoundError
from models import RESOURCES, STAGES, now_iso, record_label
SCHEMA = """
CREATE TABLE IF NOT EXISTS companies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
website TEXT NOT NULL DEFAULT '',
industry TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS deals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
amount REAL NOT NULL DEFAULT 0,
stage TEXT NOT NULL DEFAULT 'lead',
company_id INTEGER REFERENCES companies(id) ON DELETE SET NULL,
contact_id INTEGER REFERENCES contacts(id) ON DELETE SET NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
body TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS activity (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL,
action TEXT NOT NULL,
entity TEXT NOT NULL,
entity_id INTEGER NOT NULL,
deal_id INTEGER,
summary TEXT NOT NULL
);
"""
def _paging(sql, params, limit, offset):
"""Append a SQLite page clause; OFFSET alone needs ``LIMIT -1``."""
page_params = list(params)
if limit is not None:
sql += " LIMIT ? OFFSET ?"
page_params.extend([limit, offset])
elif offset:
sql += " LIMIT -1 OFFSET ?"
page_params.append(offset)
return sql, page_params
def activity_params(action, entity, record):
"""Build the activity row for a mutation, linked to its deal when known."""
if entity == "notes":
deal_id = record.get("deal_id")
elif entity == "deals":
deal_id = record["id"]
else:
deal_id = None
return (now_iso(), action, entity, record["id"], deal_id, record_label(entity, record))
class Store:
"""One SQLite connection guarded by a lock (the server is threaded)."""
def __init__(self, path):
self.path = path
self.lock = threading.RLock()
directory = os.path.dirname(os.path.abspath(path))
if directory and not os.path.isdir(directory):
os.makedirs(directory, exist_ok=True)
self.conn = sqlite3.connect(path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
with self.lock:
self.conn.execute("PRAGMA foreign_keys = ON")
self.conn.executescript(SCHEMA)
self.conn.commit()
def close(self):
with self.lock:
self.conn.close()
@contextmanager
def transaction(self):
"""Hold the lock and commit on success, roll back on any failure."""
with self.lock:
try:
yield
self.conn.commit()
except BaseException:
self.conn.rollback()
raise
def exists(self, table, record_id):
with self.lock:
row = self.conn.execute(
"SELECT 1 FROM %s WHERE id = ?" % table, (record_id,)
).fetchone()
return row is not None
def _filters(self, resource, q=None, stage=None):
cfg = RESOURCES[resource]
where, params = [], []
if q:
clauses = ["LOWER(%s) LIKE LOWER(?)" % field for field in cfg["search"]]
where.append("(%s)" % " OR ".join(clauses))
params.extend(["%%%s%%" % q] * len(clauses))
if stage and resource == "deals":
where.append("stage = ?")
params.append(stage)
return where, params
def list(self, resource, q=None, stage=None, limit=None, offset=0):
cfg = RESOURCES[resource]
where, params = self._filters(resource, q, stage)
sql = "SELECT * FROM %s" % cfg["table"]
if where:
sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY id"
sql, page_params = _paging(sql, params, limit, offset)
with self.lock:
rows = self.conn.execute(sql, page_params).fetchall()
total = self.conn.execute(
"SELECT COUNT(*) FROM %s%s"
% (cfg["table"], (" WHERE " + " AND ".join(where)) if where else ""),
params,
).fetchone()[0]
return [dict(row) for row in rows], int(total)
def get(self, resource, record_id):
cfg = RESOURCES[resource]
with self.lock:
row = self.conn.execute(
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
).fetchone()
if row is None:
raise NotFoundError("%s %s not found" % (resource, record_id))
return dict(row)
def create(self, resource, values, log_action=None):
cfg = RESOURCES[resource]
columns = list(values.keys())
sql = "INSERT INTO %s (%s) VALUES (%s)" % (
cfg["table"],
", ".join(columns),
", ".join("?" for _ in columns),
)
with self.transaction():
cursor = self.conn.execute(sql, [values[c] for c in columns])
record_id = cursor.lastrowid
if log_action:
created = self.conn.execute(
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
).fetchone()
self._append_activity(activity_params(log_action, resource, dict(created)))
return self.get(resource, record_id)
def update(self, resource, record_id, values, log_action=None):
cfg = RESOURCES[resource]
columns = list(values.keys())
sql = "UPDATE %s SET %s WHERE id = ?" % (
cfg["table"],
", ".join("%s = ?" % column for column in columns),
)
with self.transaction():
self.get(resource, record_id)
self.conn.execute(sql, [values[c] for c in columns] + [record_id])
updated = self.conn.execute(
"SELECT * FROM %s WHERE id = ?" % cfg["table"], (record_id,)
).fetchone()
if updated is None:
raise NotFoundError("%s %s not found" % (resource, record_id))
if log_action:
self._append_activity(activity_params(log_action, resource, dict(updated)))
return self.get(resource, record_id)
def delete(self, resource, record_id, log_action=None):
cfg = RESOURCES[resource]
with self.transaction():
record = self.get(resource, record_id)
self.conn.execute("DELETE FROM %s WHERE id = ?" % cfg["table"], (record_id,))
if log_action:
self._append_activity(activity_params(log_action, resource, record))
return record
def _append_activity(self, params):
"""Insert one activity row inside the caller's transaction."""
self.conn.execute(
"INSERT INTO activity (created_at, action, entity, entity_id, deal_id, summary)"
" VALUES (?, ?, ?, ?, ?, ?)",
params,
)
def list_activity(self, limit=None, offset=0, deal_id=None, entity=None):
where, params = [], []
if deal_id is not None:
where.append("deal_id = ?")
params.append(deal_id)
if entity:
where.append("entity = ?")
params.append(entity)
sql = "SELECT * FROM activity"
if where:
sql += " WHERE " + " AND ".join(where)
count_sql = sql.replace("SELECT *", "SELECT COUNT(*)")
sql += " ORDER BY id DESC"
sql, page_params = _paging(sql, params, limit, offset)
with self.lock:
rows = self.conn.execute(sql, page_params).fetchall()
total = self.conn.execute(count_sql, params).fetchone()[0]
return [dict(row) for row in rows], int(total)
def list_notes(self, deal_id, limit=None, offset=0):
self.get("deals", deal_id)
sql, page_params = _paging(
"SELECT * FROM notes WHERE deal_id = ? ORDER BY id", [deal_id], limit, offset
)
with self.lock:
rows = self.conn.execute(
sql, page_params
).fetchall()
total = self.conn.execute(
"SELECT COUNT(*) FROM notes WHERE deal_id = ?", (deal_id,)
).fetchone()[0]
return [dict(row) for row in rows], int(total)
def add_note(self, deal_id, body, log_action=None):
self.get("deals", deal_id)
with self.transaction():
cursor = self.conn.execute(
"INSERT INTO notes (deal_id, body, created_at) VALUES (?, ?, ?)",
(deal_id, body, now_iso()),
)
if log_action:
created = self.conn.execute(
"SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,)
).fetchone()
self._append_activity(activity_params(log_action, "notes", dict(created)))
row = self.conn.execute("SELECT * FROM notes WHERE id = ?", (cursor.lastrowid,)).fetchone()
return dict(row)
def pipeline(self):
with self.lock:
rows = self.conn.execute(
"SELECT stage, COUNT(*) AS count, COALESCE(SUM(amount), 0) AS amount"
" FROM deals GROUP BY stage"
).fetchall()
totals = {stage: {"count": 0, "amount": 0.0} for stage in STAGES}
for row in rows:
if row["stage"] in totals:
totals[row["stage"]] = {"count": int(row["count"]), "amount": float(row["amount"])}
return totals
@@ -0,0 +1,21 @@
"""Exceptions shared by the CRM layers; each maps to an HTTP status."""
class ValidationError(ValueError):
"""Raised when client input cannot be accepted (HTTP 400)."""
class NotFoundError(Exception):
"""Raised when a record or route does not exist (HTTP 404)."""
class MethodNotAllowedError(Exception):
"""Raised when a route exists but not for this method (HTTP 405)."""
def __init__(self, allowed=()):
super().__init__("method not allowed")
self.allowed = tuple(allowed)
class PayloadTooLargeError(Exception):
"""Raised when a request body exceeds the accepted size (HTTP 413)."""
@@ -0,0 +1,99 @@
"""The http.server adapter: bytes in, bytes out."""
import json
import os
import sqlite3
import traceback
from http.server import BaseHTTPRequestHandler
from errors import PayloadTooLargeError, ValidationError
from responses import Response, error_response
MAX_BODY_BYTES = 1_000_000
class CRMRequestHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "MiniCRM/1.0"
@property
def app(self):
return self.server.app
def log_message(self, fmt, *args):
if os.environ.get("CRM_VERBOSE"):
super().log_message(fmt, *args)
def read_body(self):
raw_length = self.headers.get("Content-Length")
try:
length = int(raw_length or 0)
except ValueError:
raise ValidationError("Content-Length must be a number")
if length < 0:
raise ValidationError("Content-Length must be a number")
if length > MAX_BODY_BYTES:
raise PayloadTooLargeError(
"request body is larger than %d bytes" % MAX_BODY_BYTES
)
raw = self.rfile.read(length) if length > 0 else b""
if not raw:
return None
try:
return json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, ValueError):
raise ValidationError("request body must be valid JSON")
def process(self, method):
body = self.read_body() if method in ("POST", "PUT", "PATCH") else None
return self.app.handle(method, self.path, body)
def send(self, response):
self.send_response(response.status)
if response.content_type:
self.send_header("Content-Type", response.content_type)
self.send_header("Content-Length", str(len(response.body)))
for key, value in response.headers.items():
self.send_header(key, value)
self.end_headers()
if response.body and self.command != "HEAD":
self.wfile.write(response.body)
def handle_one(self, method):
try:
response = self.process(method)
except (BrokenPipeError, ConnectionResetError):
return # the client hung up; there is nobody left to answer
except Exception as exc:
response = error_response(exc)
if response is None:
response = self.unexpected_error(exc)
try:
self.send(response)
except (BrokenPipeError, ConnectionResetError):
pass
def unexpected_error(self, exc):
"""Log the failure server side, answer with a generic message."""
traceback.print_exc()
if isinstance(exc, sqlite3.IntegrityError):
return Response(409, {"error": "the change conflicts with existing data"})
return Response(500, {"error": "internal server error"})
def do_GET(self):
self.handle_one("GET")
def do_HEAD(self):
self.handle_one("HEAD")
def do_POST(self):
self.handle_one("POST")
def do_PUT(self):
self.handle_one("PUT")
def do_DELETE(self):
self.handle_one("DELETE")
def do_PATCH(self):
self.handle_one("PATCH")
@@ -0,0 +1,95 @@
"""Resource definitions: stages, editable fields, validators and labels."""
from datetime import datetime, timezone
from validation import (
clean_amount,
clean_email,
clean_reference,
clean_stage,
clean_text,
)
STAGES = ("lead", "qualified", "proposal", "won", "lost")
DEFAULT_STAGE = "lead"
def now_iso():
"""Timestamp used by the records and by the activity log."""
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def validate_company(store, data):
return {
"name": clean_text(data.get("name"), "name", required=True),
"website": clean_text(data.get("website"), "website"),
"industry": clean_text(data.get("industry"), "industry"),
}
def validate_contact(store, data):
return {
"name": clean_text(data.get("name"), "name", required=True),
"email": clean_email(data.get("email"), "email"),
"phone": clean_text(data.get("phone"), "phone"),
"company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"),
}
def validate_deal(store, data):
return {
"title": clean_text(data.get("title"), "title", required=True),
"amount": clean_amount(data.get("amount"), "amount"),
"stage": clean_stage(data.get("stage"), STAGES, "stage", DEFAULT_STAGE),
"company_id": clean_reference(store, data.get("company_id"), "companies", "company_id", "company"),
"contact_id": clean_reference(store, data.get("contact_id"), "contacts", "contact_id", "contact"),
}
RESOURCES = {
"companies": {
"table": "companies",
"singular": "company",
"search": ("name",),
"fields": ("name", "website", "industry"),
"validate": validate_company,
"label": "name",
"csv_columns": ("id", "name", "website", "industry"),
},
"contacts": {
"table": "contacts",
"singular": "contact",
"search": ("name", "email"),
"fields": ("name", "email", "phone", "company_id"),
"validate": validate_contact,
"label": "name",
"csv_columns": ("id", "name", "email", "phone", "company_id"),
},
"deals": {
"table": "deals",
"singular": "deal",
"search": ("title",),
"fields": ("title", "amount", "stage", "company_id", "contact_id"),
"validate": validate_deal,
"auto": {"created_at": now_iso},
"label": "title",
"csv_columns": ("id", "title", "amount", "stage", "company_id", "contact_id", "created_at"),
},
}
def record_label(resource, record):
"""Short human readable description used in the activity log."""
if resource == "notes":
return note_label(record)
field = RESOURCES[resource]["label"]
label = (record.get(field) or "").strip() or "#%s" % record.get("id")
return '%s "%s"' % (RESOURCES[resource]["singular"], label)
def note_label(note):
"""Short description of a note, truncated to keep the log readable."""
body = " ".join((note.get("body") or "").split())
if len(body) > 80:
body = body[:79] + "…"
return 'note "%s"' % body
@@ -0,0 +1,60 @@
"""Response objects returned by the router."""
import json
from errors import (
MethodNotAllowedError,
NotFoundError,
PayloadTooLargeError,
ValidationError,
)
CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json",
".csv": "text/csv; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
}
class Response:
"""A JSON (or empty) HTTP response."""
def __init__(self, status, payload=None, headers=None):
self.status = status
self.payload = payload
self.headers = dict(headers or {})
if payload is None:
self.body = b""
self.content_type = None
else:
self.body = json.dumps(payload).encode("utf-8")
self.content_type = "application/json"
class FileResponse(Response):
"""A response with a pre-rendered body and an explicit content type."""
def __init__(self, status, body, content_type, headers=None):
self.status = status
self.payload = None
self.headers = dict(headers or {})
self.body = body
self.content_type = content_type
def error_response(exc):
"""Map a known application error to a response, or None if it is unexpected."""
if isinstance(exc, ValidationError):
return Response(400, {"error": str(exc)})
if isinstance(exc, PayloadTooLargeError):
return Response(413, {"error": str(exc)})
if isinstance(exc, NotFoundError):
return Response(404, {"error": str(exc)})
if isinstance(exc, MethodNotAllowedError):
return Response(405, {"error": str(exc)}, {"Allow": ", ".join(exc.allowed)})
return None
@@ -0,0 +1,176 @@
"""Request routing: turns (method, path, body) into a Response."""
import csv
import io
import os
from urllib.parse import parse_qs, unquote, urlparse
from errors import MethodNotAllowedError, NotFoundError, ValidationError
from models import RESOURCES
from responses import CONTENT_TYPES, FileResponse, Response, error_response
from validation import (
MAX_NOTE_LEN,
clean_text,
parse_id,
parse_int_param,
require_object,
)
def pagination(query):
"""Extract limit/offset from a query string (limit absent means "all")."""
limit = parse_int_param(query["limit"], "limit", 0) if query.get("limit") is not None else None
offset = parse_int_param(query.get("offset", "0"), "offset", 0)
return limit, offset
def render_csv(resource, records):
"""Render records as CSV with a header row and RFC 4180 quoting."""
columns = RESOURCES[resource]["csv_columns"]
buffer = io.StringIO()
writer = csv.writer(buffer, lineterminator="\r\n")
writer.writerow(columns)
for record in records:
writer.writerow(["" if record.get(column) is None else record.get(column) for column in columns])
return buffer.getvalue().encode("utf-8")
class CRMApp:
"""Transport agnostic dispatcher: everything except the socket."""
def __init__(self, store, static_dir):
self.store = store
self.static_dir = static_dir
def handle(self, method, raw_path, body=None):
method = method.upper()
parsed = urlparse(raw_path)
path = unquote(parsed.path) or "/"
query = {}
for key, values in parse_qs(parsed.query, keep_blank_values=True).items():
query[key] = values[-1]
try:
if path.startswith("/api/"):
return self.handle_api(method, path, query, body)
return self.serve_static(method, path)
except (ValidationError, NotFoundError, MethodNotAllowedError) as exc:
return error_response(exc)
def serve_static(self, method, path):
if method not in ("GET", "HEAD"):
raise MethodNotAllowedError(("GET", "HEAD"))
if path in ("/", "/index.html"):
relative = "index.html"
elif path.startswith("/static/"):
relative = path[len("/static/"):]
else:
raise NotFoundError("%s not found" % path)
root = os.path.realpath(self.static_dir)
target = os.path.realpath(os.path.join(root, relative))
if target != root and not target.startswith(root + os.sep):
raise NotFoundError("%s not found" % path)
if not os.path.isfile(target):
raise NotFoundError("%s not found" % path)
with open(target, "rb") as handle:
content = handle.read()
content_type = CONTENT_TYPES.get(os.path.splitext(target)[1].lower(), "application/octet-stream")
return FileResponse(200, content, content_type)
def handle_api(self, method, path, query, body):
parts = [part for part in path.split("/") if part]
if parts == ["api", "pipeline"]:
if method != "GET":
raise MethodNotAllowedError(("GET",))
return Response(200, self.store.pipeline())
if parts == ["api", "activity"]:
return self.activity(method, query)
if len(parts) == 2 and parts[1].endswith(".csv"):
return self.export_csv(method, parts[1][: -len(".csv")], query)
if len(parts) >= 2 and parts[1] in RESOURCES:
resource = parts[1]
if len(parts) == 2:
return self.collection(method, resource, query, body)
if len(parts) == 3:
return self.record(method, resource, parts[2], body)
if len(parts) == 4 and parts[1] == "deals" and parts[3] == "notes":
return self.notes(method, parts[2], body, query)
raise NotFoundError("%s not found" % path)
def activity(self, method, query):
if method != "GET":
raise MethodNotAllowedError(("GET",))
limit, offset = pagination(query)
deal_id = None
if query.get("deal_id"):
deal_id = parse_int_param(query["deal_id"], "deal_id", 1)
entries, total = self.store.list_activity(
limit=limit, offset=offset, deal_id=deal_id, entity=query.get("entity") or None
)
return Response(200, entries, {"X-Total-Count": str(total)})
def export_csv(self, method, resource, query):
if resource not in RESOURCES:
raise NotFoundError("/api/%s.csv not found" % resource)
if method not in ("GET", "HEAD"):
raise MethodNotAllowedError(("GET", "HEAD"))
limit, offset = pagination(query)
records, _total = self.store.list(
resource,
q=query.get("q") or None,
stage=query.get("stage") or None,
limit=limit,
offset=offset,
)
filename = "%s.csv" % resource
return FileResponse(
200,
render_csv(resource, records),
CONTENT_TYPES[".csv"],
{"Content-Disposition": 'attachment; filename="%s"' % filename},
)
def collection(self, method, resource, query, body):
if method == "GET":
limit, offset = pagination(query)
records, total = self.store.list(
resource,
q=query.get("q") or None,
stage=query.get("stage") or None,
limit=limit,
offset=offset,
)
return Response(200, records, {"X-Total-Count": str(total)})
if method == "POST":
values = RESOURCES[resource]["validate"](self.store, require_object(body))
for column, factory in RESOURCES[resource].get("auto", {}).items():
values[column] = factory()
record = self.store.create(resource, values, log_action="create")
return Response(201, record)
raise MethodNotAllowedError(("GET", "POST"))
def record(self, method, resource, raw_id, body):
record_id = parse_id(raw_id)
if method == "GET":
return Response(200, self.store.get(resource, record_id))
if method == "PUT":
values = RESOURCES[resource]["validate"](self.store, require_object(body))
record = self.store.update(resource, record_id, values, log_action="update")
return Response(200, record)
if method == "DELETE":
record = self.store.delete(resource, record_id, log_action="delete")
return Response(204)
raise MethodNotAllowedError(("GET", "PUT", "DELETE"))
def notes(self, method, raw_id, body, query=None):
deal_id = parse_id(raw_id)
if method == "GET":
limit, offset = pagination(query)
notes, total = self.store.list_notes(deal_id, limit=limit, offset=offset)
return Response(200, notes, {"X-Total-Count": str(total)})
if method == "POST":
text = clean_text(
require_object(body).get("body"), "body", required=True, max_len=MAX_NOTE_LEN
)
note = self.store.add_note(deal_id, text, log_action="create")
return Response(201, note)
raise MethodNotAllowedError(("GET", "POST"))
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Entry point of the Mini CRM.
Run it with ``python3 server.py``. Configuration comes from the environment:
* ``PORT`` -- TCP port, default 8000 (always bound to 127.0.0.1)
* ``CRM_DB`` -- SQLite file, default ``crm.db``
The implementation lives in the sibling modules ``db``, ``models``,
``validation``, ``responses``, ``router`` and ``handlers``. This module wires
them together and re-exports their public names, so ``import server`` keeps
working for the tests and for scripts built on top of it.
"""
import os
from http.server import ThreadingHTTPServer
from db import SCHEMA, Store
from errors import MethodNotAllowedError, NotFoundError, ValidationError
from handlers import CRMRequestHandler
from models import DEFAULT_STAGE, RESOURCES, STAGES, now_iso
from responses import CONTENT_TYPES, FileResponse, Response
from router import CRMApp
from validation import (
EMAIL_RE,
MAX_NOTE_LEN,
MAX_TEXT_LEN,
clean_amount,
clean_email,
clean_reference,
clean_stage,
clean_text,
parse_id,
require_object,
)
HOST = "127.0.0.1"
DEFAULT_PORT = 8000
DEFAULT_DB = "crm.db"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")
__all__ = [
"CONTENT_TYPES", "CRMApp", "CRMRequestHandler", "CRMServer", "DEFAULT_DB",
"DEFAULT_PORT", "DEFAULT_STAGE", "EMAIL_RE", "FileResponse", "HOST",
"MAX_NOTE_LEN", "MAX_TEXT_LEN", "MethodNotAllowedError", "NotFoundError",
"RESOURCES", "Response", "SCHEMA", "STAGES", "STATIC_DIR", "Store",
"ValidationError", "clean_amount", "clean_email", "clean_reference",
"clean_stage", "clean_text", "config_from_env", "create_server", "main",
"now_iso", "parse_id", "require_object",
]
class CRMServer(ThreadingHTTPServer):
"""Binds the CRM app to a loopback TCP port."""
allow_reuse_address = True
daemon_threads = True
def __init__(self, host, port, db_path, static_dir=STATIC_DIR):
self.app = CRMApp(Store(db_path), static_dir)
super().__init__((host, port), CRMRequestHandler)
def shutdown(self):
super().shutdown()
self.app.store.close()
def create_server(port=None, db_path=None, host=HOST):
return CRMServer(host, int(port), db_path)
def config_from_env(environ=None):
"""Read PORT and CRM_DB, with the documented defaults."""
environ = os.environ if environ is None else environ
raw_port = environ.get("PORT", str(DEFAULT_PORT))
try:
port = int(raw_port)
except ValueError:
raise SystemExit("PORT must be an integer, got %r" % raw_port)
return port, environ.get("CRM_DB", DEFAULT_DB)
def main(argv=None):
port, db_path = config_from_env()
server = create_server(port, db_path)
print(
"CRM listening on http://%s:%d (db: %s)"
% (server.server_address[0], server.server_address[1], db_path)
)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nshutting down")
finally:
server.shutdown()
if __name__ == "__main__":
main()
@@ -0,0 +1,414 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mini CRM</title>
<style>
:root {
--bg: #f5f6f8; --panel: #ffffff; --ink: #1e2430; --muted: #6b7480;
--line: #dfe3e9; --accent: #2f6feb; --danger: #c0392b; --radius: 8px;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink);
font: 15px/1.45 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { background: var(--panel); border-bottom: 1px solid var(--line);
padding: 12px 18px; display: flex; gap: 14px; align-items: center; flex-wrap: wrap; }
h1 { font-size: 18px; margin: 0; }
main { padding: 18px; display: grid; gap: 18px; }
section { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; }
h2 { font-size: 15px; margin: 0 0 10px; }
form { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; align-items: center; }
input, select, textarea, button { font: inherit; padding: 7px 9px; border: 1px solid var(--line);
border-radius: 6px; background: #fff; color: var(--ink); }
input[type="search"] { min-width: 260px; }
button { cursor: pointer; background: var(--accent); border-color: var(--accent); color: #fff; }
button.ghost { background: #fff; color: var(--ink); border-color: var(--line); }
button.danger { background: #fff; color: var(--danger); border-color: var(--line); }
ul { list-style: none; margin: 0; padding: 0; }
li { display: flex; gap: 10px; align-items: center; padding: 8px 0; border-top: 1px solid var(--line); }
li span.grow { flex: 1; }
.muted { color: var(--muted); font-size: 13px; }
.board { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 10px; }
.column { background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px; }
.column h3 { margin: 0 0 8px; font-size: 13px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
.card { background: #fff; border: 1px solid var(--line); border-radius: 6px; padding: 8px; margin-bottom: 8px; }
.card .actions { display: flex; gap: 6px; margin-top: 6px; }
.card .actions button { padding: 3px 7px; font-size: 12px; }
#status { color: var(--muted); font-size: 13px; }
#status.error { color: var(--danger); }
.editing { outline: 2px solid var(--accent); }
</style>
</head>
<body>
<header>
<h1>Mini CRM</h1>
<input id="search" type="search" placeholder="Search companies, contacts, deals" aria-label="Search">
<span id="status"></span>
</header>
<main>
<section>
<h2>Companies</h2>
<form id="company-form" data-resource="companies">
<input name="name" placeholder="Name" required maxlength="200">
<input name="website" placeholder="Website" maxlength="200">
<input name="industry" placeholder="Industry" maxlength="200">
<button type="submit">Save</button>
<button type="button" class="ghost" data-action="reset">Clear</button>
</form>
<ul id="companies"></ul>
</section>
<section>
<h2>Contacts</h2>
<form id="contact-form" data-resource="contacts">
<input name="name" placeholder="Name" required maxlength="200">
<input name="email" placeholder="Email" maxlength="200">
<input name="phone" placeholder="Phone" maxlength="200">
<select name="company_id"></select>
<button type="submit">Save</button>
<button type="button" class="ghost" data-action="reset">Clear</button>
</form>
<ul id="contacts"></ul>
</section>
<section>
<h2>Deals</h2>
<form id="deal-form" data-resource="deals">
<input name="title" placeholder="Title" required maxlength="200">
<input name="amount" placeholder="Amount" type="number" min="0" step="0.01" value="0">
<select name="stage"></select>
<select name="company_id"></select>
<select name="contact_id"></select>
<button type="submit">Save</button>
<button type="button" class="ghost" data-action="reset">Clear</button>
</form>
<div id="board" class="board"></div>
</section>
<section id="deal-panel" hidden>
<h2 id="deal-panel-title">Deal</h2>
<button type="button" class="ghost" id="deal-close">Close (Esc)</button>
<div id="deal-panel-meta" class="muted"></div>
<h3>Notes</h3>
<ul id="deal-notes"></ul>
<form id="note-form">
<input name="body" placeholder="Add a note" required maxlength="4000" style="flex:1">
<button type="submit">Add note</button>
</form>
<h3>Activity</h3>
<ul id="deal-activity"></ul>
</section>
</main>
<script>
"use strict";
const STAGES = ["lead", "qualified", "proposal", "won", "lost"];
const state = {
companies: [], contacts: [], deals: [], query: "", editing: {},
selectedDeal: null, notes: [], activity: []
};
function status(message, isError) {
const node = document.getElementById("status");
node.textContent = message || "";
node.className = isError ? "error" : "";
if (message) setTimeout(() => { if (node.textContent === message) node.textContent = ""; }, 4000);
}
async function api(path, options) {
const response = await fetch(path, Object.assign({ headers: { "Content-Type": "application/json" } }, options));
if (response.status === 204) return null;
const data = await response.json().catch(() => null);
if (!response.ok) throw new Error((data && data.error) || ("HTTP " + response.status));
return data;
}
function formValues(form) {
const values = {};
new FormData(form).forEach((value, key) => { values[key] = value; });
["company_id", "contact_id"].forEach((key) => {
if (key in values && values[key] === "") values[key] = null;
});
if ("amount" in values) values.amount = values.amount === "" ? 0 : Number(values.amount);
return values;
}
function fillForm(form, record) {
for (const field of form.elements) {
if (!field.name) continue;
const value = record ? record[field.name] : "";
field.value = value === null || value === undefined ? (field.name.endsWith("_id") ? "" : value === 0 ? 0 : "") : value;
}
}
function setEditing(resource, form, record) {
state.editing[resource] = record ? record.id : null;
fillForm(form, record || null);
form.classList.toggle("editing", Boolean(record));
form.querySelector("button[type=submit]").textContent = record ? "Update" : "Save";
}
async function load() {
const query = state.query ? "?q=" + encodeURIComponent(state.query) : "";
const [companies, contacts, deals] = await Promise.all([
api("/api/companies" + query), api("/api/contacts" + query), api("/api/deals" + query)
]);
state.companies = companies; state.contacts = contacts; state.deals = deals;
render();
}
function option(select, value, label) {
const node = document.createElement("option");
node.value = value; node.textContent = label;
select.appendChild(node);
}
function renderSelects() {
const stageSelect = document.querySelector('#deal-form [name="stage"]');
stageSelect.innerHTML = "";
STAGES.forEach((stage) => option(stageSelect, stage, stage));
for (const selector of ['#contact-form [name="company_id"]', '#deal-form [name="company_id"]']) {
const select = document.querySelector(selector);
const current = select.value;
select.innerHTML = "";
option(select, "", "no company");
state.companies.forEach((company) => option(select, company.id, company.name));
select.value = current;
}
const contactSelect = document.querySelector('#deal-form [name="contact_id"]');
const currentContact = contactSelect.value;
contactSelect.innerHTML = "";
option(contactSelect, "", "no contact");
state.contacts.forEach((contact) => option(contactSelect, contact.id, contact.name));
contactSelect.value = currentContact;
}
function makeRow(label, detail, actions) {
const row = document.createElement("li");
const text = document.createElement("span");
text.className = "grow";
text.textContent = label;
row.appendChild(text);
if (detail) {
const extra = document.createElement("span");
extra.className = "muted";
extra.textContent = detail;
row.appendChild(extra);
}
actions.forEach((action) => row.appendChild(action));
return row;
}
function actionButton(label, className, handler) {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.className = className;
button.addEventListener("click", handler);
return button;
}
function renderCompanies() {
const list = document.getElementById("companies");
list.innerHTML = "";
state.companies.forEach((company) => {
const form = document.getElementById("company-form");
list.appendChild(makeRow(company.name, [company.industry, company.website].filter(Boolean).join(" · "), [
actionButton("Edit", "ghost", () => setEditing("companies", form, company)),
actionButton("Delete", "danger", async () => {
await api("/api/companies/" + company.id, { method: "DELETE" });
status("Deleted company " + company.name);
await load();
})
]));
});
}
function renderContacts() {
const list = document.getElementById("contacts");
list.innerHTML = "";
state.contacts.forEach((contact) => {
const company = state.companies.find((item) => item.id === contact.company_id);
const form = document.getElementById("contact-form");
list.appendChild(makeRow(contact.name, [contact.email, contact.phone, company ? company.name : null].filter(Boolean).join(" · "), [
actionButton("Edit", "ghost", () => setEditing("contacts", form, contact)),
actionButton("Delete", "danger", async () => {
await api("/api/contacts/" + contact.id, { method: "DELETE" });
status("Deleted contact " + contact.name);
await load();
})
]));
});
}
function renderBoard() {
const board = document.getElementById("board");
board.innerHTML = "";
STAGES.forEach((stage) => {
const column = document.createElement("div");
column.className = "column";
const heading = document.createElement("h3");
const deals = state.deals.filter((deal) => deal.stage === stage);
const total = deals.reduce((sum, deal) => sum + Number(deal.amount || 0), 0);
heading.textContent = stage + " (" + deals.length + " · " + total.toFixed(2) + ")";
column.appendChild(heading);
deals.forEach((deal) => {
const card = document.createElement("div");
card.className = "card";
const title = document.createElement("div");
title.textContent = deal.title;
card.appendChild(title);
const meta = document.createElement("div");
meta.className = "muted";
const company = state.companies.find((item) => item.id === deal.company_id);
meta.textContent = Number(deal.amount || 0).toFixed(2) + (company ? " · " + company.name : "");
card.appendChild(meta);
const actions = document.createElement("div");
actions.className = "actions";
const form = document.getElementById("deal-form");
actions.appendChild(actionButton("Edit", "ghost", () => setEditing("deals", form, deal)));
actions.appendChild(actionButton("Delete", "danger", async () => {
await api("/api/deals/" + deal.id, { method: "DELETE" });
if (state.selectedDeal && state.selectedDeal.id === deal.id) closeDeal();
status("Deleted deal " + deal.title);
await load();
}));
actions.appendChild(actionButton("Notes", "ghost", () => openDeal(deal)));
card.appendChild(actions);
column.appendChild(card);
});
board.appendChild(column);
});
}
function render() {
renderSelects();
renderCompanies();
renderContacts();
renderBoard();
renderDealPanel();
}
function renderDealPanel() {
const panel = document.getElementById("deal-panel");
const deal = state.selectedDeal;
if (!deal) {
panel.hidden = true;
return;
}
panel.hidden = false;
document.getElementById("deal-panel-title").textContent = "Deal #" + deal.id + ": " + deal.title;
const company = state.companies.find((item) => item.id === deal.company_id);
const contact = state.contacts.find((item) => item.id === deal.contact_id);
document.getElementById("deal-panel-meta").textContent = [
deal.stage, Number(deal.amount || 0).toFixed(2),
company ? "company: " + company.name : null,
contact ? "contact: " + contact.name : null
].filter(Boolean).join(" · ");
const list = document.getElementById("deal-notes");
list.innerHTML = "";
state.notes.forEach((note) => {
list.appendChild(makeRow(note.body, note.created_at, []));
});
if (!state.notes.length) {
const empty = document.createElement("li");
empty.className = "muted";
empty.textContent = "No notes yet.";
list.appendChild(empty);
}
const activityList = document.getElementById("deal-activity");
activityList.innerHTML = "";
state.activity.forEach((entry) => {
activityList.appendChild(makeRow(entry.action + " " + entry.summary, entry.created_at, []));
});
if (!state.activity.length) {
const empty = document.createElement("li");
empty.className = "muted";
empty.textContent = "No activity yet.";
activityList.appendChild(empty);
}
}
async function openDeal(deal) {
state.selectedDeal = deal;
state.notes = await api("/api/deals/" + deal.id + "/notes");
state.activity = await api("/api/activity?deal_id=" + deal.id + "&limit=20");
renderDealPanel();
}
function closeDeal() {
state.selectedDeal = null;
state.notes = [];
state.activity = [];
renderDealPanel();
}
document.getElementById("note-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (!state.selectedDeal) return;
const form = event.target;
try {
const values = formValues(form);
await api("/api/deals/" + state.selectedDeal.id + "/notes", { method: "POST", body: JSON.stringify(values) });
form.reset();
await openDeal(state.selectedDeal);
status("Note added");
} catch (error) {
status(error.message, true);
}
});
document.getElementById("deal-close").addEventListener("click", closeDeal);
document.addEventListener("keydown", (event) => {
const target = event.target;
const typing = target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");
if (event.key === "/" && !typing) {
event.preventDefault();
document.getElementById("search").focus();
} else if (event.key === "Escape" && state.selectedDeal) {
closeDeal();
}
});
function wireForm(form, resource) {
form.addEventListener("submit", async (event) => {
event.preventDefault();
const values = formValues(form);
const id = state.editing[resource];
try {
if (id) {
await api("/api/" + resource + "/" + id, { method: "PUT", body: JSON.stringify(values) });
status("Updated " + resource.slice(0, -1));
} else {
await api("/api/" + resource, { method: "POST", body: JSON.stringify(values) });
status("Created " + resource.slice(0, -1));
}
setEditing(resource, form, null);
await load();
} catch (error) {
status(error.message, true);
}
});
form.querySelector('[data-action="reset"]').addEventListener("click", () => setEditing(resource, form, null));
}
let searchTimer = null;
document.getElementById("search").addEventListener("input", (event) => {
clearTimeout(searchTimer);
const value = event.target.value;
searchTimer = setTimeout(() => {
state.query = value.trim();
load().catch((error) => status(error.message, true));
}, 200);
});
wireForm(document.getElementById("company-form"), "companies");
wireForm(document.getElementById("contact-form"), "contacts");
wireForm(document.getElementById("deal-form"), "deals");
load().catch((error) => status(error.message, true));
</script>
</body>
</html>
@@ -0,0 +1 @@
"""Test package for the CRM application."""
@@ -0,0 +1,156 @@
"""Shared helpers: drive the real HTTP handler without opening a socket."""
import io
import json
import os
import shutil
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
import server as server_module # noqa: E402
class FakeSocket:
"""Stands in for a connected socket: feeds bytes in, captures bytes out."""
def __init__(self, request):
self.incoming = io.BytesIO(request)
self.outgoing = io.BytesIO()
def makefile(self, mode, bufsize=-1, *args, **kwargs):
return self.incoming if "r" in mode else self.outgoing
def close(self):
pass
def shutdown(self, *args, **kwargs):
pass
def sendall(self, data):
self.outgoing.write(data)
def send(self, data):
self.outgoing.write(data)
return len(data)
class FakeServer:
def __init__(self, app):
self.app = app
self.server_address = ("127.0.0.1", 0)
def log_message(self, fmt, *args):
pass
def log_error(self, fmt, *args):
pass
def log_request(self, *args):
pass
def raw_request(app, method, path, body=None, extra_headers=None):
"""Run one HTTP request through CRMRequestHandler and return the response."""
headers = {"Host": "127.0.0.1", "Connection": "close"}
payload = b""
if body is not None:
if isinstance(body, bytes):
payload = body
elif isinstance(body, str):
payload = body.encode("utf-8")
else:
payload = json.dumps(body).encode("utf-8")
headers["Content-Length"] = str(len(payload))
if payload and "Content-Type" not in (extra_headers or {}):
headers["Content-Type"] = "application/json"
headers.update(extra_headers or {})
lines = ["%s %s HTTP/1.1" % (method, path)]
lines.extend("%s: %s" % (key, value) for key, value in headers.items())
request = ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + payload
sock = FakeSocket(request)
server_module.CRMRequestHandler(sock, ("127.0.0.1", 1234), FakeServer(app))
raw = sock.outgoing.getvalue()
head, _, rest = raw.partition(b"\r\n\r\n")
status_line = head.split(b"\r\n")[0].decode("latin-1")
parts = status_line.split(" ", 2)
status = int(parts[1])
response_headers = {}
for line in head.split(b"\r\n")[1:]:
name, _, value = line.decode("latin-1").partition(":")
response_headers[name.strip().lower()] = value.strip()
length = int(response_headers.get("content-length", "0") or 0)
body_bytes = rest[:length]
data = None
if body_bytes and "application/json" in response_headers.get("content-type", ""):
data = json.loads(body_bytes.decode("utf-8"))
return status, data, response_headers, body_bytes
class ApiTestCase(unittest.TestCase):
"""Base class with a throwaway database per test."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix="crm-test-")
self.db_path = os.path.join(self.tmpdir, "crm.db")
self.store = server_module.Store(self.db_path)
self.app = server_module.CRMApp(self.store, static_dir=server_module.STATIC_DIR)
def tearDown(self):
self.store.close()
shutil.rmtree(self.tmpdir, ignore_errors=True)
def request_full(self, method, path, body=None, extra_headers=None):
"""Same as :meth:`request` but also returns the raw response bytes."""
return raw_request(self.app, method, path, body, extra_headers)
def request(self, method, path, body=None, extra_headers=None):
status, data, headers, _ = self.request_full(method, path, body, extra_headers)
return status, data, headers
def get(self, path):
status, data, headers, _ = self.request_full("GET", path)
return status, data, headers
def post(self, path, body=None, **kwargs):
status, data, _, _ = self.request_full("POST", path, body, **kwargs)
return status, data
def put(self, path, body=None):
status, data, _, _ = self.request_full("PUT", path, body)
return status, data
def delete(self, path):
status, data, _, _ = self.request_full("DELETE", path)
return status, data
def create(self, resource, payload):
status, data = self.post("/api/%s" % resource, payload)
self.assertEqual(status, 201, "could not create %s: %r" % (resource, data))
return data
def create_company(self, name="Acme", **extra):
payload = {"name": name}
payload.update(extra)
return self.create("companies", payload)
def create_contact(self, name="Ada", **extra):
payload = {"name": name}
payload.update(extra)
return self.create("contacts", payload)
def create_deal(self, title="Big deal", **extra):
payload = {"title": title}
payload.update(extra)
return self.create("deals", payload)
def assert_bad_request(self, status, data, path):
self.assertEqual(status, 400, "expected 400 from %s, got %s: %r" % (path, status, data))
self.assertIsInstance(data, dict)
self.assertTrue(data.get("error"))
@@ -0,0 +1,110 @@
"""Tests for the activity log and GET /api/activity."""
import unittest
from tests.base import ApiTestCase
class ActivityApiTest(ApiTestCase):
def entries(self, path="/api/activity"):
status, data, headers = self.get(path)
self.assertEqual(status, 200)
self.assertIsInstance(data, list)
return data, headers
def test_empty_log(self):
data, headers = self.entries()
self.assertEqual(data, [])
self.assertEqual(headers.get("x-total-count"), "0")
def test_create_update_delete_are_logged(self):
company = self.create_company("Acme")
self.put("/api/companies/%d" % company["id"], {"name": "Acme II"})
self.delete("/api/companies/%d" % company["id"])
data, headers = self.entries()
self.assertEqual(headers.get("x-total-count"), "3")
self.assertEqual([entry["action"] for entry in data], ["delete", "update", "create"])
for entry in data:
self.assertEqual(entry["entity"], "companies")
self.assertEqual(entry["entity_id"], company["id"])
self.assertIsNone(entry["deal_id"])
self.assertTrue(entry["created_at"])
self.assertEqual(data[0]["summary"], 'company "Acme II"')
self.assertEqual(data[2]["summary"], 'company "Acme"')
def test_every_resource_is_logged(self):
contact = self.create_contact("Ada")
deal = self.create_deal("Rollout")
self.put("/api/contacts/%d" % contact["id"], {"name": "Ada L"})
self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "won"})
data, _ = self.entries()
self.assertEqual(
[(entry["entity"], entry["action"]) for entry in data],
[("deals", "update"), ("contacts", "update"), ("deals", "create"), ("contacts", "create")],
)
self.assertEqual(data[0]["summary"], 'deal "Rollout"')
def test_notes_are_logged_against_their_deal(self):
deal = self.create_deal("Rollout")
other = self.create_deal("Other")
self.post("/api/deals/%d/notes" % deal["id"], {"body": "called the client"})
self.post("/api/deals/%d/notes" % other["id"], {"body": "unrelated"})
data, headers = self.entries()
self.assertEqual(headers.get("x-total-count"), "4")
note_entries = [entry for entry in data if entry["entity"] == "notes"]
self.assertEqual(len(note_entries), 2)
self.assertEqual(note_entries[0]["deal_id"], other["id"])
self.assertEqual(note_entries[1]["deal_id"], deal["id"])
self.assertEqual(note_entries[1]["summary"], 'note "called the client"')
def test_newest_first(self):
self.create_company("One")
self.create_company("Two")
data, _ = self.entries()
self.assertEqual([entry["summary"] for entry in data], ['company "Two"', 'company "One"'])
ids = [entry["id"] for entry in data]
self.assertEqual(ids, sorted(ids, reverse=True))
def test_limit_returns_newest_n(self):
for name in ("One", "Two", "Three"):
self.create_company(name)
data, headers = self.entries("/api/activity?limit=2")
self.assertEqual([entry["summary"] for entry in data], ['company "Three"', 'company "Two"'])
self.assertEqual(headers.get("x-total-count"), "3")
def test_offset_pages_back_in_time(self):
for name in ("One", "Two", "Three"):
self.create_company(name)
data, _ = self.entries("/api/activity?limit=1&offset=2")
self.assertEqual([entry["summary"] for entry in data], ['company "One"'])
def test_filter_by_deal(self):
deal = self.create_deal("Rollout")
self.post("/api/deals/%d/notes" % deal["id"], {"body": "first"})
self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "won"})
self.create_contact("Unrelated")
data, headers = self.entries("/api/activity?deal_id=%d" % deal["id"])
self.assertEqual([entry["action"] for entry in data], ["update", "create", "create"])
self.assertEqual(headers.get("x-total-count"), "3")
self.assertTrue(all(entry["deal_id"] == deal["id"] for entry in data))
def test_filter_by_entity(self):
self.create_company("One")
self.create_contact("Ada")
data, _ = self.entries("/api/activity?entity=contacts")
self.assertEqual([entry["entity"] for entry in data], ["contacts"])
def test_invalid_parameters_are_400(self):
for path in ("/api/activity?limit=x", "/api/activity?limit=-2", "/api/activity?deal_id=nope"):
status, payload, _ = self.get(path)
self.assertEqual(status, 400, path)
self.assertIn("error", payload)
def test_post_is_not_allowed(self):
status, payload = self.request_full("POST", "/api/activity", {})[:2]
self.assertEqual(status, 405)
self.assertIn("error", payload)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,123 @@
"""Tests for /api/companies."""
import unittest
from tests.base import ApiTestCase
class CompaniesApiTest(ApiTestCase):
def test_empty_list(self):
status, data, headers = self.get("/api/companies")
self.assertEqual(status, 200)
self.assertEqual(data, [])
self.assertEqual(headers.get("content-type"), "application/json")
def test_create_returns_201_and_id(self):
status, data = self.post(
"/api/companies", {"name": "Acme", "website": "acme.example", "industry": "tools"}
)
self.assertEqual(status, 201)
self.assertEqual(data["id"], 1)
self.assertEqual(data["name"], "Acme")
self.assertEqual(data["website"], "acme.example")
self.assertEqual(data["industry"], "tools")
def test_create_minimal_and_optional_defaults(self):
company = self.create_company("Only Name")
self.assertEqual(company["website"], "")
self.assertEqual(company["industry"], "")
def test_list_returns_all(self):
first = self.create_company("Acme")
second = self.create_company("Globex")
status, data, _ = self.get("/api/companies")
self.assertEqual(status, 200)
self.assertEqual([item["id"] for item in data], [first["id"], second["id"]])
def test_get_by_id(self):
company = self.create_company("Initech", industry="software")
status, data, _ = self.get("/api/companies/%d" % company["id"])
self.assertEqual(status, 200)
self.assertEqual(data["name"], "Initech")
self.assertEqual(data["industry"], "software")
def test_update_replaces_fields(self):
company = self.create_company("Umbrella", website="umbrella.example", industry="labs")
status, data = self.put("/api/companies/%d" % company["id"], {"name": "Umbrella Corp"})
self.assertEqual(status, 200)
self.assertEqual(data["id"], company["id"])
self.assertEqual(data["name"], "Umbrella Corp")
self.assertEqual(data["website"], "")
self.assertEqual(data["industry"], "")
status, reread, _ = self.get("/api/companies/%d" % company["id"])
self.assertEqual(reread["name"], "Umbrella Corp")
def test_delete_returns_204_and_removes(self):
company = self.create_company("Wonka")
status, data = self.delete("/api/companies/%d" % company["id"])
self.assertEqual(status, 204)
self.assertIsNone(data)
status, data, _ = self.get("/api/companies/%d" % company["id"])
self.assertEqual(status, 404)
self.assertIn("error", data)
status, listed, _ = self.get("/api/companies")
self.assertEqual(listed, [])
def test_search_is_case_insensitive_substring(self):
self.create_company("Acme Industries")
self.create_company("Globex")
status, data, _ = self.get("/api/companies?q=acme")
self.assertEqual(status, 200)
self.assertEqual([item["name"] for item in data], ["Acme Industries"])
status, data, _ = self.get("/api/companies?q=ME%20IND")
self.assertEqual([item["name"] for item in data], ["Acme Industries"])
status, data, _ = self.get("/api/companies?q=nothing")
self.assertEqual(data, [])
def test_unknown_id_is_404(self):
for method in ("GET", "PUT", "DELETE"):
if method == "PUT":
status, data = self.put("/api/companies/4242", {"name": "Ghost"})
else:
status, data, _ = self.request(method, "/api/companies/4242")
self.assertEqual(status, 404, method)
self.assertEqual(data, {"error": data["error"]})
self.assertTrue(data["error"])
def test_missing_name_is_400(self):
for payload in ({}, {"website": "x.example"}, {"name": ""}, {"name": " "}, {"name": None}):
status, data = self.post("/api/companies", payload)
self.assert_bad_request(status, data, "POST /api/companies %r" % (payload,))
def test_wrong_types_are_400(self):
for payload in (
{"name": 5},
{"name": True},
{"name": "ok", "website": 12},
{"name": "ok", "industry": ["a"]},
):
status, data = self.post("/api/companies", payload)
self.assert_bad_request(status, data, "POST /api/companies %r" % (payload,))
def test_invalid_json_body_is_400(self):
status, data, _ = self.request("POST", "/api/companies", "{not json")
self.assertEqual(status, 400)
self.assertIn("error", data)
def test_json_array_body_is_400(self):
status, data = self.post("/api/companies", [1, 2, 3])
self.assert_bad_request(status, data, "POST /api/companies")
def test_update_requires_name(self):
company = self.create_company("Hooli")
status, data = self.put("/api/companies/%d" % company["id"], {"website": "hooli.example"})
self.assert_bad_request(status, data, "PUT company")
def test_method_not_allowed(self):
status, data, _ = self.request("DELETE", "/api/companies")
self.assertEqual(status, 405)
self.assertIn("error", data)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,100 @@
"""Tests for /api/contacts."""
import unittest
from tests.base import ApiTestCase
class ContactsApiTest(ApiTestCase):
def test_empty_list(self):
status, data, _ = self.get("/api/contacts")
self.assertEqual(status, 200)
self.assertEqual(data, [])
def test_create_full_record(self):
company = self.create_company("Acme")
status, data = self.post(
"/api/contacts",
{
"name": "Ada Lovelace",
"email": "ada@acme.example",
"phone": "+1 555 0100",
"company_id": company["id"],
},
)
self.assertEqual(status, 201)
self.assertEqual(data["id"], 1)
self.assertEqual(data["name"], "Ada Lovelace")
self.assertEqual(data["email"], "ada@acme.example")
self.assertEqual(data["phone"], "+1 555 0100")
self.assertEqual(data["company_id"], company["id"])
def test_create_without_company(self):
contact = self.create_contact("Grace")
self.assertIsNone(contact["company_id"])
def test_get_update_delete(self):
contact = self.create_contact("Grace", email="grace@example.com")
status, data, _ = self.get("/api/contacts/%d" % contact["id"])
self.assertEqual(status, 200)
self.assertEqual(data["email"], "grace@example.com")
other = self.create_company("Raytheon")
status, data = self.put(
"/api/contacts/%d" % contact["id"],
{"name": "Grace Hopper", "email": "grace@raytheon.example", "company_id": other["id"]},
)
self.assertEqual(status, 200)
self.assertEqual(data["name"], "Grace Hopper")
self.assertEqual(data["company_id"], other["id"])
self.assertEqual(data["phone"], "")
status, _ = self.delete("/api/contacts/%d" % contact["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/contacts/%d" % contact["id"])
self.assertEqual(status, 404)
def test_search_matches_name_and_email(self):
self.create_contact("Ada Lovelace", email="ada@example.com")
self.create_contact("Alan Turing", email="alan@bletchley.example")
for query, expected in (
("ada", ["Ada Lovelace"]),
("ADA", ["Ada Lovelace"]),
("bletchley", ["Alan Turing"]),
("turing", ["Alan Turing"]),
("zzz", []),
):
status, data, _ = self.get("/api/contacts?q=%s" % query)
self.assertEqual(status, 200)
self.assertEqual([item["name"] for item in data], expected, query)
def test_missing_name_is_400(self):
for payload in ({}, {"name": ""}, {"name": 3}, {"email": "no-name@example.com"}):
status, data = self.post("/api/contacts", payload)
self.assert_bad_request(status, data, "POST /api/contacts %r" % (payload,))
def test_unknown_company_is_400(self):
status, data = self.post("/api/contacts", {"name": "Nobody", "company_id": 999})
self.assert_bad_request(status, data, "POST /api/contacts unknown company")
def test_unknown_id_is_404(self):
status, data, _ = self.get("/api/contacts/1234")
self.assertEqual(status, 404)
self.assertIn("error", data)
status, data = self.put("/api/contacts/1234", {"name": "Ghost"})
self.assertEqual(status, 404)
status, data = self.delete("/api/contacts/1234")
self.assertEqual(status, 404)
def test_deleting_company_clears_reference_but_keeps_contact(self):
company = self.create_company("Acme")
contact = self.create_contact("Ada", company_id=company["id"])
status, _ = self.delete("/api/companies/%d" % company["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/contacts/%d" % contact["id"])
self.assertEqual(status, 200)
self.assertIsNone(data["company_id"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
"""Tests for the CSV export endpoints."""
import csv
import io
import unittest
from tests.base import ApiTestCase
class CsvExportTest(ApiTestCase):
def download(self, path):
status, _, headers, body = self.request_full("GET", path)
self.assertEqual(status, 200)
self.assertTrue(headers.get("content-type", "").startswith("text/csv"), headers)
return list(csv.reader(io.StringIO(body.decode("utf-8"))))
def test_header_row_only_when_empty(self):
for resource, columns in (
("companies", ["id", "name", "website", "industry"]),
("contacts", ["id", "name", "email", "phone", "company_id"]),
("deals", ["id", "title", "amount", "stage", "company_id", "contact_id", "created_at"]),
):
rows = self.download("/api/%s.csv" % resource)
self.assertEqual(rows, [columns], resource)
def test_rows_match_the_api(self):
company = self.create_company("Acme", website="acme.example", industry="tools")
contact = self.create_contact("Ada", email="ada@acme.example", company_id=company["id"])
deal = self.create_deal("Rollout", amount=1500, stage="won", company_id=company["id"], contact_id=contact["id"])
rows = self.download("/api/companies.csv")
self.assertEqual(rows[1], [str(company["id"]), "Acme", "acme.example", "tools"])
rows = self.download("/api/contacts.csv")
self.assertEqual(rows[1], [str(contact["id"]), "Ada", "ada@acme.example", "", str(company["id"])])
rows = self.download("/api/deals.csv")
self.assertEqual(rows[1][:6], [str(deal["id"]), "Rollout", "1500.0", "won", str(company["id"]), str(contact["id"])])
def test_quoting_of_tricky_values(self):
self.create_company('Smith, Jane & "Associates"', industry="line\nbreak")
rows = self.download("/api/companies.csv")
self.assertEqual(len(rows), 2)
self.assertEqual(rows[1][1], 'Smith, Jane & "Associates"')
self.assertEqual(rows[1][3], "line\nbreak")
status, _, _, body = self.request_full("GET", "/api/companies.csv")
self.assertIn(b'"Smith, Jane & ""Associates"""', body)
def test_null_references_become_empty_cells(self):
self.create_contact("Solo")
rows = self.download("/api/contacts.csv")
self.assertEqual(rows[1], ["1", "Solo", "", "", ""])
def test_filters_apply(self):
self.create_deal("Alpha", stage="won")
self.create_deal("Beta", stage="lead")
rows = self.download("/api/deals.csv?stage=won")
self.assertEqual(len(rows), 2)
self.assertEqual(rows[1][1], "Alpha")
rows = self.download("/api/deals.csv?q=beta&stage=lead")
self.assertEqual(len(rows), 2)
self.assertEqual(rows[1][1], "Beta")
def test_pagination_applies(self):
for index in range(3):
self.create_company("C%d" % index)
rows = self.download("/api/companies.csv?limit=1&offset=1")
self.assertEqual(len(rows), 2)
self.assertEqual(rows[1][1], "C1")
def test_unknown_resource_is_404(self):
status, data, _ = self.get("/api/nope.csv")
self.assertEqual(status, 404)
self.assertIn("error", data)
def test_wrong_method_is_405(self):
status, data = self.request_full("POST", "/api/companies.csv", {})[:2]
self.assertEqual(status, 405)
self.assertIn("error", data)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,150 @@
"""Tests for /api/deals."""
import unittest
from tests.base import ApiTestCase
STAGES = ("lead", "qualified", "proposal", "won", "lost")
class DealsApiTest(ApiTestCase):
def test_empty_list(self):
status, data, _ = self.get("/api/deals")
self.assertEqual(status, 200)
self.assertEqual(data, [])
def test_create_defaults(self):
status, data = self.post("/api/deals", {"title": "First deal"})
self.assertEqual(status, 201)
self.assertEqual(data["title"], "First deal")
self.assertEqual(data["amount"], 0)
self.assertEqual(data["stage"], "lead")
self.assertIsNone(data["company_id"])
self.assertIsNone(data["contact_id"])
def test_create_full_record(self):
company = self.create_company("Acme")
contact = self.create_contact("Ada", company_id=company["id"])
status, data = self.post(
"/api/deals",
{
"title": "Enterprise rollout",
"amount": 12500.5,
"stage": "proposal",
"company_id": company["id"],
"contact_id": contact["id"],
},
)
self.assertEqual(status, 201)
self.assertEqual(data["amount"], 12500.5)
self.assertEqual(data["stage"], "proposal")
self.assertEqual(data["company_id"], company["id"])
self.assertEqual(data["contact_id"], contact["id"])
def test_every_stage_is_accepted(self):
for index, stage in enumerate(STAGES):
status, data = self.post("/api/deals", {"title": "Deal %d" % index, "stage": stage})
self.assertEqual(status, 201, stage)
self.assertEqual(data["stage"], stage)
def test_invalid_stage_is_400_on_create(self):
for stage in ("closed", "Lead", "", " ", None, 3):
if stage is None:
continue # absent stage falls back to the default
status, data = self.post("/api/deals", {"title": "Bad stage", "stage": stage})
self.assert_bad_request(status, data, "POST deal stage=%r" % (stage,))
def test_invalid_stage_is_400_on_update(self):
deal = self.create_deal("Move me")
status, data = self.put("/api/deals/%d" % deal["id"], {"title": "Move me", "stage": "someday"})
self.assert_bad_request(status, data, "PUT deal stage")
status, current, _ = self.get("/api/deals/%d" % deal["id"])
self.assertEqual(current["stage"], "lead")
def test_update_moves_stage_and_amount(self):
deal = self.create_deal("Negotiation", amount=100)
status, data = self.put("/api/deals/%d" % deal["id"], {"title": "Negotiation", "amount": 250, "stage": "won"})
self.assertEqual(status, 200)
self.assertEqual(data["stage"], "won")
self.assertEqual(data["amount"], 250)
def test_missing_title_is_400(self):
for payload in ({}, {"title": ""}, {"title": 7}, {"amount": 10}):
status, data = self.post("/api/deals", payload)
self.assert_bad_request(status, data, "POST /api/deals %r" % (payload,))
def test_bad_amount_is_400(self):
for amount in ("1000", -1, -0.01, "abc", True, [5]):
status, data = self.post("/api/deals", {"title": "Bad amount", "amount": amount})
self.assert_bad_request(status, data, "POST deal amount=%r" % (amount,))
def test_zero_amount_is_allowed(self):
status, data = self.post("/api/deals", {"title": "Free trial", "amount": 0})
self.assertEqual(status, 201)
self.assertEqual(data["amount"], 0)
def test_stage_filter(self):
self.create_deal("A", stage="won")
self.create_deal("B", stage="lead")
self.create_deal("C", stage="won")
status, data, _ = self.get("/api/deals?stage=won")
self.assertEqual(status, 200)
self.assertEqual([item["title"] for item in data], ["A", "C"])
def test_text_filter_matches_title(self):
self.create_deal("Alpha contract")
self.create_deal("Beta renewal")
status, data, _ = self.get("/api/deals?q=beta")
self.assertEqual([item["title"] for item in data], ["Beta renewal"])
def test_stage_and_text_filters_combine(self):
self.create_deal("Alpha win", stage="won")
self.create_deal("Alpha loss", stage="lost")
self.create_deal("Gamma win", stage="won")
status, data, _ = self.get("/api/deals?stage=won&q=alpha")
self.assertEqual(status, 200)
self.assertEqual([item["title"] for item in data], ["Alpha win"])
def test_unknown_id_is_404(self):
status, data, _ = self.get("/api/deals/777")
self.assertEqual(status, 404)
self.assertIn("error", data)
status, data = self.put("/api/deals/777", {"title": "Ghost"})
self.assertEqual(status, 404)
status, data = self.delete("/api/deals/777")
self.assertEqual(status, 404)
def test_delete_deal(self):
deal = self.create_deal("Doomed")
status, _ = self.delete("/api/deals/%d" % deal["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/deals")
self.assertEqual(data, [])
def test_deleting_company_keeps_deal_and_clears_reference(self):
company = self.create_company("Acme")
deal = self.create_deal("Kept", company_id=company["id"])
status, _ = self.delete("/api/companies/%d" % company["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/deals/%d" % deal["id"])
self.assertEqual(status, 200)
self.assertIsNone(data["company_id"])
def test_deleting_contact_keeps_deal_and_clears_reference(self):
contact = self.create_contact("Ada")
deal = self.create_deal("Kept", contact_id=contact["id"])
status, _ = self.delete("/api/contacts/%d" % contact["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/deals/%d" % deal["id"])
self.assertEqual(status, 200)
self.assertIsNone(data["contact_id"])
def test_unknown_references_are_400(self):
status, data = self.post("/api/deals", {"title": "Bad refs", "company_id": 404})
self.assert_bad_request(status, data, "unknown company_id")
status, data = self.post("/api/deals", {"title": "Bad refs", "contact_id": "x"})
self.assert_bad_request(status, data, "non integer contact_id")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,115 @@
"""End-to-end checks against a real listening server.
These are skipped automatically when the environment forbids opening a
listening socket (for example inside a restrictive sandbox); every endpoint is
also covered by the in-process tests in the other modules.
"""
import json
import os
import shutil
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
from tests.base import ROOT # noqa: F401 (adds the project root to sys.path)
import server as server_module
def _start_server(db_path):
return server_module.create_server(0, db_path)
class LiveServerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmpdir = tempfile.mkdtemp(prefix="crm-live-")
try:
cls.server = _start_server(os.path.join(cls.tmpdir, "live.db"))
except (PermissionError, OSError) as exc:
shutil.rmtree(cls.tmpdir, ignore_errors=True)
raise unittest.SkipTest("cannot open a listening socket: %s" % exc)
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.thread.start()
cls.base = "http://127.0.0.1:%d" % cls.server.server_address[1]
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.thread.join(timeout=5)
cls.server.server_close()
shutil.rmtree(cls.tmpdir, ignore_errors=True)
def call(self, method, path, payload=None):
data = None if payload is None else json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
self.base + path,
data=data,
method=method,
headers={"Content-Type": "application/json"} if data else {},
)
try:
with urllib.request.urlopen(request, timeout=10) as response:
body = response.read()
status = response.status
except urllib.error.HTTPError as exc:
body = exc.read()
status = exc.code
parsed = json.loads(body.decode("utf-8")) if body else None
return status, parsed
def test_full_round_trip(self):
status, company = self.call("POST", "/api/companies", {"name": "Live Co", "industry": "tests"})
self.assertEqual(status, 201)
self.assertGreater(company["id"], 0)
status, contact = self.call(
"POST", "/api/contacts", {"name": "Ada", "email": "ada@live.example", "company_id": company["id"]}
)
self.assertEqual(status, 201)
status, deal = self.call(
"POST", "/api/deals", {"title": "Live deal", "amount": 500, "company_id": company["id"]}
)
self.assertEqual(status, 201)
status, note = self.call("POST", "/api/deals/%d/notes" % deal["id"], {"body": "kickoff"})
self.assertEqual(status, 201)
status, notes = self.call("GET", "/api/deals/%d/notes" % deal["id"])
self.assertEqual(status, 200)
self.assertEqual([item["body"] for item in notes], ["kickoff"])
status, deals = self.call("GET", "/api/deals?stage=lead&q=live")
self.assertEqual(status, 200)
self.assertEqual(len(deals), 1)
status, pipeline = self.call("GET", "/api/pipeline")
self.assertEqual(status, 200)
self.assertEqual(pipeline["lead"]["count"], 1)
self.assertEqual(pipeline["lead"]["amount"], 500)
status, updated = self.call("PUT", "/api/deals/%d" % deal["id"], {"title": "Live deal", "stage": "won", "amount": 500})
self.assertEqual(status, 200)
self.assertEqual(updated["stage"], "won")
status, _ = self.call("DELETE", "/api/companies/%d" % company["id"])
self.assertEqual(status, 204)
status, deals = self.call("GET", "/api/deals")
self.assertEqual(len(deals), 1)
self.assertIsNone(deals[0]["company_id"])
def test_index_and_errors(self):
with urllib.request.urlopen(self.base + "/", timeout=10) as response:
self.assertEqual(response.status, 200)
self.assertIn("text/html", response.headers.get("Content-Type", ""))
with self.assertRaises(urllib.error.HTTPError) as ctx:
urllib.request.urlopen(self.base + "/api/companies/424242", timeout=10)
self.assertEqual(ctx.exception.code, 404)
self.assertIn("error", json.loads(ctx.exception.read().decode("utf-8")))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,65 @@
"""Tests for GET/POST /api/deals/{id}/notes."""
import unittest
from tests.base import ApiTestCase
class NotesApiTest(ApiTestCase):
def test_empty_notes(self):
deal = self.create_deal("Noted")
status, data, headers = self.get("/api/deals/%d/notes" % deal["id"])
self.assertEqual(status, 200)
self.assertEqual(data, [])
self.assertEqual(headers.get("content-type"), "application/json")
def test_create_note_returns_201(self):
deal = self.create_deal("Noted")
status, data = self.post("/api/deals/%d/notes" % deal["id"], {"body": "Called the client"})
self.assertEqual(status, 201)
self.assertEqual(data["deal_id"], deal["id"])
self.assertEqual(data["body"], "Called the client")
self.assertIsInstance(data["id"], int)
self.assertTrue(data["created_at"])
def test_notes_are_listed_in_order_and_scoped_to_deal(self):
first = self.create_deal("One")
second = self.create_deal("Two")
self.post("/api/deals/%d/notes" % first["id"], {"body": "one-a"})
self.post("/api/deals/%d/notes" % second["id"], {"body": "two-a"})
self.post("/api/deals/%d/notes" % first["id"], {"body": "one-b"})
status, data, _ = self.get("/api/deals/%d/notes" % first["id"])
self.assertEqual([note["body"] for note in data], ["one-a", "one-b"])
status, data, _ = self.get("/api/deals/%d/notes" % second["id"])
self.assertEqual([note["body"] for note in data], ["two-a"])
def test_body_is_required(self):
deal = self.create_deal("Noted")
for payload in (None, {}, {"body": ""}, {"body": " "}, {"body": 5}, {"note": "x"}):
status, data = self.post("/api/deals/%d/notes" % deal["id"], payload)
self.assert_bad_request(status, data, "POST notes %r" % (payload,))
def test_unknown_deal_is_404(self):
status, data, _ = self.get("/api/deals/999/notes")
self.assertEqual(status, 404)
self.assertIn("error", data)
status, data = self.post("/api/deals/999/notes", {"body": "hello"})
self.assertEqual(status, 404)
def test_notes_route_rejects_other_methods(self):
deal = self.create_deal("Noted")
status, data, _ = self.request("DELETE", "/api/deals/%d/notes" % deal["id"])
self.assertEqual(status, 405)
self.assertIn("error", data)
def test_deleting_deal_removes_its_notes(self):
deal = self.create_deal("Doomed")
self.post("/api/deals/%d/notes" % deal["id"], {"body": "bye"})
status, _ = self.delete("/api/deals/%d" % deal["id"])
self.assertEqual(status, 204)
status, data, _ = self.get("/api/deals/%d/notes" % deal["id"])
self.assertEqual(status, 404)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,87 @@
"""Tests for ?limit=N&offset=M and the X-Total-Count header."""
import unittest
from tests.base import ApiTestCase
class PaginationTest(ApiTestCase):
def setUp(self):
super().setUp()
for index in range(1, 6):
self.create_company("Company %d" % index)
def test_default_returns_everything(self):
status, data, headers = self.get("/api/companies")
self.assertEqual(status, 200)
self.assertEqual(len(data), 5)
self.assertEqual(headers.get("x-total-count"), "5")
def test_limit(self):
status, data, headers = self.get("/api/companies?limit=2")
self.assertEqual(status, 200)
self.assertEqual([item["name"] for item in data], ["Company 1", "Company 2"])
self.assertEqual(headers.get("x-total-count"), "5")
def test_offset(self):
status, data, headers = self.get("/api/companies?offset=3")
self.assertEqual(status, 200)
self.assertEqual([item["name"] for item in data], ["Company 4", "Company 5"])
self.assertEqual(headers.get("x-total-count"), "5")
def test_limit_and_offset(self):
status, data, headers = self.get("/api/companies?limit=2&offset=2")
self.assertEqual(status, 200)
self.assertEqual([item["name"] for item in data], ["Company 3", "Company 4"])
self.assertEqual(headers.get("x-total-count"), "5")
def test_offset_past_the_end(self):
status, data, headers = self.get("/api/companies?limit=2&offset=99")
self.assertEqual(status, 200)
self.assertEqual(data, [])
self.assertEqual(headers.get("x-total-count"), "5")
def test_total_counts_filters(self):
self.create_company("Other")
status, data, headers = self.get("/api/companies?q=company&limit=2")
self.assertEqual(len(data), 2)
self.assertEqual(headers.get("x-total-count"), "5")
def test_contacts_and_deals_are_paginated(self):
for index in range(3):
self.create_contact("Contact %d" % index)
self.create_deal("Deal %d" % index, stage="won" if index == 2 else "lead")
status, data, headers = self.get("/api/contacts?limit=1")
self.assertEqual(len(data), 1)
self.assertEqual(headers.get("x-total-count"), "3")
status, data, headers = self.get("/api/deals?stage=lead&limit=1&offset=1")
self.assertEqual([item["title"] for item in data], ["Deal 1"])
self.assertEqual(headers.get("x-total-count"), "2")
def test_notes_are_paginated(self):
deal = self.create_deal("Noted")
for index in range(4):
self.post("/api/deals/%d/notes" % deal["id"], {"body": "note %d" % index})
status, data, headers = self.get("/api/deals/%d/notes?limit=2&offset=1" % deal["id"])
self.assertEqual(status, 200)
self.assertEqual([note["body"] for note in data], ["note 1", "note 2"])
self.assertEqual(headers.get("x-total-count"), "4")
status, data, headers = self.get("/api/deals/%d/notes" % deal["id"])
self.assertEqual(len(data), 4)
self.assertEqual(headers.get("x-total-count"), "4")
def test_invalid_values_are_400(self):
for path in (
"/api/companies?limit=abc",
"/api/companies?limit=-1",
"/api/companies?offset=-5",
"/api/companies?offset=x",
"/api/deals?limit=1.5",
):
status, data, _ = self.get(path)
self.assertEqual(status, 400, path)
self.assertIn("error", data)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,54 @@
"""Tests for GET /api/pipeline."""
import unittest
from tests.base import ApiTestCase
STAGES = ("lead", "qualified", "proposal", "won", "lost")
class PipelineApiTest(ApiTestCase):
def test_empty_pipeline_has_every_stage(self):
status, data, headers = self.get("/api/pipeline")
self.assertEqual(status, 200)
self.assertEqual(headers.get("content-type"), "application/json")
self.assertEqual(sorted(data), sorted(STAGES))
for stage in STAGES:
self.assertEqual(data[stage], {"count": 0, "amount": 0})
def test_counts_and_totals(self):
self.create_deal("A", amount=100, stage="lead")
self.create_deal("B", amount=250.5, stage="lead")
self.create_deal("C", amount=900, stage="won")
status, data, _ = self.get("/api/pipeline")
self.assertEqual(status, 200)
self.assertEqual(data["lead"], {"count": 2, "amount": 350.5})
self.assertEqual(data["won"], {"count": 1, "amount": 900})
self.assertEqual(data["qualified"]["count"], 0)
self.assertEqual(data["proposal"]["amount"], 0)
self.assertEqual(data["lost"]["count"], 0)
def test_pipeline_ignores_filters(self):
self.create_deal("Alpha", amount=10, stage="won")
status, data, _ = self.get("/api/pipeline?stage=lead&q=zzz")
self.assertEqual(status, 200)
self.assertEqual(data["won"]["count"], 1)
def test_pipeline_reflects_updates_and_deletes(self):
deal = self.create_deal("Moving", amount=42, stage="lead")
self.put("/api/deals/%d" % deal["id"], {"title": "Moving", "amount": 42, "stage": "lost"})
status, data, _ = self.get("/api/pipeline")
self.assertEqual(data["lead"]["count"], 0)
self.assertEqual(data["lost"], {"count": 1, "amount": 42})
self.delete("/api/deals/%d" % deal["id"])
status, data, _ = self.get("/api/pipeline")
self.assertEqual(data["lost"]["count"], 0)
def test_pipeline_rejects_post(self):
status, data, _ = self.request("POST", "/api/pipeline", {})
self.assertEqual(status, 405)
self.assertIn("error", data)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,123 @@
"""Tests for the hardening fixes: body limits, error mapping, atomic logging."""
import contextlib
import io
import sqlite3
import unittest
from tests.base import ApiTestCase
import handlers
class BodyLimitTest(ApiTestCase):
def test_oversized_body_is_rejected(self):
original = handlers.MAX_BODY_BYTES
handlers.MAX_BODY_BYTES = 64
try:
status, data = self.post("/api/companies", {"name": "x" * 200})
self.assertEqual(status, 413)
self.assertIn("larger than 64 bytes", data["error"])
finally:
handlers.MAX_BODY_BYTES = original
def test_body_at_the_limit_is_accepted(self):
original = handlers.MAX_BODY_BYTES
handlers.MAX_BODY_BYTES = 4096
try:
status, _ = self.post("/api/companies", {"name": "y" * 200})
self.assertEqual(status, 201)
finally:
handlers.MAX_BODY_BYTES = original
def test_negative_content_length_is_400(self):
status, data, _ = self.request_full("POST", "/api/companies", {}, {"Content-Length": "-5"})[:3]
self.assertEqual(status, 400)
self.assertIn("Content-Length", data["error"])
def test_non_numeric_content_length_is_400(self):
status, data, _ = self.request_full("POST", "/api/companies", {}, {"Content-Length": "many"})[:3]
self.assertEqual(status, 400)
self.assertIn("Content-Length", data["error"])
class ErrorMappingTest(ApiTestCase):
def silence(self):
return contextlib.redirect_stderr(io.StringIO())
def test_unexpected_errors_do_not_leak_internals(self):
def boom(*args, **kwargs):
raise sqlite3.OperationalError("no such table: secret_internal_stuff")
self.store.list = boom
with self.silence():
status, data, _ = self.get("/api/companies")
self.assertEqual(status, 500)
self.assertEqual(data, {"error": "internal server error"})
self.assertNotIn("secret_internal_stuff", str(data))
def test_integrity_conflicts_answer_409(self):
def boom(*args, **kwargs):
raise sqlite3.IntegrityError("UNIQUE constraint failed")
self.store.create = boom
with self.silence():
status, data = self.post("/api/companies", {"name": "Conflict"})
self.assertEqual(status, 409)
self.assertEqual(data, {"error": "the change conflicts with existing data"})
def test_known_errors_keep_their_status(self):
with self.silence():
status, data, _ = self.get("/api/companies/4242")
self.assertEqual(status, 404)
self.assertIn("error", data)
class AtomicActivityTest(ApiTestCase):
def activity_for(self, entity, entity_id):
entries, _total = self.store.list_activity(entity=entity)
return [entry for entry in entries if entry["entity_id"] == entity_id]
def test_each_mutation_writes_exactly_one_entry(self):
company = self.create_company("Acme")
self.assertEqual(len(self.activity_for("companies", company["id"])), 1)
self.put("/api/companies/%d" % company["id"], {"name": "Acme II"})
self.assertEqual(len(self.activity_for("companies", company["id"])), 2)
self.delete("/api/companies/%d" % company["id"])
self.assertEqual(len(self.activity_for("companies", company["id"])), 3)
def test_rejected_request_leaves_no_trace(self):
deal = self.create_deal("Rollout")
before = len(self.activity_for("deals", deal["id"]))
self.put("/api/deals/%d" % deal["id"], {"title": "Rollout", "stage": "bogus"})
self.assertEqual(len(self.activity_for("deals", deal["id"])), before)
def test_failed_database_write_rolls_back_the_log(self):
company = self.create_company("Acme")
contact = self.create_contact("Ada", company_id=company["id"])
before = len(self.activity_for("contacts", contact["id"]))
with self.assertRaises(sqlite3.IntegrityError):
self.store.update("contacts", contact["id"], {"company_id": 999}, log_action="update")
self.assertEqual(len(self.activity_for("contacts", contact["id"])), before)
stored = self.store.get("contacts", contact["id"])
self.assertEqual(stored["company_id"], company["id"])
def test_note_and_its_log_entry_are_written_together(self):
deal = self.create_deal("Rollout")
self.post("/api/deals/%d/notes" % deal["id"], {"body": "kickoff"})
notes, _total = self.store.list_notes(deal["id"])
entries = self.activity_for("notes", notes[0]["id"])
self.assertEqual(len(notes), 1)
self.assertEqual(len(entries), 1)
self.assertEqual(entries[0]["deal_id"], deal["id"])
def test_failed_mutation_leaves_no_transaction_open(self):
company = self.create_company("Acme")
contact = self.create_contact("Ada", company_id=company["id"])
with self.assertRaises(sqlite3.IntegrityError):
self.store.update("contacts", contact["id"], {"company_id": 999}, log_action="update")
self.assertFalse(self.store.conn.in_transaction)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,101 @@
"""Tests for the front-end route, unknown routes and server configuration."""
import os
import unittest
from tests.base import ApiTestCase
import server as server_module
class StaticRoutesTest(ApiTestCase):
def test_root_serves_single_page_app(self):
status, _, headers, body = self.request_full("GET", "/")
self.assertEqual(status, 200)
self.assertTrue(headers.get("content-type", "").startswith("text/html"))
self.assertIn(b"<html", body.lower())
self.assertIn(b"/api/companies", body)
def test_static_files_are_served(self):
status, _, headers, body = self.request_full("GET", "/static/index.html")
self.assertEqual(status, 200)
self.assertTrue(headers.get("content-type", "").startswith("text/html"))
def test_front_end_wires_every_feature(self):
_, _, _, body = self.request_full("GET", "/")
text = body.decode("utf-8")
for marker in (
'id="search"',
'id="board"',
'id="companies"',
'id="contacts"',
'id="deal-panel"',
'id="deal-notes"',
'id="deal-activity"',
"/api/activity?deal_id=",
'event.key === "/"',
):
self.assertIn(marker, text)
def test_unknown_path_is_404(self):
status, data, _ = self.request("GET", "/nope")
self.assertEqual(status, 404)
self.assertIn("error", data)
def test_unknown_api_route_is_404(self):
for path in ("/api", "/api/nope", "/api/companies/1/extra", "/api/deals/1/notes/2"):
status, data, _ = self.request("GET", path)
self.assertEqual(status, 404, path)
self.assertIn("error", data)
def test_non_numeric_id_is_404(self):
status, data, _ = self.request("GET", "/api/companies/not-a-number")
self.assertEqual(status, 404)
self.assertIn("error", data)
def test_path_traversal_is_blocked(self):
status, _, _, _ = self.request_full("GET", "/static/../server.py")
self.assertEqual(status, 404)
def test_post_to_static_route_is_405(self):
status, data, _ = self.request("POST", "/", {})
self.assertEqual(status, 405)
self.assertIn("error", data)
class ConfigurationTest(unittest.TestCase):
def test_defaults(self):
port, db_path = server_module.config_from_env({})
self.assertEqual(port, 8000)
self.assertEqual(db_path, "crm.db")
def test_environment_overrides(self):
port, db_path = server_module.config_from_env({"PORT": "8123", "CRM_DB": "/tmp/x.db"})
self.assertEqual(port, 8123)
self.assertEqual(db_path, "/tmp/x.db")
def test_bad_port_is_rejected(self):
with self.assertRaises(SystemExit):
server_module.config_from_env({"PORT": "nope"})
def test_server_binds_loopback(self):
self.assertEqual(server_module.HOST, "127.0.0.1")
def test_schema_is_created_on_first_start(self):
import sqlite3
import tempfile
path = os.path.join(tempfile.mkdtemp(prefix="crm-schema-"), "nested", "crm.db")
store = server_module.Store(path)
store.close()
names = {
row[0]
for row in sqlite3.connect(path).execute(
"SELECT name FROM sqlite_master WHERE type = 'table'"
)
}
self.assertTrue({"companies", "contacts", "deals", "notes"} <= names)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,212 @@
"""Unit tests for the shared validation helpers and the rules they enforce."""
import os
import tempfile
import unittest
from errors import NotFoundError, ValidationError
from tests.base import ApiTestCase
import validation
class CleanTextTest(unittest.TestCase):
def test_required(self):
for value in (None, "", " "):
with self.assertRaises(ValidationError) as ctx:
validation.clean_text(value, "name", required=True)
self.assertIn("name is required", str(ctx.exception))
def test_optional_becomes_empty_string(self):
for value in (None, "", " "):
self.assertEqual(validation.clean_text(value, "website"), "")
def test_value_is_trimmed(self):
self.assertEqual(validation.clean_text(" Acme ", "name", required=True), "Acme")
def test_types(self):
for value in (5, 5.5, True, False, ["a"], {"a": 1}, object()):
with self.assertRaises(ValidationError) as ctx:
validation.clean_text(value, "name", required=True)
self.assertIn("must be a string", str(ctx.exception))
def test_length_limit_is_200_for_names(self):
self.assertEqual(validation.MAX_TEXT_LEN, 200)
self.assertEqual(len(validation.clean_text("a" * 200, "name", required=True)), 200)
with self.assertRaises(ValidationError) as ctx:
validation.clean_text("a" * 201, "name", required=True)
self.assertIn("at most 200 characters", str(ctx.exception))
def test_length_limit_applies_to_optional_fields_too(self):
with self.assertRaises(ValidationError):
validation.clean_text("b" * 201, "website")
def test_custom_max_length_for_notes(self):
self.assertEqual(validation.MAX_NOTE_LEN, 4000)
self.assertEqual(
len(validation.clean_text("n" * 4000, "body", required=True, max_len=validation.MAX_NOTE_LEN)),
4000,
)
with self.assertRaises(ValidationError):
validation.clean_text("n" * 4001, "body", required=True, max_len=validation.MAX_NOTE_LEN)
class CleanEmailTest(unittest.TestCase):
def test_valid_shapes(self):
for value in ("ada@example.com", "a.b+c@sub.domain.co.uk", "x_y@example.io"):
self.assertEqual(validation.clean_email(value), value)
self.assertEqual(validation.clean_email(None), "")
self.assertEqual(validation.clean_email(""), "")
def test_invalid_shapes(self):
for value in ("ada", "ada@", "@example.com", "ada@example", "ada @example.com", "a@@b.com", "ada@.com"):
with self.assertRaises(ValidationError) as ctx:
validation.clean_email(value)
self.assertIn("not a valid email address", str(ctx.exception))
def test_wrong_type(self):
with self.assertRaises(ValidationError):
validation.clean_email(7)
def test_length_limit(self):
with self.assertRaises(ValidationError):
validation.clean_email("a" * 200 + "@example.com")
class CleanAmountTest(unittest.TestCase):
def test_default(self):
self.assertEqual(validation.clean_amount(None), 0.0)
def test_numbers(self):
self.assertEqual(validation.clean_amount(0), 0.0)
self.assertEqual(validation.clean_amount(10), 10.0)
self.assertEqual(validation.clean_amount(10.5), 10.5)
def test_negative_is_rejected(self):
for value in (-1, -0.01, -1000):
with self.assertRaises(ValidationError) as ctx:
validation.clean_amount(value)
self.assertIn("greater than or equal to 0", str(ctx.exception))
def test_non_numbers_are_rejected(self):
for value in ("10", "", "abc", True, None if False else [1], {"v": 1}):
with self.assertRaises(ValidationError) as ctx:
validation.clean_amount(value)
self.assertIn("must be a number", str(ctx.exception))
class CleanStageTest(unittest.TestCase):
def test_default_when_absent(self):
self.assertEqual(validation.clean_stage(None, ("lead", "won"), default="lead"), "lead")
def test_allowed_stages(self):
for stage in ("lead", "qualified", "proposal", "won", "lost"):
self.assertEqual(validation.clean_stage(stage, (stage), "stage", "lead"), stage)
def test_unknown_stage(self):
for value in ("closed", "Lead", "", " ", "won "):
with self.assertRaises(ValidationError) as ctx:
validation.clean_stage(value, ("lead", "won"), "stage", "lead")
self.assertIn("stage must be one of", str(ctx.exception))
def test_wrong_type(self):
for value in (1, True, ["lead"]):
with self.assertRaises(ValidationError):
validation.clean_stage(value, ("lead",), "stage", "lead")
class CleanReferenceTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.mkdtemp(prefix="crm-validate-")
import db
self.store = db.Store(os.path.join(self.directory, "v.db"))
self.created = self.store.create("companies", {"name": "Acme", "website": "", "industry": ""})
def tearDown(self):
self.store.close()
def test_absent_is_none(self):
for value in (None, ""):
self.assertIsNone(validation.clean_reference(self.store, value, "companies", "company_id"))
def test_existing_reference(self):
self.assertEqual(
validation.clean_reference(self.store, self.created["id"], "companies", "company_id"),
self.created["id"],
)
def test_unknown_reference(self):
with self.assertRaises(ValidationError) as ctx:
validation.clean_reference(self.store, 4242, "companies", "company_id", "company")
self.assertIn("does not reference an existing company", str(ctx.exception))
def test_wrong_type(self):
for value in ("1", 1.5, True, [1]):
with self.assertRaises(ValidationError) as ctx:
validation.clean_reference(self.store, value, "companies", "company_id")
self.assertIn("must be an integer", str(ctx.exception))
class BodyAndParamTest(unittest.TestCase):
def test_require_object(self):
self.assertEqual(validation.require_object({"a": 1}), {"a": 1})
for value in (None, [], "text", 5):
with self.assertRaises(ValidationError):
validation.require_object(value)
def test_parse_id(self):
self.assertEqual(validation.parse_id("7"), 7)
for value in ("x", "", "-1", "0", None, "1.5"):
with self.assertRaises(NotFoundError):
validation.parse_id(value)
def test_parse_int_param(self):
self.assertEqual(validation.parse_int_param("5", "limit", 0), 5)
self.assertEqual(validation.parse_int_param("0", "offset", 0), 0)
with self.assertRaises(ValidationError):
validation.parse_int_param("-1", "limit", 0)
with self.assertRaises(ValidationError):
validation.parse_int_param("x", "limit", 0)
with self.assertRaises(ValidationError):
validation.parse_int_param("1.5", "limit", 0)
class RulesAreEnforcedThroughTheApiTest(ApiTestCase):
"""The handlers must use the shared helpers, not their own checks."""
def test_name_length_limit(self):
status, data = self.post("/api/companies", {"name": "a" * 200})
self.assertEqual(status, 201)
status, data = self.post("/api/companies", {"name": "a" * 201})
self.assert_bad_request(status, data, "company name too long")
self.assertIn("200 characters", data["error"])
deal = self.create_deal("t" * 200)
status, data = self.put("/api/deals/%d" % deal["id"], {"title": "t" * 201})
self.assert_bad_request(status, data, "deal title too long")
def test_email_shape(self):
status, _ = self.post("/api/contacts", {"name": "Ada", "email": "ada@example.com"})
self.assertEqual(status, 201)
for email in ("ada", "ada@example", "@example.com"):
status, data = self.post("/api/contacts", {"name": "Ada", "email": email})
self.assert_bad_request(status, data, "email %r" % email)
self.assertIn("valid email", data["error"])
def test_amount_rules(self):
status, _ = self.post("/api/deals", {"title": "Free", "amount": 0})
self.assertEqual(status, 201)
for amount in (-1, "100", True):
status, data = self.post("/api/deals", {"title": "Bad", "amount": amount})
self.assert_bad_request(status, data, "amount %r" % (amount,))
def test_note_length_limit(self):
deal = self.create_deal("Noted")
status, _ = self.post("/api/deals/%d/notes" % deal["id"], {"body": "n" * 4000})
self.assertEqual(status, 201)
status, data = self.post("/api/deals/%d/notes" % deal["id"], {"body": "n" * 4001})
self.assert_bad_request(status, data, "note too long")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,98 @@
"""Input validation helpers shared by every handler."""
import re
from errors import NotFoundError, ValidationError
MAX_TEXT_LEN = 200
MAX_NOTE_LEN = 4000
EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$")
def clean_text(value, field, required=False, max_len=MAX_TEXT_LEN):
"""Validate an optional text field and return a trimmed string."""
if value is None:
if required:
raise ValidationError("%s is required" % field)
return ""
if isinstance(value, bool) or not isinstance(value, str):
raise ValidationError("%s must be a string" % field)
text = value.strip()
if not text:
if required:
raise ValidationError("%s is required" % field)
return ""
if len(text) > max_len:
raise ValidationError("%s must be at most %d characters" % (field, max_len))
return text
def clean_email(value, field="email"):
"""Validate an optional email address."""
text = clean_text(value, field)
if text and not EMAIL_RE.match(text):
raise ValidationError("%s is not a valid email address" % field)
return text
def clean_amount(value, field="amount"):
"""Validate an optional non-negative number, defaulting to 0."""
if value is None:
return 0.0
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValidationError("%s must be a number" % field)
amount = float(value)
if amount < 0:
raise ValidationError("%s must be greater than or equal to 0" % field)
return amount
def clean_stage(value, stages, field="stage", default=None):
"""Validate a deal stage, defaulting when the key is absent."""
if value is None:
return default
if isinstance(value, bool) or not isinstance(value, str) or value not in stages:
raise ValidationError("%s must be one of: %s" % (field, ", ".join(stages)))
return value
def clean_reference(store, value, table, field, entity="record"):
"""Validate an optional foreign key against an existing row."""
if value is None or value == "":
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValidationError("%s must be an integer" % field)
if not store.exists(table, value):
raise ValidationError("%s does not reference an existing %s" % (field, entity))
return value
def require_object(body):
"""Accept only a parsed JSON object as a request body."""
if body is None:
raise ValidationError("request body is required")
if not isinstance(body, dict):
raise ValidationError("request body must be a JSON object")
return body
def parse_id(raw_id):
"""Parse a record id taken from the URL."""
try:
value = int(raw_id)
except (TypeError, ValueError):
raise NotFoundError("invalid id %r" % (raw_id,))
if value < 1:
raise NotFoundError("invalid id %r" % (raw_id,))
return value
def parse_int_param(raw_value, field, minimum):
"""Parse an integer query parameter such as limit or offset."""
try:
value = int(raw_value)
except (TypeError, ValueError):
raise ValidationError("%s must be an integer" % field)
if value < minimum:
raise ValidationError("%s must be greater than or equal to %d" % (field, minimum))
return value
+38
View File
@@ -0,0 +1,38 @@
---
id: crm
title: Small CRM web app (two phases)
kind: create
expected_rounds: 60-110
---
# Small CRM web app (two phases)
Existing task of docs/e2e-run.md (jobs 945*), prompt text unchanged from `scripts/e2e/codex/prompt-crm.txt` (sha256 2ab4d92db393334f1ac953086116cefb9744b522b98bfd4ea6efd7e02e319af9 of the file). Empty seed. Acceptance: `accept.py` = `crm_acceptance.py` (21 checks, REST API plus the app's own unittest suite) run on a copy of the workspace.
## Prompt
<!-- PROMPT BEGIN -->
Build a small CRM web application in the current directory using ONLY Python 3 standard library modules (http.server, sqlite3, json, unittest, urllib): there is no network and no package can be installed.
Layout and commands (fixed, an acceptance script will rely on them):
- server.py: running `python3 server.py` starts an HTTP server on the port in the environment variable PORT (default 8000), bound to 127.0.0.1, with data stored in the SQLite file given by the environment variable CRM_DB (default crm.db). It creates the tables on first start.
- tests/: a unittest suite; `python3 -m unittest discover -s tests` must run offline and pass. Cover every endpoint.
- README.md: how to run, the API, and the data model.
- static/index.html (served at GET /): a single-page front-end (plain HTML + JavaScript, no libraries) with a companies list, a contacts list, a deals board with one column per stage, a search box that filters the lists, and forms to create, edit and delete records and to add notes to a deal.
REST API (JSON bodies and responses, Content-Type application/json):
- Resources: /api/companies (name required, website, industry), /api/contacts (name required, email, phone, company_id optional), /api/deals (title required, amount number default 0, stage, company_id optional, contact_id optional), notes: GET and POST /api/deals/{id}/notes (body required).
- For each of companies, contacts, deals: GET /api/<r> lists all records (supports ?q=text, a case-insensitive substring filter on the name/title/email fields, and for deals also ?stage=<stage>); POST /api/<r> creates and returns 201 with the record including its integer id; GET /api/<r>/{id}; PUT /api/<r>/{id} replaces the editable fields and returns 200 with the record; DELETE /api/<r>/{id} returns 204. Unknown ids return 404 with {"error": "..."}; invalid input returns 400 with {"error": "..."}.
- Deal stages are exactly: lead, qualified, proposal, won, lost (default lead). PUT with another stage value returns 400. Deleting a company or contact must not delete deals; it clears the reference.
- GET /api/deals?stage=won&q=... combines both filters. GET /api/pipeline returns {"lead": {"count": n, "amount": total}, ...} for every stage.
Work step by step, run the tests and fix failures. When all tests pass and the server starts and answers the API, reply with a short summary.
Phase 2 (start only after phase 1 passes; keep every phase-1 behaviour and endpoint unchanged, the acceptance script re-runs them). This phase is a long refactor-and-extend job, work through it item by item and re-run the whole test suite after every item. Before editing a file read all of it; before you change behaviour read the tests that cover it.
1. Split server.py into modules (for example db.py, models.py, handlers.py, router.py) while `python3 server.py` keeps working with the same environment variables.
2. Pagination: every list endpoint accepts ?limit=N&offset=M (defaults unchanged when absent) and returns the total count in an X-Total-Count header.
3. CSV export: GET /api/companies.csv, /api/contacts.csv, /api/deals.csv with a header row and proper quoting.
4. An activity log table written on every create, update and delete, and GET /api/activity?limit=N returning the newest entries first.
5. Input validation helpers shared by all handlers, with unit tests for every rule (types, lengths up to 200 characters for names, email shape, amount >= 0).
6. Front-end: add a deal detail panel showing notes and the activity of that deal, and a keyboard shortcut / to focus the search box.
7. Write CODE_REVIEW.md: read every source and test file once more, list the weaknesses you find, fix the three most important ones, and document them.
When everything passes, reply with a short summary.
<!-- PROMPT END -->
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Acceptance for debuglog-sched. Usage: python3 accept.py WORKSPACE
Exit 0 = every check passed. The workspace is copied to private temporary directories first and is
never modified. Standard library only; runs on Python 3.9 .. 3.14.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
HIDDEN = os.path.join(HERE, "hidden")
RESULTS = []
def record(ok, name, detail=""):
RESULTS.append(bool(ok))
print(("PASS %s" % name) if ok else ("FAIL %s :: %s" % (name, " ".join(str(detail).split())[:400])))
def run(cmd, cwd, timeout=300):
env = dict(os.environ)
env.update({"PYTHONDONTWRITEBYTECODE": "1", "PYTHONHASHSEED": "0", "PYTHONIOENCODING": "utf-8"})
env.pop("PYTHONPATH", None)
try:
proc = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
except subprocess.TimeoutExpired:
return 124, "timed out after %ds" % timeout
return proc.returncode, proc.stdout.decode("utf-8", "replace")
def unittest_run(cwd, *extra):
code, out = run([sys.executable, "-m", "unittest", "discover", "-s", "tests"] + list(extra), cwd)
m = re.search(r"Ran (\d+) tests?", out)
return code, (int(m.group(1)) if m else 0), out
def tail(out, n=5):
return " | ".join([l for l in out.splitlines() if l.strip()][-n:])
def replace_tree(src, dst):
shutil.rmtree(dst, ignore_errors=True)
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__"))
def main():
if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]):
print("usage: accept.py WORKSPACE", file=sys.stderr)
return 2
workspace = os.path.abspath(sys.argv[1])
tmp = tempfile.mkdtemp(prefix="accept-debuglog-sched-")
try:
ignore = shutil.ignore_patterns("__pycache__", ".git", "*.pyc", ".pytest_cache")
root = os.path.join(tmp, "ws")
shutil.copytree(workspace, root, ignore=ignore)
evaluate(root, tmp, ignore)
finally:
shutil.rmtree(tmp, ignore_errors=True)
failed = RESULTS.count(False)
print("%d checks, %d failed" % (len(RESULTS), failed))
return 1 if failed else 0
def evaluate(root, tmp, ignore):
if not os.path.isdir(os.path.join(root, "sched")):
record(False, "layout", "no sched/ package in the workspace")
return
# 1. the original unit tests still pass on the agent's code
probe = os.path.join(tmp, "probe1")
shutil.copytree(root, probe, ignore=ignore)
replace_tree(os.path.join(HIDDEN, "tests"), os.path.join(probe, "tests"))
code, n, out = unittest_run(probe)
record(code == 0 and n >= 30, "original_tests_pass", "exit %s, %d tests: %s" % (code, n, tail(out)))
# 2. the regression test exists and passes on the fixed code
reg = os.path.join(root, "tests", "test_regression.py")
if not os.path.isfile(reg):
record(False, "regression_test_exists", "tests/test_regression.py is missing")
record(False, "regression_test_fails_on_original_code", "no regression test")
else:
code, n, out = unittest_run(root, "-p", "test_regression.py")
record(code == 0 and n >= 1, "regression_test_passes", "exit %s, %d tests: %s" % (code, n, tail(out)))
# 3. ... and it fails on the original code (same tests, pristine sched/)
probe = os.path.join(tmp, "probe2")
shutil.copytree(root, probe, ignore=ignore)
replace_tree(os.path.join(HIDDEN, "orig", "sched"), os.path.join(probe, "sched"))
code, n, out = unittest_run(probe, "-p", "test_regression.py")
broken = "Failed to import test module" in out or "ModuleNotFoundError" in out
record(
code != 0 and n >= 1 and not broken,
"regression_test_fails_on_original_code",
"exit %s, %d tests, import problem: %s: %s" % (code, n, broken, tail(out)),
)
# 4. hidden stress simulations with the pristine simulator driving the agent's service code
for name, jobs in (("a", 140000), ("b", 100000)):
probe = os.path.join(tmp, "stress_" + name)
shutil.copytree(root, probe, ignore=ignore)
shutil.copyfile(os.path.join(HIDDEN, "orig", "sched", "sim.py"), os.path.join(probe, "sched", "sim.py"))
code, out = run([sys.executable, "-B", os.path.join(HIDDEN, "stress.py"), probe, name], probe, timeout=240)
line = [l for l in out.splitlines() if l.startswith("{")]
if code != 0 or not line:
record(False, "stress_" + name, "exit %s: %s" % (code, tail(out)))
continue
s = json.loads(line[-1])
problems = []
if s["submitted"] != jobs:
problems.append("submitted %s of %d" % (s["submitted"], jobs))
if s["lost"]:
problems.append("%d jobs lost (e.g. %s)" % (s["lost"], s["lost_sample"]))
if s["duplicated"]:
problems.append("%d jobs ran or completed twice" % s["duplicated"])
if s["completed"] + s["dead"] != s["submitted"]:
problems.append("completed %d + dead %d != submitted %d" % (s["completed"], s["dead"], s["submitted"]))
record(not problems, "stress_" + name, "; ".join(problems))
# 5. FINDINGS.md
path = os.path.join(root, "FINDINGS.md")
if not os.path.isfile(path):
for n in ("findings_exists", "findings_names_file_and_function", "findings_explains_cause", "findings_cites_log_lines"):
record(False, n, "FINDINGS.md is missing")
return
with open(path, encoding="utf-8", errors="replace") as fh:
text = fh.read()
record(len(text.strip()) >= 300, "findings_exists", "only %d characters" % len(text.strip()))
record(
"ids.py" in text and re.search(r"next_id|IdGenerator", text) is not None,
"findings_names_file_and_function",
"must name ids.py and the function (next_id / IdGenerator)",
)
record(
re.search(r"wrap|overflow|roll-?over|reus|re-us|collid|collision|recycl|same id|duplicate id", text, re.I) is not None,
"findings_explains_cause",
"does not talk about wrap-around / id reuse / collision",
)
with open(os.path.join(HIDDEN, "evidence.json")) as fh:
evidence = json.load(fh)
keys = set()
def collect(node):
if isinstance(node, int):
keys.add(node)
elif isinstance(node, list):
for item in node:
collect(item)
elif isinstance(node, dict):
for key, item in node.items():
if key != "red_herrings":
collect(item)
collect(evidence)
cited = {int(x) for x in re.findall(r"(?<![\d.])(\d{3,5})(?!\d)", text)}
near = sorted(c for c in cited if any(abs(c - k) <= 2 for k in keys))
record(bool(near), "findings_cites_log_lines", "no cited line number is within 2 lines of the evidence (cited: %s)" % sorted(cited)[:12])
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Generate seed/logs/service.log (and hidden/evidence.json) by replaying a scripted incident through the seed code.
Run from anywhere: python3 gen_log.py
The log is the tail of a longer simulated run (about 4k jobs have already gone through when it
starts, so it begins in the middle of things): the id sequence wraps at j-fff, and four long-running
export jobs are still leased when their ids are handed out a second time. Two more incidents (a
stalled worker whose lease expires, and a job that fails three times) are unrelated red herrings.
"""
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "seed"))
from sched.sim import Sim, SimConfig # noqa: E402
LOG_FROM = 3796 # job number at which the excerpt starts (300 jobs before the id sequence wraps)
JOBS = LOG_FROM + 1500
def config():
return SimConfig(
jobs=JOBS,
seed=7,
workers=6,
slow_workers=3,
rate=1.8,
# exports that are already running when the excerpt starts: job number -> duration in seconds
planted={20: 2233.8, 163: 3300.0, 640: 2271.24},
stalls={4500: (0.5, 150.0)}, # a frozen worker: no heartbeat for 150 s
fail_plan={4350: 99}, # a job whose upstream keeps failing
keep_log=True,
log_from=LOG_FROM,
)
def main():
sim = Sim(config())
sim.run()
lines = sim.log.lines
out = os.path.join(HERE, "seed", "logs", "service.log")
os.makedirs(os.path.dirname(out), exist_ok=True)
with open(out, "w", newline="\n") as fh:
fh.write("\n".join(lines) + "\n")
def find(pattern, start=0):
rx = re.compile(pattern)
return [i for i, l in enumerate(lines, 1) if i > start and rx.search(l)]
key = {}
key["wrap_last"] = find(r"accepted job=j-fff ")[0]
key["wrap_first"] = find(r"accepted job=j-000 ")[0]
reused = {}
for jid in ("j-014", "j-0a3", "j-280", "j-3c7"):
accepted = find(r"accepted job=%s kind=(?!export)" % jid)
assert len(accepted) == 1, (jid, accepted)
symptom = find(r"job %s vanished|ack for unknown job %s|claim of unknown job %s" % (jid, jid, jid), accepted[0])
assert symptom, jid
reused[jid] = {"accepted": accepted[0], "symptom": symptom}
key["reused"] = reused
key["dedupe_swallow"] = [i for i in find(r"dedupe hit key=k-d3f091db") if i > reused["j-014"]["accepted"]]
key["ack_attempts0"] = find(r"ack job=j-014 worker=w4 attempts=0")
key["claim_dropped"] = find(r"claim of unknown job j-014")
key["ack_unknown"] = find(r"ack for unknown job j-280")
key["vanished"] = find(r"vanished: lease expired while running")
key["red_herrings"] = {
"lease_expired": find(r"lease expired job=j-194"),
"dead": find(r"dead after 3 attempts"),
}
with open(os.path.join(HERE, "hidden", "evidence.json"), "w", newline="\n") as fh:
json.dump(key, fh, indent=1, sort_keys=True)
size = os.path.getsize(out)
print("%d lines, %d bytes" % (len(lines), size))
print(json.dumps(key, sort_keys=True))
if __name__ == "__main__":
main()
@@ -0,0 +1,55 @@
{
"ack_attempts0": [
1000
],
"ack_unknown": [
3055
],
"claim_dropped": [
1009
],
"dedupe_swallow": [
1496
],
"red_herrings": {
"dead": [
1974,
3364
],
"lease_expired": [
2857
]
},
"reused": {
"j-014": {
"accepted": 986,
"symptom": [
1009
]
},
"j-0a3": {
"accepted": 1456,
"symptom": [
1655
]
},
"j-280": {
"accepted": 2870,
"symptom": [
3055
]
},
"j-3c7": {
"accepted": 3991,
"symptom": [
4058
]
}
},
"vanished": [
1655,
4058
],
"wrap_first": 928,
"wrap_last": 927
}
@@ -0,0 +1 @@
"""A small lease-based job scheduler with a deterministic simulator."""
@@ -0,0 +1,24 @@
from datetime import datetime, timedelta
EPOCH = datetime(2024, 5, 14, 6, 0, 0)
class VirtualClock:
"""Simulated time in seconds since EPOCH; only the simulator moves it."""
def __init__(self, start=0.0):
self._now = start
def now(self):
return self._now
def advance_to(self, t):
if t < self._now:
raise ValueError("clock cannot go backwards: %.3f < %.3f" % (t, self._now))
self._now = t
def format_ts(t):
ms = int(round(t * 1000))
stamp = EPOCH + timedelta(milliseconds=ms)
return stamp.strftime("%Y-%m-%d %H:%M:%S") + ".%03d" % (ms % 1000)
@@ -0,0 +1,24 @@
class Deduper:
"""Remembers idempotency keys for a while so client retries do not create second jobs."""
def __init__(self, window):
self.window = window
self._seen = {}
def lookup(self, key, now):
entry = self._seen.get(key)
if entry is not None and now - entry[1] <= self.window:
return entry[0]
return None
def remember(self, key, job_id, now):
self._seen[key] = (job_id, now)
def prune(self, now):
stale = [k for k, (_job, ts) in self._seen.items() if now - ts > self.window]
for key in stale:
del self._seen[key]
return len(stale)
def __len__(self):
return len(self._seen)
@@ -0,0 +1,15 @@
"""Job id generation."""
ID_BITS = 12 # three hex digits keep ids short enough to read out on a support call
ID_MASK = (1 << ID_BITS) - 1
class IdGenerator:
"""Hands out ids like j-0a3, one per accepted job."""
def __init__(self, start=0):
self._seq = start & ID_MASK
def next_id(self):
self._seq = (self._seq + 1) & ID_MASK
return "j-%03x" % self._seq
@@ -0,0 +1,38 @@
class Lease:
def __init__(self, job_id, worker, expires):
self.job_id = job_id
self.worker = worker
self.expires = expires
class LeaseTable:
"""Who is working on which job, and until when."""
def __init__(self, ttl):
self.ttl = ttl
self._leases = {}
def grant(self, job_id, worker, now):
lease = Lease(job_id, worker, now + self.ttl)
self._leases[job_id] = lease
return lease
def renew(self, job_id, now):
lease = self._leases.get(job_id)
if lease is None:
return False
lease.expires = now + self.ttl
return True
def release(self, job_id):
return self._leases.pop(job_id, None)
def expired(self, now):
return [lease for lease in self._leases.values() if lease.expires <= now]
def holder(self, job_id):
lease = self._leases.get(job_id)
return lease.worker if lease else None
def __len__(self):
return len(self._leases)
@@ -0,0 +1,24 @@
from .clock import format_ts
class Log:
"""Collects log lines stamped with the virtual clock."""
def __init__(self, clock, enabled=True):
self.clock = clock
self.enabled = enabled
self.lines = []
def _emit(self, level, comp, msg, args):
if self.enabled:
text = msg % args if args else msg
self.lines.append("%s %-5s %-8s %s" % (format_ts(self.clock.now()), level, comp, text))
def info(self, comp, msg, *args):
self._emit("INFO", comp, msg, args)
def warn(self, comp, msg, *args):
self._emit("WARN", comp, msg, args)
def error(self, comp, msg, *args):
self._emit("ERROR", comp, msg, args)
@@ -0,0 +1,34 @@
class Metrics:
"""Counters plus a queue depth gauge that is kept by hand and reconciled on flush."""
def __init__(self, log):
self.log = log
self.counters = {}
self.depth = 0
def inc(self, name, n=1):
self.counters[name] = self.counters.get(name, 0) + n
def get(self, name):
return self.counters.get(name, 0)
def flush(self, actual_depth, leased):
if self.depth != actual_depth:
self.log.warn(
"metrics",
"queue_depth counter drifted (counter=%d actual=%d), reconciling",
self.depth,
actual_depth,
)
self.depth = actual_depth
self.log.info(
"metrics",
"queue_depth=%d leased=%d submitted=%d done=%d dead=%d retries=%d dedupe_hits=%d",
actual_depth,
leased,
self.get("submitted"),
self.get("done"),
self.get("dead"),
self.get("retries"),
self.get("dedupe_hits"),
)
@@ -0,0 +1,21 @@
from dataclasses import dataclass, field
from typing import Optional
QUEUED = "queued"
LEASED = "leased"
RETRY_WAIT = "retry_wait"
DONE = "done"
DEAD = "dead"
@dataclass
class Job:
id: str
kind: str
payload: dict
key: str
client: str
created_at: float
status: str = QUEUED
attempts: int = 0
worker: Optional[str] = None
@@ -0,0 +1,35 @@
from collections import deque
class JobQueue:
"""FIFO queue with one lane per job kind; workers pop from the lanes they serve."""
def __init__(self):
self._lanes = {}
self._seq = 0
self._size = 0
def push(self, job_id, kind):
self._seq += 1
self._lanes.setdefault(kind, deque()).append((self._seq, job_id))
self._size += 1
def pop(self, kinds):
"""Oldest queued job id among the given kinds, or None."""
best = None
for kind in kinds:
lane = self._lanes.get(kind)
if lane and (best is None or lane[0][0] < self._lanes[best][0][0]):
best = kind
if best is None:
return None
self._size -= 1
return self._lanes[best].popleft()[1]
def depth(self, kind=None):
if kind is None:
return self._size
return len(self._lanes.get(kind, ()))
def __len__(self):
return self._size
@@ -0,0 +1,14 @@
class RetryPolicy:
"""Exponential backoff with a cap."""
def __init__(self, max_attempts=3, base=2.0, factor=2.0, cap=30.0):
self.max_attempts = max_attempts
self.base = base
self.factor = factor
self.cap = cap
def delay(self, attempt):
return min(self.cap, self.base * self.factor ** (attempt - 1))
def exhausted(self, attempts):
return attempts >= self.max_attempts
@@ -0,0 +1,158 @@
"""The scheduler service: submit, claim, heartbeat, ack/fail and the lease reaper."""
from .dedupe import Deduper
from .ids import IdGenerator
from .lease import LeaseTable
from .metrics import Metrics
from .model import DEAD, DONE, LEASED, QUEUED, RETRY_WAIT, Job
from .queue import JobQueue
from .retry import RetryPolicy
from .store import JobStore
class Scheduler:
def __init__(
self,
clock,
log,
lease_ttl=120.0,
dedupe_window=900.0,
policy=None,
call_later=None,
on_complete=None,
on_dead=None,
):
self.clock = clock
self.log = log
self.ids = IdGenerator()
self.store = JobStore()
self.queue = JobQueue()
self.leases = LeaseTable(lease_ttl)
self.dedupe = Deduper(dedupe_window)
self.policy = policy or RetryPolicy()
self.metrics = Metrics(log)
self.call_later = call_later
self.on_complete = on_complete
self.on_dead = on_dead
def submit(self, kind, payload, key, client):
"""Accept a job; a repeated key returns the id of the earlier submission."""
now = self.clock.now()
known = self.dedupe.lookup(key, now)
if known is not None:
self.metrics.inc("dedupe_hits")
self.log.info("service", "dedupe hit key=%s job=%s, not enqueued", key, known)
return known
job = Job(self.ids.next_id(), kind, payload, key, client, now)
self.store.put(job)
self.queue.push(job.id, kind)
self.dedupe.remember(key, job.id, now)
self.metrics.inc("submitted")
self.metrics.depth += 1
self.log.info("service", "accepted job=%s kind=%s client=%s key=%s", job.id, kind, client, key)
return job.id
def claim(self, worker, kinds):
"""Hand the oldest matching job to a worker and lease it."""
while True:
job_id = self.queue.pop(kinds)
if job_id is None:
return None
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "claim of unknown job %s by %s, dropped", job_id, worker)
continue
job.status = LEASED
job.worker = worker
job.attempts += 1
self.leases.grant(job.id, worker, self.clock.now())
self.metrics.depth -= 1
self.log.info(
"lease", "lease granted job=%s worker=%s ttl=%ds attempt=%d", job.id, worker, self.leases.ttl, job.attempts
)
return job
def heartbeat(self, job_id, worker):
"""Extend the lease of a running job; False means the job is gone."""
if self.store.get(job_id) is None:
return False
if not self.leases.renew(job_id, self.clock.now()):
return False
self.log.info("lease", "lease renewed job=%s worker=%s ttl=%ds", job_id, worker, self.leases.ttl)
return True
def ack(self, job_id, worker):
"""A worker finished a job: drop the record and report the completion."""
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "ack for unknown job %s worker=%s", job_id, worker)
return False
job.status = DONE
self.store.delete(job_id)
self.leases.release(job_id)
self.metrics.inc("done")
self.log.info("service", "ack job=%s worker=%s attempts=%d", job_id, worker, job.attempts)
if self.on_complete:
self.on_complete(job)
return True
def fail(self, job_id, worker, error):
"""A worker reports a failed attempt: retry with backoff or give up."""
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "failure report for unknown job %s worker=%s", job_id, worker)
return False
self.leases.release(job_id)
if self.policy.exhausted(job.attempts):
job.status = DEAD
self.store.delete(job_id)
self.metrics.inc("dead")
self.log.error("service", "job %s dead after %d attempts: %s", job_id, job.attempts, error)
if self.on_dead:
self.on_dead(job)
return False
delay = self.policy.delay(job.attempts)
job.status = RETRY_WAIT
self.metrics.inc("retries")
self.log.warn(
"service",
"job %s failed attempt=%d/%d: %s; retry in %.1fs",
job_id,
job.attempts,
self.policy.max_attempts,
error,
delay,
)
self.call_later(delay, lambda: self.requeue(job_id))
return True
def requeue(self, job_id):
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "requeue of unknown job %s", job_id)
return
job.status = QUEUED
job.worker = None
self.queue.push(job.id, job.kind)
self.log.info("service", "requeued job=%s attempt=%d", job.id, job.attempts + 1)
def reap(self):
"""Take back the jobs of workers that stopped renewing their lease."""
now = self.clock.now()
for lease in self.leases.expired(now):
self.leases.release(lease.job_id)
job = self.store.get(lease.job_id)
if job is None:
self.log.warn("lease", "expired lease for unknown job %s worker=%s", lease.job_id, lease.worker)
continue
self.metrics.inc("lease_expired")
self.log.warn(
"lease", "lease expired job=%s worker=%s, no heartbeat for %ds; requeued", job.id, lease.worker, self.leases.ttl
)
job.status = QUEUED
job.worker = None
self.queue.push(job.id, job.kind)
self.dedupe.prune(now)
def flush_metrics(self):
self.metrics.flush(len(self.queue), len(self.leases))
@@ -0,0 +1,270 @@
"""Deterministic discrete-event simulation of the scheduler.
A virtual clock drives clients that submit jobs, workers that run them and the housekeeping timers
of the service. Everything is seeded, so a configuration always produces the same run.
"""
import heapq
import itertools
import random
from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple
from .clock import VirtualClock
from .logs import Log
from .service import Scheduler
from .worker import Worker
FAST_KINDS = ("email", "thumbnail", "invoice")
SLOW_KINDS = ("export",)
ERRORS = {
"email": "TimeoutError: upstream mailer timed out after 5s",
"thumbnail": "OSError: image decoder failed",
"invoice": "ConnectionError: ledger api unavailable",
"export": "MemoryError: report too large",
}
@dataclass
class SimConfig:
jobs: int = 30000
seed: int = 1
workers: int = 3 # the last `slow_workers` of them serve only the export lane
slow_workers: int = 1
rate: float = 1.0 # new jobs per second
export_prob: float = 1 / 6000
export_min: float = 2400.0
export_max: float = 6000.0
fail_prob: float = 0.01 # first attempt fails, the retry succeeds
dead_prob: float = 0.0005 # every attempt fails
heavy_prob: float = 0.004 # fast jobs that take 10-40 s
dup_prob: float = 0.03 # client sends the same request twice
hb_interval: float = 40.0
lease_ttl: float = 120.0
planted: Dict[int, float] = field(default_factory=dict) # job number -> export duration
overrides: Dict[int, float] = field(default_factory=dict) # job number -> duration
stalls: Dict[int, Tuple[float, float]] = field(default_factory=dict) # job number -> (offset, length)
fail_plan: Dict[int, int] = field(default_factory=dict) # job number -> failing attempts
keep_log: bool = False
log_from: Optional[int] = None # keep log lines from the moment this job number is submitted
log_extra: float = 20.0 # seconds to keep going after the last submission when log_from is set
class Plan:
"""What the client submits and how the job will behave when a worker runs it."""
__slots__ = ("n", "kind", "payload", "key", "client", "dup_delay")
class Run:
__slots__ = ("token", "job", "start", "end", "stall")
def __init__(self, token, job, start, end, stall):
self.token = token
self.job = job
self.start = start
self.end = end
self.stall = stall
class Sim:
def __init__(self, cfg):
self.cfg = cfg
self.clock = VirtualClock()
self.log = Log(self.clock, enabled=cfg.keep_log and cfg.log_from is None)
self.rng_arrival = random.Random(cfg.seed)
self.rng_tie = random.Random(cfg.seed + 7919)
self._heap = []
self._seq = itertools.count()
self._tokens = itertools.count(1)
self._foreground = 0
self._arrived = 0
self._stop_at = None
self.service = Scheduler(
self.clock,
self.log,
lease_ttl=cfg.lease_ttl,
call_later=self.call_later,
on_complete=self._completed,
on_dead=self._dead,
)
fast = cfg.workers - cfg.slow_workers
self.workers = [Worker("w%d" % (i + 1), FAST_KINDS, self.service, self.log) for i in range(fast)]
self.workers += [Worker("w%d" % (fast + i + 1), SLOW_KINDS, self.service, self.log) for i in range(cfg.slow_workers)]
self.runs = {}
self.credits = {}
self.dead = {}
self.executed = {}
self.vanished = 0
self.events = 0
# ------------------------------------------------------------------ event loop
def at(self, t, fn, *args, background=False):
if not background:
self._foreground += 1
heapq.heappush(self._heap, (t, self.rng_tie.random(), next(self._seq), background, fn, args))
def call_later(self, delay, fn):
self.at(self.clock.now() + delay, fn)
def run(self):
self.at(0.0, self.arrive)
self.at(10.0, self.tick_reap, background=True)
self.at(30.0, self.tick_flush, background=True)
while self._heap:
t, _tie, _seq, background, fn, args = heapq.heappop(self._heap)
if not background:
self._foreground -= 1
elif self._foreground == 0:
break # only housekeeping timers are left
if self._stop_at is not None and t > self._stop_at:
break
self.clock.advance_to(t)
self.events += 1
fn(*args)
return self.summary()
# ------------------------------------------------------------------ clients
def plan(self, n):
cfg = self.cfg
r = random.Random(cfg.seed * 1000003 + n)
p = Plan()
p.n = n
if n in cfg.planted:
p.kind, dur = "export", cfg.planted[n]
elif r.random() < cfg.export_prob:
p.kind, dur = "export", r.uniform(cfg.export_min, cfg.export_max)
else:
pick = r.random()
p.kind = "email" if pick < 0.55 else ("thumbnail" if pick < 0.85 else "invoice")
dur = {"email": r.uniform(0.3, 1.6), "thumbnail": r.uniform(0.8, 3.0), "invoice": r.uniform(0.5, 2.0)}[p.kind]
if r.random() < cfg.heavy_prob:
dur = r.uniform(10.0, 40.0)
dur = cfg.overrides.get(n, dur)
roll = r.random()
fail = 1 if roll < cfg.fail_prob else (99 if roll > 1.0 - cfg.dead_prob else 0)
fail = cfg.fail_plan.get(n, fail)
p.payload = {"n": n, "dur": dur, "fail": fail}
p.key = "k-%08x" % ((n * 2654435761 + cfg.seed) & 0xFFFFFFFF)
p.client = "c%03d" % r.randrange(1, 400)
p.dup_delay = r.uniform(2.0, 40.0) if r.random() < cfg.dup_prob else None
return p
def arrive(self):
cfg = self.cfg
n = self._arrived + 1
self._arrived = n
if cfg.log_from is not None and n == cfg.log_from:
self.log.enabled = True
p = self.plan(n)
now = self.clock.now()
self.service.submit(p.kind, p.payload, p.key, p.client)
if p.dup_delay is not None:
self.at(now + p.dup_delay, self.resubmit, p)
if p.kind != "export":
self.at(now + 90.0, self.check_timeout, p)
if n < cfg.jobs:
self.at(now + self.rng_arrival.expovariate(cfg.rate), self.arrive)
elif cfg.log_from is not None:
self._stop_at = now + cfg.log_extra
self.dispatch()
def resubmit(self, p):
self.service.submit(p.kind, p.payload, p.key, p.client)
self.dispatch()
def check_timeout(self, p):
"""Clients that have seen no result after 90 s send the request again."""
if not self.executed.get(p.n) and not self.dead.get(p.n):
self.resubmit(p)
# ------------------------------------------------------------------ workers
def dispatch(self):
if not len(self.service.queue):
return
for w in self.workers:
if w.idle:
job = w.poll()
if job is not None:
self.start(w, job)
def start(self, w, job):
cfg = self.cfg
now = self.clock.now()
stall = cfg.stalls.get(job.payload["n"])
end = now + job.payload["dur"] + (stall[1] if stall else 0.0)
token = next(self._tokens)
self.runs[w.name] = Run(token, job, now, end, stall)
self.at(end, self.finish, w, token)
if end - now > cfg.hb_interval:
self.at(now + cfg.hb_interval, self.beat, w, token)
def beat(self, w, token):
run = self.runs.get(w.name)
if run is None or run.token != token:
return
now = self.clock.now()
frozen = run.stall is not None and run.start + run.stall[0] <= now < run.start + run.stall[0] + run.stall[1]
if not frozen and not w.heartbeat():
del self.runs[w.name]
self.vanished += 1
self.dispatch()
return
if now + self.cfg.hb_interval < run.end:
self.at(now + self.cfg.hb_interval, self.beat, w, token)
def finish(self, w, token):
run = self.runs.get(w.name)
if run is None or run.token != token:
return
del self.runs[w.name]
job = run.job
n = job.payload["n"]
if job.attempts <= job.payload["fail"]:
w.fail(ERRORS[job.kind])
else:
self.executed[n] = self.executed.get(n, 0) + 1
w.complete()
self.dispatch()
def _completed(self, job):
n = job.payload["n"]
self.credits[n] = self.credits.get(n, 0) + 1
def _dead(self, job):
n = job.payload["n"]
self.dead[n] = self.dead.get(n, 0) + 1
# ------------------------------------------------------------------ housekeeping
def tick_reap(self):
self.service.reap()
self.dispatch()
self.at(self.clock.now() + 10.0, self.tick_reap, background=True)
def tick_flush(self):
self.service.flush_metrics()
self.at(self.clock.now() + 30.0, self.tick_flush, background=True)
# ------------------------------------------------------------------ result
def summary(self):
n = self._arrived
lost = [i for i in range(1, n + 1) if not self.credits.get(i) and not self.dead.get(i)]
dup = [i for i in range(1, n + 1) if self.credits.get(i, 0) > 1 or self.executed.get(i, 0) > 1]
return {
"submitted": n,
"completed": sum(1 for i in range(1, n + 1) if self.credits.get(i)),
"dead": len(self.dead),
"lost": len(lost),
"lost_sample": lost[:5],
"duplicated": len(dup),
"vanished": self.vanished,
"lease_expired": self.service.metrics.get("lease_expired"),
"dedupe_hits": self.service.metrics.get("dedupe_hits"),
"virtual_seconds": round(self.clock.now(), 1),
"events": self.events,
}
@@ -0,0 +1,24 @@
class JobStore:
"""In-memory job records, keyed by job id."""
def __init__(self):
self._jobs = {}
def put(self, job):
# upsert: the retry path saves updated records through here as well
self._jobs[job.id] = job
def get(self, job_id):
return self._jobs.get(job_id)
def delete(self, job_id):
return self._jobs.pop(job_id, None)
def __contains__(self, job_id):
return job_id in self._jobs
def __len__(self):
return len(self._jobs)
def count(self, status):
return sum(1 for job in self._jobs.values() if job.status == status)
@@ -0,0 +1,55 @@
"""Worker side of the protocol: claim, heartbeat, then ack or fail."""
SLOW_SECONDS = 10.0
SLOW_SECONDS_BY_KIND = {"export": 7200.0}
class Worker:
def __init__(self, name, kinds, service, log):
self.name = name
self.kinds = tuple(kinds)
self.service = service
self.log = log
self.current = None
self.started_at = 0.0
@property
def idle(self):
return self.current is None
def poll(self):
"""Ask the scheduler for work; returns the claimed job or None."""
job = self.service.claim(self.name, self.kinds)
if job is not None:
self.current = job
self.started_at = self.service.clock.now()
return job
def heartbeat(self):
"""Renew the lease of the running job; abandon the job if the scheduler lost it."""
job = self.current
if self.service.heartbeat(job.id, self.name):
return True
self.log.error(
"worker",
"job %s vanished: lease expired while running (worker=%s kind=%s attempt=%d)",
job.id,
self.name,
job.kind,
job.attempts,
)
self.current = None
return False
def complete(self):
job = self.current
self.current = None
took = self.service.clock.now() - self.started_at
if took > SLOW_SECONDS_BY_KIND.get(job.kind, SLOW_SECONDS):
self.log.warn("worker", "slow job %s worker=%s kind=%s took %.1fs", job.id, self.name, job.kind, took)
return self.service.ack(job.id, self.name)
def fail(self, error):
job = self.current
self.current = None
return self.service.fail(job.id, self.name, error)
@@ -0,0 +1,28 @@
"""Hidden stress simulation: python3 stress.py WORKSPACE a|b -> one JSON line.
WORKSPACE is a private copy whose sched/sim.py has been replaced by the pristine simulator.
"""
import json
import sys
import time
sys.path.insert(0, sys.argv[1])
sys.dont_write_bytecode = True
from sched.sim import Sim, SimConfig # noqa: E402
CONFIGS = {
# three workers, one of them for exports; ids wrap about 34 times
"a": dict(jobs=140000, seed=11, workers=3, slow_workers=1, rate=1.0, export_prob=1 / 6000),
# five workers, two for exports, busier traffic and a different seed
"b": dict(jobs=100000, seed=29, workers=5, slow_workers=2, rate=1.8, export_prob=1 / 4000),
}
if __name__ == "__main__":
cfg = SimConfig(**CONFIGS[sys.argv[2]])
started = time.time()
summary = Sim(cfg).run()
summary["configured_jobs"] = cfg.jobs
summary["wall_seconds"] = round(time.time() - started, 1)
print(json.dumps(summary, sort_keys=True))
@@ -0,0 +1,16 @@
from sched.clock import VirtualClock
from sched.logs import Log
from sched.service import Scheduler
def make_scheduler(**kwargs):
clock = VirtualClock()
log = Log(clock)
later = []
sched = Scheduler(clock, log, call_later=lambda delay, fn: later.append((clock.now() + delay, fn)), **kwargs)
sched.pending = later
return sched
def submit(sched, n, kind="email"):
return sched.submit(kind, {"n": n}, "key-%d" % n, "c001")
@@ -0,0 +1,27 @@
import unittest
from sched.ids import IdGenerator
class IdGeneratorTests(unittest.TestCase):
def test_first_ids(self):
gen = IdGenerator()
self.assertEqual([gen.next_id() for _ in range(3)], ["j-001", "j-002", "j-003"])
def test_ids_are_hex(self):
gen = IdGenerator(start=0x0A2)
self.assertEqual(gen.next_id(), "j-0a3")
def test_ids_are_unique_for_a_while(self):
gen = IdGenerator()
ids = [gen.next_id() for _ in range(2000)]
self.assertEqual(len(set(ids)), 2000)
def test_ids_sort_in_creation_order_within_a_page(self):
gen = IdGenerator()
ids = [gen.next_id() for _ in range(200)]
self.assertEqual(ids, sorted(ids))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,59 @@
import unittest
from sched.dedupe import Deduper
from sched.lease import LeaseTable
from sched.retry import RetryPolicy
class LeaseTests(unittest.TestCase):
def test_grant_and_expiry(self):
leases = LeaseTable(ttl=120)
leases.grant("j-001", "w1", now=10.0)
self.assertEqual(leases.holder("j-001"), "w1")
self.assertEqual(leases.expired(129.9), [])
self.assertEqual([l.job_id for l in leases.expired(130.0)], ["j-001"])
def test_renew_pushes_expiry(self):
leases = LeaseTable(ttl=120)
leases.grant("j-001", "w1", now=0.0)
self.assertTrue(leases.renew("j-001", now=100.0))
self.assertEqual(leases.expired(200.0), [])
self.assertEqual(len(leases.expired(220.0)), 1)
def test_renew_unknown_and_release(self):
leases = LeaseTable(ttl=60)
self.assertFalse(leases.renew("j-404", now=0.0))
leases.grant("j-001", "w1", now=0.0)
self.assertIsNotNone(leases.release("j-001"))
self.assertEqual(len(leases), 0)
class DedupeTests(unittest.TestCase):
def test_hit_within_window(self):
d = Deduper(window=900)
d.remember("k1", "j-001", now=0.0)
self.assertEqual(d.lookup("k1", now=899.0), "j-001")
self.assertIsNone(d.lookup("k1", now=901.0))
self.assertIsNone(d.lookup("k2", now=1.0))
def test_prune(self):
d = Deduper(window=100)
d.remember("k1", "j-001", now=0.0)
d.remember("k2", "j-002", now=90.0)
self.assertEqual(d.prune(now=150.0), 1)
self.assertEqual(len(d), 1)
class RetryTests(unittest.TestCase):
def test_backoff_is_capped(self):
p = RetryPolicy(max_attempts=5, base=2.0, factor=2.0, cap=10.0)
self.assertEqual([p.delay(a) for a in (1, 2, 3, 4)], [2.0, 4.0, 8.0, 10.0])
def test_exhausted(self):
p = RetryPolicy(max_attempts=3)
self.assertFalse(p.exhausted(2))
self.assertTrue(p.exhausted(3))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,97 @@
import unittest
from helpers import make_scheduler, submit
from sched.model import LEASED, RETRY_WAIT
class ServiceTests(unittest.TestCase):
def test_submit_claim_ack(self):
s = make_scheduler()
jid = submit(s, 1)
job = s.claim("w1", ("email",))
self.assertEqual(job.id, jid)
self.assertEqual((job.status, job.worker, job.attempts), (LEASED, "w1", 1))
self.assertTrue(s.ack(jid, "w1"))
self.assertNotIn(jid, s.store)
def test_claim_respects_kinds(self):
s = make_scheduler()
submit(s, 1, kind="export")
self.assertIsNone(s.claim("w1", ("email", "thumbnail")))
self.assertIsNotNone(s.claim("w3", ("export",)))
def test_duplicate_key_is_not_enqueued_twice(self):
s = make_scheduler()
a = s.submit("email", {"n": 1}, "same-key", "c001")
b = s.submit("email", {"n": 1}, "same-key", "c001")
self.assertEqual(a, b)
self.assertEqual(len(s.queue), 1)
self.assertEqual(s.metrics.get("dedupe_hits"), 1)
def test_ack_of_unknown_job_is_reported(self):
s = make_scheduler()
self.assertFalse(s.ack("j-404", "w1"))
self.assertTrue(any("ack for unknown job j-404" in line for line in s.log.lines))
def test_heartbeat_keeps_the_lease_alive(self):
s = make_scheduler(lease_ttl=100)
jid = submit(s, 1)
s.claim("w1", ("email",))
s.clock.advance_to(80.0)
self.assertTrue(s.heartbeat(jid, "w1"))
s.clock.advance_to(150.0)
s.reap()
self.assertEqual(s.store.get(jid).status, LEASED)
def test_expired_lease_requeues_the_job(self):
s = make_scheduler(lease_ttl=100)
jid = submit(s, 1)
s.claim("w1", ("email",))
s.clock.advance_to(101.0)
s.reap()
again = s.claim("w2", ("email",))
self.assertEqual((again.id, again.attempts), (jid, 2))
def test_failure_schedules_a_retry(self):
s = make_scheduler()
jid = submit(s, 1)
s.claim("w1", ("email",))
self.assertTrue(s.fail(jid, "w1", "boom"))
self.assertEqual(s.store.get(jid).status, RETRY_WAIT)
self.assertEqual(len(s.pending), 1)
when, fn = s.pending[0]
self.assertEqual(when, 2.0)
fn()
self.assertEqual(s.claim("w1", ("email",)).attempts, 2)
def test_job_dies_after_max_attempts(self):
s = make_scheduler()
jid = submit(s, 1)
for _ in range(3):
s.claim("w1", ("email",))
s.fail(jid, "w1", "boom")
if s.pending:
s.pending.pop()[1]()
self.assertNotIn(jid, s.store)
self.assertEqual(s.metrics.get("dead"), 1)
self.assertTrue(any("dead after 3 attempts" in line for line in s.log.lines))
def test_completion_callback(self):
done = []
s = make_scheduler(on_complete=done.append)
jid = submit(s, 7)
s.claim("w1", ("email",))
s.ack(jid, "w1")
self.assertEqual([j.payload["n"] for j in done], [7])
def test_metrics_flush_reconciles_the_depth_gauge(self):
s = make_scheduler()
submit(s, 1)
submit(s, 2)
s.flush_metrics()
self.assertEqual(s.metrics.depth, 2)
self.assertTrue(s.log.lines[-1].endswith("dedupe_hits=0"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import unittest
from sched.clock import VirtualClock, format_ts
from sched.sim import Sim, SimConfig
class ClockTests(unittest.TestCase):
def test_format(self):
self.assertEqual(format_ts(0.0), "2024-05-14 06:00:00.000")
self.assertEqual(format_ts(3661.2504), "2024-05-14 07:01:01.250")
def test_time_does_not_run_backwards(self):
clock = VirtualClock()
clock.advance_to(5.0)
with self.assertRaises(ValueError):
clock.advance_to(4.0)
class SimTests(unittest.TestCase):
def test_small_run_completes_every_job(self):
summary = Sim(SimConfig(jobs=500, seed=3)).run()
self.assertEqual(summary["submitted"], 500)
self.assertEqual(summary["lost"], 0)
self.assertEqual(summary["duplicated"], 0)
self.assertEqual(summary["completed"] + summary["dead"], 500)
def test_same_seed_same_result(self):
a = Sim(SimConfig(jobs=300, seed=5)).run()
b = Sim(SimConfig(jobs=300, seed=5)).run()
self.assertEqual(a, b)
def test_log_lines_are_stamped_and_ordered(self):
sim = Sim(SimConfig(jobs=100, seed=2, keep_log=True))
sim.run()
stamps = [line[:23] for line in sim.log.lines]
self.assertEqual(stamps, sorted(stamps))
self.assertIn("accepted job=j-001 ", sim.log.lines[0])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,59 @@
import unittest
from sched.model import DONE, LEASED, Job
from sched.queue import JobQueue
from sched.store import JobStore
def make_job(job_id, kind="email"):
return Job(job_id, kind, {}, "k-" + job_id, "c001", 0.0)
class StoreTests(unittest.TestCase):
def test_put_get_delete(self):
store = JobStore()
store.put(make_job("j-001"))
self.assertIn("j-001", store)
self.assertEqual(store.get("j-001").kind, "email")
self.assertEqual(len(store), 1)
self.assertIsNotNone(store.delete("j-001"))
self.assertIsNone(store.get("j-001"))
self.assertIsNone(store.delete("j-001"))
def test_count_by_status(self):
store = JobStore()
a, b = make_job("j-001"), make_job("j-002")
b.status = LEASED
store.put(a)
store.put(b)
self.assertEqual(store.count(LEASED), 1)
self.assertEqual(store.count(DONE), 0)
class QueueTests(unittest.TestCase):
def test_fifo_within_a_kind(self):
q = JobQueue()
for i in range(3):
q.push("j-00%d" % i, "email")
self.assertEqual([q.pop(("email",)) for _ in range(3)], ["j-000", "j-001", "j-002"])
self.assertIsNone(q.pop(("email",)))
def test_oldest_across_served_kinds(self):
q = JobQueue()
q.push("j-001", "thumbnail")
q.push("j-002", "email")
q.push("j-003", "export")
self.assertEqual(q.pop(("email", "thumbnail")), "j-001")
self.assertEqual(q.pop(("email", "thumbnail")), "j-002")
self.assertIsNone(q.pop(("email", "thumbnail")))
self.assertEqual(q.pop(("export",)), "j-003")
def test_depth(self):
q = JobQueue()
q.push("j-001", "email")
q.push("j-002", "export")
self.assertEqual((len(q), q.depth("email"), q.depth("export"), q.depth("invoice")), (2, 1, 1, 0))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,37 @@
# Findings: jobs lost in production
## Root cause
`sched/ids.py`, `IdGenerator.next_id()`: the id sequence is masked to 12 bits (`ID_MASK`), so after `j-fff` the
counter wraps around to `j-000` and every id is handed out again after 4096 jobs. Nothing checks whether the id is
still in use. A long-running job (the `export` jobs on w4/w5/w6 run for 30-60 minutes and keep their lease alive with
heartbeats) is therefore still alive when a new job is accepted with the same id. `JobStore.put` silently overwrites
the record of the old job, the lease table and the dedupe table are keyed by the same id, and from then on the two
jobs share one record:
* when the old job acks or the new one acks, the first ack deletes the shared record and the other side finds
nothing: `ack for unknown job`, `claim of unknown job ... dropped`, or, at its next heartbeat,
`job ... vanished: lease expired while running`;
* the client of the lost job retries with the same key, `dedupe.py` still maps the key to the reused id and
swallows the resubmission (`dedupe hit ... not enqueued`), so the job never completes.
## Evidence (logs/service.log)
* lines 927-928: `accepted job=j-fff` is followed by `accepted job=j-000`, the id sequence wrapped.
* lines 123, 357, 553, 769: heartbeats `lease renewed job=j-014 worker=w4`; the export j-014 is running and leased.
* line 986: `accepted job=j-014 kind=thumbnail` - the same id is issued again while the export still holds it.
* line 1000: `ack job=j-014 worker=w4 attempts=0` (the export acks, but the record it deletes is the new job's, attempts=0).
* line 1009: `claim of unknown job j-014 by w1, dropped`; line 1496: `dedupe hit key=k-d3f091db job=j-014, not enqueued`
(the client retry of the lost thumbnail job is swallowed).
* line 1456: `accepted job=j-0a3` while the export on w5 is leased; line 1655: `job j-0a3 vanished: lease expired while running`.
* line 2870: `accepted job=j-280` while the export on w6 is leased; line 3055: `ack for unknown job j-280 worker=w2`.
* line 3991: `accepted job=j-3c7` reuses the id of the export on w4; line 4058: `job j-3c7 vanished`.
Unrelated noise: the `queue_depth counter drifted` warnings, the transient `failed attempt` retries, the two `dead after 3
attempts` errors and the lease expiry of j-194 (line 2857, a frozen worker) are different things.
## Fix
`IdGenerator.next_id()` no longer masks the sequence, so ids are never reused (they just grow to four hex digits and
more). `JobStore.put` now refuses to overwrite a record of a different job, so a future id collision fails loudly at
submit time instead of corrupting a running job. Regression tests: `tests/test_regression.py`.
@@ -0,0 +1,12 @@
"""Job id generation."""
class IdGenerator:
"""Hands out ids like j-0a3, one per accepted job; an id is never handed out twice."""
def __init__(self, start=0):
self._seq = start
def next_id(self):
self._seq += 1
return "j-%03x" % self._seq
@@ -0,0 +1,26 @@
class JobStore:
"""In-memory job records, keyed by job id."""
def __init__(self):
self._jobs = {}
def put(self, job):
old = self._jobs.get(job.id)
if old is not None and old is not job:
raise KeyError("job id %s is already in use" % job.id)
self._jobs[job.id] = job
def get(self, job_id):
return self._jobs.get(job_id)
def delete(self, job_id):
return self._jobs.pop(job_id, None)
def __contains__(self, job_id):
return job_id in self._jobs
def __len__(self):
return len(self._jobs)
def count(self, status):
return sum(1 for job in self._jobs.values() if job.status == status)
@@ -0,0 +1,31 @@
import unittest
from helpers import make_scheduler, submit
from sched.ids import IdGenerator
class IdReuseRegression(unittest.TestCase):
def test_ids_do_not_repeat_over_many_jobs(self):
gen = IdGenerator()
seen = set()
for _ in range(10000):
job_id = gen.next_id()
self.assertNotIn(job_id, seen)
seen.add(job_id)
def test_running_job_survives_the_id_space_being_cycled(self):
s = make_scheduler(lease_ttl=10 ** 9)
slow = submit(s, 0, kind="export")
job = s.claim("w4", ("export",))
self.assertEqual(job.id, slow)
for n in range(1, 5000):
job_id = submit(s, n)
self.assertNotEqual(job_id, slow, "job %d got the id of the running export" % n)
s.claim("w1", ("email",))
s.ack(job_id, "w1")
self.assertTrue(s.heartbeat(slow, "w4"))
self.assertTrue(s.ack(slow, "w4"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Replay a synthetic workload through the scheduler on a virtual clock.
python3 run_sim.py --jobs 50000 --seed 3
python3 run_sim.py --jobs 2000 --log /tmp/sim.log
Prints a one-line JSON summary; the exit status is 1 when jobs were lost or ran twice.
"""
import argparse
import json
import sys
from sched.sim import Sim, SimConfig
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--jobs", type=int, default=30000, help="number of client requests (default 30000)")
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--workers", type=int, default=3)
ap.add_argument("--slow-workers", type=int, default=1, help="workers that only serve the export lane")
ap.add_argument("--rate", type=float, default=1.0, help="new jobs per second")
ap.add_argument("--export-prob", type=float, default=1 / 6000)
ap.add_argument("--log", metavar="FILE", help="also write the service log to FILE")
args = ap.parse_args(argv)
cfg = SimConfig(
jobs=args.jobs,
seed=args.seed,
workers=args.workers,
slow_workers=args.slow_workers,
rate=args.rate,
export_prob=args.export_prob,
keep_log=bool(args.log),
)
sim = Sim(cfg)
summary = sim.run()
if args.log:
with open(args.log, "w") as fh:
fh.write("\n".join(sim.log.lines) + "\n")
print(json.dumps(summary, sort_keys=True))
return 1 if summary["lost"] or summary["duplicated"] else 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1 @@
"""A small lease-based job scheduler with a deterministic simulator."""
@@ -0,0 +1,24 @@
from datetime import datetime, timedelta
EPOCH = datetime(2024, 5, 14, 6, 0, 0)
class VirtualClock:
"""Simulated time in seconds since EPOCH; only the simulator moves it."""
def __init__(self, start=0.0):
self._now = start
def now(self):
return self._now
def advance_to(self, t):
if t < self._now:
raise ValueError("clock cannot go backwards: %.3f < %.3f" % (t, self._now))
self._now = t
def format_ts(t):
ms = int(round(t * 1000))
stamp = EPOCH + timedelta(milliseconds=ms)
return stamp.strftime("%Y-%m-%d %H:%M:%S") + ".%03d" % (ms % 1000)
@@ -0,0 +1,24 @@
class Deduper:
"""Remembers idempotency keys for a while so client retries do not create second jobs."""
def __init__(self, window):
self.window = window
self._seen = {}
def lookup(self, key, now):
entry = self._seen.get(key)
if entry is not None and now - entry[1] <= self.window:
return entry[0]
return None
def remember(self, key, job_id, now):
self._seen[key] = (job_id, now)
def prune(self, now):
stale = [k for k, (_job, ts) in self._seen.items() if now - ts > self.window]
for key in stale:
del self._seen[key]
return len(stale)
def __len__(self):
return len(self._seen)
@@ -0,0 +1,15 @@
"""Job id generation."""
ID_BITS = 12 # three hex digits keep ids short enough to read out on a support call
ID_MASK = (1 << ID_BITS) - 1
class IdGenerator:
"""Hands out ids like j-0a3, one per accepted job."""
def __init__(self, start=0):
self._seq = start & ID_MASK
def next_id(self):
self._seq = (self._seq + 1) & ID_MASK
return "j-%03x" % self._seq
@@ -0,0 +1,38 @@
class Lease:
def __init__(self, job_id, worker, expires):
self.job_id = job_id
self.worker = worker
self.expires = expires
class LeaseTable:
"""Who is working on which job, and until when."""
def __init__(self, ttl):
self.ttl = ttl
self._leases = {}
def grant(self, job_id, worker, now):
lease = Lease(job_id, worker, now + self.ttl)
self._leases[job_id] = lease
return lease
def renew(self, job_id, now):
lease = self._leases.get(job_id)
if lease is None:
return False
lease.expires = now + self.ttl
return True
def release(self, job_id):
return self._leases.pop(job_id, None)
def expired(self, now):
return [lease for lease in self._leases.values() if lease.expires <= now]
def holder(self, job_id):
lease = self._leases.get(job_id)
return lease.worker if lease else None
def __len__(self):
return len(self._leases)
@@ -0,0 +1,24 @@
from .clock import format_ts
class Log:
"""Collects log lines stamped with the virtual clock."""
def __init__(self, clock, enabled=True):
self.clock = clock
self.enabled = enabled
self.lines = []
def _emit(self, level, comp, msg, args):
if self.enabled:
text = msg % args if args else msg
self.lines.append("%s %-5s %-8s %s" % (format_ts(self.clock.now()), level, comp, text))
def info(self, comp, msg, *args):
self._emit("INFO", comp, msg, args)
def warn(self, comp, msg, *args):
self._emit("WARN", comp, msg, args)
def error(self, comp, msg, *args):
self._emit("ERROR", comp, msg, args)
@@ -0,0 +1,34 @@
class Metrics:
"""Counters plus a queue depth gauge that is kept by hand and reconciled on flush."""
def __init__(self, log):
self.log = log
self.counters = {}
self.depth = 0
def inc(self, name, n=1):
self.counters[name] = self.counters.get(name, 0) + n
def get(self, name):
return self.counters.get(name, 0)
def flush(self, actual_depth, leased):
if self.depth != actual_depth:
self.log.warn(
"metrics",
"queue_depth counter drifted (counter=%d actual=%d), reconciling",
self.depth,
actual_depth,
)
self.depth = actual_depth
self.log.info(
"metrics",
"queue_depth=%d leased=%d submitted=%d done=%d dead=%d retries=%d dedupe_hits=%d",
actual_depth,
leased,
self.get("submitted"),
self.get("done"),
self.get("dead"),
self.get("retries"),
self.get("dedupe_hits"),
)
@@ -0,0 +1,21 @@
from dataclasses import dataclass, field
from typing import Optional
QUEUED = "queued"
LEASED = "leased"
RETRY_WAIT = "retry_wait"
DONE = "done"
DEAD = "dead"
@dataclass
class Job:
id: str
kind: str
payload: dict
key: str
client: str
created_at: float
status: str = QUEUED
attempts: int = 0
worker: Optional[str] = None
@@ -0,0 +1,35 @@
from collections import deque
class JobQueue:
"""FIFO queue with one lane per job kind; workers pop from the lanes they serve."""
def __init__(self):
self._lanes = {}
self._seq = 0
self._size = 0
def push(self, job_id, kind):
self._seq += 1
self._lanes.setdefault(kind, deque()).append((self._seq, job_id))
self._size += 1
def pop(self, kinds):
"""Oldest queued job id among the given kinds, or None."""
best = None
for kind in kinds:
lane = self._lanes.get(kind)
if lane and (best is None or lane[0][0] < self._lanes[best][0][0]):
best = kind
if best is None:
return None
self._size -= 1
return self._lanes[best].popleft()[1]
def depth(self, kind=None):
if kind is None:
return self._size
return len(self._lanes.get(kind, ()))
def __len__(self):
return self._size
@@ -0,0 +1,14 @@
class RetryPolicy:
"""Exponential backoff with a cap."""
def __init__(self, max_attempts=3, base=2.0, factor=2.0, cap=30.0):
self.max_attempts = max_attempts
self.base = base
self.factor = factor
self.cap = cap
def delay(self, attempt):
return min(self.cap, self.base * self.factor ** (attempt - 1))
def exhausted(self, attempts):
return attempts >= self.max_attempts
@@ -0,0 +1,158 @@
"""The scheduler service: submit, claim, heartbeat, ack/fail and the lease reaper."""
from .dedupe import Deduper
from .ids import IdGenerator
from .lease import LeaseTable
from .metrics import Metrics
from .model import DEAD, DONE, LEASED, QUEUED, RETRY_WAIT, Job
from .queue import JobQueue
from .retry import RetryPolicy
from .store import JobStore
class Scheduler:
def __init__(
self,
clock,
log,
lease_ttl=120.0,
dedupe_window=900.0,
policy=None,
call_later=None,
on_complete=None,
on_dead=None,
):
self.clock = clock
self.log = log
self.ids = IdGenerator()
self.store = JobStore()
self.queue = JobQueue()
self.leases = LeaseTable(lease_ttl)
self.dedupe = Deduper(dedupe_window)
self.policy = policy or RetryPolicy()
self.metrics = Metrics(log)
self.call_later = call_later
self.on_complete = on_complete
self.on_dead = on_dead
def submit(self, kind, payload, key, client):
"""Accept a job; a repeated key returns the id of the earlier submission."""
now = self.clock.now()
known = self.dedupe.lookup(key, now)
if known is not None:
self.metrics.inc("dedupe_hits")
self.log.info("service", "dedupe hit key=%s job=%s, not enqueued", key, known)
return known
job = Job(self.ids.next_id(), kind, payload, key, client, now)
self.store.put(job)
self.queue.push(job.id, kind)
self.dedupe.remember(key, job.id, now)
self.metrics.inc("submitted")
self.metrics.depth += 1
self.log.info("service", "accepted job=%s kind=%s client=%s key=%s", job.id, kind, client, key)
return job.id
def claim(self, worker, kinds):
"""Hand the oldest matching job to a worker and lease it."""
while True:
job_id = self.queue.pop(kinds)
if job_id is None:
return None
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "claim of unknown job %s by %s, dropped", job_id, worker)
continue
job.status = LEASED
job.worker = worker
job.attempts += 1
self.leases.grant(job.id, worker, self.clock.now())
self.metrics.depth -= 1
self.log.info(
"lease", "lease granted job=%s worker=%s ttl=%ds attempt=%d", job.id, worker, self.leases.ttl, job.attempts
)
return job
def heartbeat(self, job_id, worker):
"""Extend the lease of a running job; False means the job is gone."""
if self.store.get(job_id) is None:
return False
if not self.leases.renew(job_id, self.clock.now()):
return False
self.log.info("lease", "lease renewed job=%s worker=%s ttl=%ds", job_id, worker, self.leases.ttl)
return True
def ack(self, job_id, worker):
"""A worker finished a job: drop the record and report the completion."""
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "ack for unknown job %s worker=%s", job_id, worker)
return False
job.status = DONE
self.store.delete(job_id)
self.leases.release(job_id)
self.metrics.inc("done")
self.log.info("service", "ack job=%s worker=%s attempts=%d", job_id, worker, job.attempts)
if self.on_complete:
self.on_complete(job)
return True
def fail(self, job_id, worker, error):
"""A worker reports a failed attempt: retry with backoff or give up."""
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "failure report for unknown job %s worker=%s", job_id, worker)
return False
self.leases.release(job_id)
if self.policy.exhausted(job.attempts):
job.status = DEAD
self.store.delete(job_id)
self.metrics.inc("dead")
self.log.error("service", "job %s dead after %d attempts: %s", job_id, job.attempts, error)
if self.on_dead:
self.on_dead(job)
return False
delay = self.policy.delay(job.attempts)
job.status = RETRY_WAIT
self.metrics.inc("retries")
self.log.warn(
"service",
"job %s failed attempt=%d/%d: %s; retry in %.1fs",
job_id,
job.attempts,
self.policy.max_attempts,
error,
delay,
)
self.call_later(delay, lambda: self.requeue(job_id))
return True
def requeue(self, job_id):
job = self.store.get(job_id)
if job is None:
self.log.warn("service", "requeue of unknown job %s", job_id)
return
job.status = QUEUED
job.worker = None
self.queue.push(job.id, job.kind)
self.log.info("service", "requeued job=%s attempt=%d", job.id, job.attempts + 1)
def reap(self):
"""Take back the jobs of workers that stopped renewing their lease."""
now = self.clock.now()
for lease in self.leases.expired(now):
self.leases.release(lease.job_id)
job = self.store.get(lease.job_id)
if job is None:
self.log.warn("lease", "expired lease for unknown job %s worker=%s", lease.job_id, lease.worker)
continue
self.metrics.inc("lease_expired")
self.log.warn(
"lease", "lease expired job=%s worker=%s, no heartbeat for %ds; requeued", job.id, lease.worker, self.leases.ttl
)
job.status = QUEUED
job.worker = None
self.queue.push(job.id, job.kind)
self.dedupe.prune(now)
def flush_metrics(self):
self.metrics.flush(len(self.queue), len(self.leases))
@@ -0,0 +1,270 @@
"""Deterministic discrete-event simulation of the scheduler.
A virtual clock drives clients that submit jobs, workers that run them and the housekeeping timers
of the service. Everything is seeded, so a configuration always produces the same run.
"""
import heapq
import itertools
import random
from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple
from .clock import VirtualClock
from .logs import Log
from .service import Scheduler
from .worker import Worker
FAST_KINDS = ("email", "thumbnail", "invoice")
SLOW_KINDS = ("export",)
ERRORS = {
"email": "TimeoutError: upstream mailer timed out after 5s",
"thumbnail": "OSError: image decoder failed",
"invoice": "ConnectionError: ledger api unavailable",
"export": "MemoryError: report too large",
}
@dataclass
class SimConfig:
jobs: int = 30000
seed: int = 1
workers: int = 3 # the last `slow_workers` of them serve only the export lane
slow_workers: int = 1
rate: float = 1.0 # new jobs per second
export_prob: float = 1 / 6000
export_min: float = 2400.0
export_max: float = 6000.0
fail_prob: float = 0.01 # first attempt fails, the retry succeeds
dead_prob: float = 0.0005 # every attempt fails
heavy_prob: float = 0.004 # fast jobs that take 10-40 s
dup_prob: float = 0.03 # client sends the same request twice
hb_interval: float = 40.0
lease_ttl: float = 120.0
planted: Dict[int, float] = field(default_factory=dict) # job number -> export duration
overrides: Dict[int, float] = field(default_factory=dict) # job number -> duration
stalls: Dict[int, Tuple[float, float]] = field(default_factory=dict) # job number -> (offset, length)
fail_plan: Dict[int, int] = field(default_factory=dict) # job number -> failing attempts
keep_log: bool = False
log_from: Optional[int] = None # keep log lines from the moment this job number is submitted
log_extra: float = 20.0 # seconds to keep going after the last submission when log_from is set
class Plan:
"""What the client submits and how the job will behave when a worker runs it."""
__slots__ = ("n", "kind", "payload", "key", "client", "dup_delay")
class Run:
__slots__ = ("token", "job", "start", "end", "stall")
def __init__(self, token, job, start, end, stall):
self.token = token
self.job = job
self.start = start
self.end = end
self.stall = stall
class Sim:
def __init__(self, cfg):
self.cfg = cfg
self.clock = VirtualClock()
self.log = Log(self.clock, enabled=cfg.keep_log and cfg.log_from is None)
self.rng_arrival = random.Random(cfg.seed)
self.rng_tie = random.Random(cfg.seed + 7919)
self._heap = []
self._seq = itertools.count()
self._tokens = itertools.count(1)
self._foreground = 0
self._arrived = 0
self._stop_at = None
self.service = Scheduler(
self.clock,
self.log,
lease_ttl=cfg.lease_ttl,
call_later=self.call_later,
on_complete=self._completed,
on_dead=self._dead,
)
fast = cfg.workers - cfg.slow_workers
self.workers = [Worker("w%d" % (i + 1), FAST_KINDS, self.service, self.log) for i in range(fast)]
self.workers += [Worker("w%d" % (fast + i + 1), SLOW_KINDS, self.service, self.log) for i in range(cfg.slow_workers)]
self.runs = {}
self.credits = {}
self.dead = {}
self.executed = {}
self.vanished = 0
self.events = 0
# ------------------------------------------------------------------ event loop
def at(self, t, fn, *args, background=False):
if not background:
self._foreground += 1
heapq.heappush(self._heap, (t, self.rng_tie.random(), next(self._seq), background, fn, args))
def call_later(self, delay, fn):
self.at(self.clock.now() + delay, fn)
def run(self):
self.at(0.0, self.arrive)
self.at(10.0, self.tick_reap, background=True)
self.at(30.0, self.tick_flush, background=True)
while self._heap:
t, _tie, _seq, background, fn, args = heapq.heappop(self._heap)
if not background:
self._foreground -= 1
elif self._foreground == 0:
break # only housekeeping timers are left
if self._stop_at is not None and t > self._stop_at:
break
self.clock.advance_to(t)
self.events += 1
fn(*args)
return self.summary()
# ------------------------------------------------------------------ clients
def plan(self, n):
cfg = self.cfg
r = random.Random(cfg.seed * 1000003 + n)
p = Plan()
p.n = n
if n in cfg.planted:
p.kind, dur = "export", cfg.planted[n]
elif r.random() < cfg.export_prob:
p.kind, dur = "export", r.uniform(cfg.export_min, cfg.export_max)
else:
pick = r.random()
p.kind = "email" if pick < 0.55 else ("thumbnail" if pick < 0.85 else "invoice")
dur = {"email": r.uniform(0.3, 1.6), "thumbnail": r.uniform(0.8, 3.0), "invoice": r.uniform(0.5, 2.0)}[p.kind]
if r.random() < cfg.heavy_prob:
dur = r.uniform(10.0, 40.0)
dur = cfg.overrides.get(n, dur)
roll = r.random()
fail = 1 if roll < cfg.fail_prob else (99 if roll > 1.0 - cfg.dead_prob else 0)
fail = cfg.fail_plan.get(n, fail)
p.payload = {"n": n, "dur": dur, "fail": fail}
p.key = "k-%08x" % ((n * 2654435761 + cfg.seed) & 0xFFFFFFFF)
p.client = "c%03d" % r.randrange(1, 400)
p.dup_delay = r.uniform(2.0, 40.0) if r.random() < cfg.dup_prob else None
return p
def arrive(self):
cfg = self.cfg
n = self._arrived + 1
self._arrived = n
if cfg.log_from is not None and n == cfg.log_from:
self.log.enabled = True
p = self.plan(n)
now = self.clock.now()
self.service.submit(p.kind, p.payload, p.key, p.client)
if p.dup_delay is not None:
self.at(now + p.dup_delay, self.resubmit, p)
if p.kind != "export":
self.at(now + 90.0, self.check_timeout, p)
if n < cfg.jobs:
self.at(now + self.rng_arrival.expovariate(cfg.rate), self.arrive)
elif cfg.log_from is not None:
self._stop_at = now + cfg.log_extra
self.dispatch()
def resubmit(self, p):
self.service.submit(p.kind, p.payload, p.key, p.client)
self.dispatch()
def check_timeout(self, p):
"""Clients that have seen no result after 90 s send the request again."""
if not self.executed.get(p.n) and not self.dead.get(p.n):
self.resubmit(p)
# ------------------------------------------------------------------ workers
def dispatch(self):
if not len(self.service.queue):
return
for w in self.workers:
if w.idle:
job = w.poll()
if job is not None:
self.start(w, job)
def start(self, w, job):
cfg = self.cfg
now = self.clock.now()
stall = cfg.stalls.get(job.payload["n"])
end = now + job.payload["dur"] + (stall[1] if stall else 0.0)
token = next(self._tokens)
self.runs[w.name] = Run(token, job, now, end, stall)
self.at(end, self.finish, w, token)
if end - now > cfg.hb_interval:
self.at(now + cfg.hb_interval, self.beat, w, token)
def beat(self, w, token):
run = self.runs.get(w.name)
if run is None or run.token != token:
return
now = self.clock.now()
frozen = run.stall is not None and run.start + run.stall[0] <= now < run.start + run.stall[0] + run.stall[1]
if not frozen and not w.heartbeat():
del self.runs[w.name]
self.vanished += 1
self.dispatch()
return
if now + self.cfg.hb_interval < run.end:
self.at(now + self.cfg.hb_interval, self.beat, w, token)
def finish(self, w, token):
run = self.runs.get(w.name)
if run is None or run.token != token:
return
del self.runs[w.name]
job = run.job
n = job.payload["n"]
if job.attempts <= job.payload["fail"]:
w.fail(ERRORS[job.kind])
else:
self.executed[n] = self.executed.get(n, 0) + 1
w.complete()
self.dispatch()
def _completed(self, job):
n = job.payload["n"]
self.credits[n] = self.credits.get(n, 0) + 1
def _dead(self, job):
n = job.payload["n"]
self.dead[n] = self.dead.get(n, 0) + 1
# ------------------------------------------------------------------ housekeeping
def tick_reap(self):
self.service.reap()
self.dispatch()
self.at(self.clock.now() + 10.0, self.tick_reap, background=True)
def tick_flush(self):
self.service.flush_metrics()
self.at(self.clock.now() + 30.0, self.tick_flush, background=True)
# ------------------------------------------------------------------ result
def summary(self):
n = self._arrived
lost = [i for i in range(1, n + 1) if not self.credits.get(i) and not self.dead.get(i)]
dup = [i for i in range(1, n + 1) if self.credits.get(i, 0) > 1 or self.executed.get(i, 0) > 1]
return {
"submitted": n,
"completed": sum(1 for i in range(1, n + 1) if self.credits.get(i)),
"dead": len(self.dead),
"lost": len(lost),
"lost_sample": lost[:5],
"duplicated": len(dup),
"vanished": self.vanished,
"lease_expired": self.service.metrics.get("lease_expired"),
"dedupe_hits": self.service.metrics.get("dedupe_hits"),
"virtual_seconds": round(self.clock.now(), 1),
"events": self.events,
}
@@ -0,0 +1,24 @@
class JobStore:
"""In-memory job records, keyed by job id."""
def __init__(self):
self._jobs = {}
def put(self, job):
# upsert: the retry path saves updated records through here as well
self._jobs[job.id] = job
def get(self, job_id):
return self._jobs.get(job_id)
def delete(self, job_id):
return self._jobs.pop(job_id, None)
def __contains__(self, job_id):
return job_id in self._jobs
def __len__(self):
return len(self._jobs)
def count(self, status):
return sum(1 for job in self._jobs.values() if job.status == status)
@@ -0,0 +1,55 @@
"""Worker side of the protocol: claim, heartbeat, then ack or fail."""
SLOW_SECONDS = 10.0
SLOW_SECONDS_BY_KIND = {"export": 7200.0}
class Worker:
def __init__(self, name, kinds, service, log):
self.name = name
self.kinds = tuple(kinds)
self.service = service
self.log = log
self.current = None
self.started_at = 0.0
@property
def idle(self):
return self.current is None
def poll(self):
"""Ask the scheduler for work; returns the claimed job or None."""
job = self.service.claim(self.name, self.kinds)
if job is not None:
self.current = job
self.started_at = self.service.clock.now()
return job
def heartbeat(self):
"""Renew the lease of the running job; abandon the job if the scheduler lost it."""
job = self.current
if self.service.heartbeat(job.id, self.name):
return True
self.log.error(
"worker",
"job %s vanished: lease expired while running (worker=%s kind=%s attempt=%d)",
job.id,
self.name,
job.kind,
job.attempts,
)
self.current = None
return False
def complete(self):
job = self.current
self.current = None
took = self.service.clock.now() - self.started_at
if took > SLOW_SECONDS_BY_KIND.get(job.kind, SLOW_SECONDS):
self.log.warn("worker", "slow job %s worker=%s kind=%s took %.1fs", job.id, self.name, job.kind, took)
return self.service.ack(job.id, self.name)
def fail(self, error):
job = self.current
self.current = None
return self.service.fail(job.id, self.name, error)
@@ -0,0 +1,16 @@
from sched.clock import VirtualClock
from sched.logs import Log
from sched.service import Scheduler
def make_scheduler(**kwargs):
clock = VirtualClock()
log = Log(clock)
later = []
sched = Scheduler(clock, log, call_later=lambda delay, fn: later.append((clock.now() + delay, fn)), **kwargs)
sched.pending = later
return sched
def submit(sched, n, kind="email"):
return sched.submit(kind, {"n": n}, "key-%d" % n, "c001")
@@ -0,0 +1,27 @@
import unittest
from sched.ids import IdGenerator
class IdGeneratorTests(unittest.TestCase):
def test_first_ids(self):
gen = IdGenerator()
self.assertEqual([gen.next_id() for _ in range(3)], ["j-001", "j-002", "j-003"])
def test_ids_are_hex(self):
gen = IdGenerator(start=0x0A2)
self.assertEqual(gen.next_id(), "j-0a3")
def test_ids_are_unique_for_a_while(self):
gen = IdGenerator()
ids = [gen.next_id() for _ in range(2000)]
self.assertEqual(len(set(ids)), 2000)
def test_ids_sort_in_creation_order_within_a_page(self):
gen = IdGenerator()
ids = [gen.next_id() for _ in range(200)]
self.assertEqual(ids, sorted(ids))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,59 @@
import unittest
from sched.dedupe import Deduper
from sched.lease import LeaseTable
from sched.retry import RetryPolicy
class LeaseTests(unittest.TestCase):
def test_grant_and_expiry(self):
leases = LeaseTable(ttl=120)
leases.grant("j-001", "w1", now=10.0)
self.assertEqual(leases.holder("j-001"), "w1")
self.assertEqual(leases.expired(129.9), [])
self.assertEqual([l.job_id for l in leases.expired(130.0)], ["j-001"])
def test_renew_pushes_expiry(self):
leases = LeaseTable(ttl=120)
leases.grant("j-001", "w1", now=0.0)
self.assertTrue(leases.renew("j-001", now=100.0))
self.assertEqual(leases.expired(200.0), [])
self.assertEqual(len(leases.expired(220.0)), 1)
def test_renew_unknown_and_release(self):
leases = LeaseTable(ttl=60)
self.assertFalse(leases.renew("j-404", now=0.0))
leases.grant("j-001", "w1", now=0.0)
self.assertIsNotNone(leases.release("j-001"))
self.assertEqual(len(leases), 0)
class DedupeTests(unittest.TestCase):
def test_hit_within_window(self):
d = Deduper(window=900)
d.remember("k1", "j-001", now=0.0)
self.assertEqual(d.lookup("k1", now=899.0), "j-001")
self.assertIsNone(d.lookup("k1", now=901.0))
self.assertIsNone(d.lookup("k2", now=1.0))
def test_prune(self):
d = Deduper(window=100)
d.remember("k1", "j-001", now=0.0)
d.remember("k2", "j-002", now=90.0)
self.assertEqual(d.prune(now=150.0), 1)
self.assertEqual(len(d), 1)
class RetryTests(unittest.TestCase):
def test_backoff_is_capped(self):
p = RetryPolicy(max_attempts=5, base=2.0, factor=2.0, cap=10.0)
self.assertEqual([p.delay(a) for a in (1, 2, 3, 4)], [2.0, 4.0, 8.0, 10.0])
def test_exhausted(self):
p = RetryPolicy(max_attempts=3)
self.assertFalse(p.exhausted(2))
self.assertTrue(p.exhausted(3))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,97 @@
import unittest
from helpers import make_scheduler, submit
from sched.model import LEASED, RETRY_WAIT
class ServiceTests(unittest.TestCase):
def test_submit_claim_ack(self):
s = make_scheduler()
jid = submit(s, 1)
job = s.claim("w1", ("email",))
self.assertEqual(job.id, jid)
self.assertEqual((job.status, job.worker, job.attempts), (LEASED, "w1", 1))
self.assertTrue(s.ack(jid, "w1"))
self.assertNotIn(jid, s.store)
def test_claim_respects_kinds(self):
s = make_scheduler()
submit(s, 1, kind="export")
self.assertIsNone(s.claim("w1", ("email", "thumbnail")))
self.assertIsNotNone(s.claim("w3", ("export",)))
def test_duplicate_key_is_not_enqueued_twice(self):
s = make_scheduler()
a = s.submit("email", {"n": 1}, "same-key", "c001")
b = s.submit("email", {"n": 1}, "same-key", "c001")
self.assertEqual(a, b)
self.assertEqual(len(s.queue), 1)
self.assertEqual(s.metrics.get("dedupe_hits"), 1)
def test_ack_of_unknown_job_is_reported(self):
s = make_scheduler()
self.assertFalse(s.ack("j-404", "w1"))
self.assertTrue(any("ack for unknown job j-404" in line for line in s.log.lines))
def test_heartbeat_keeps_the_lease_alive(self):
s = make_scheduler(lease_ttl=100)
jid = submit(s, 1)
s.claim("w1", ("email",))
s.clock.advance_to(80.0)
self.assertTrue(s.heartbeat(jid, "w1"))
s.clock.advance_to(150.0)
s.reap()
self.assertEqual(s.store.get(jid).status, LEASED)
def test_expired_lease_requeues_the_job(self):
s = make_scheduler(lease_ttl=100)
jid = submit(s, 1)
s.claim("w1", ("email",))
s.clock.advance_to(101.0)
s.reap()
again = s.claim("w2", ("email",))
self.assertEqual((again.id, again.attempts), (jid, 2))
def test_failure_schedules_a_retry(self):
s = make_scheduler()
jid = submit(s, 1)
s.claim("w1", ("email",))
self.assertTrue(s.fail(jid, "w1", "boom"))
self.assertEqual(s.store.get(jid).status, RETRY_WAIT)
self.assertEqual(len(s.pending), 1)
when, fn = s.pending[0]
self.assertEqual(when, 2.0)
fn()
self.assertEqual(s.claim("w1", ("email",)).attempts, 2)
def test_job_dies_after_max_attempts(self):
s = make_scheduler()
jid = submit(s, 1)
for _ in range(3):
s.claim("w1", ("email",))
s.fail(jid, "w1", "boom")
if s.pending:
s.pending.pop()[1]()
self.assertNotIn(jid, s.store)
self.assertEqual(s.metrics.get("dead"), 1)
self.assertTrue(any("dead after 3 attempts" in line for line in s.log.lines))
def test_completion_callback(self):
done = []
s = make_scheduler(on_complete=done.append)
jid = submit(s, 7)
s.claim("w1", ("email",))
s.ack(jid, "w1")
self.assertEqual([j.payload["n"] for j in done], [7])
def test_metrics_flush_reconciles_the_depth_gauge(self):
s = make_scheduler()
submit(s, 1)
submit(s, 2)
s.flush_metrics()
self.assertEqual(s.metrics.depth, 2)
self.assertTrue(s.log.lines[-1].endswith("dedupe_hits=0"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import unittest
from sched.clock import VirtualClock, format_ts
from sched.sim import Sim, SimConfig
class ClockTests(unittest.TestCase):
def test_format(self):
self.assertEqual(format_ts(0.0), "2024-05-14 06:00:00.000")
self.assertEqual(format_ts(3661.2504), "2024-05-14 07:01:01.250")
def test_time_does_not_run_backwards(self):
clock = VirtualClock()
clock.advance_to(5.0)
with self.assertRaises(ValueError):
clock.advance_to(4.0)
class SimTests(unittest.TestCase):
def test_small_run_completes_every_job(self):
summary = Sim(SimConfig(jobs=500, seed=3)).run()
self.assertEqual(summary["submitted"], 500)
self.assertEqual(summary["lost"], 0)
self.assertEqual(summary["duplicated"], 0)
self.assertEqual(summary["completed"] + summary["dead"], 500)
def test_same_seed_same_result(self):
a = Sim(SimConfig(jobs=300, seed=5)).run()
b = Sim(SimConfig(jobs=300, seed=5)).run()
self.assertEqual(a, b)
def test_log_lines_are_stamped_and_ordered(self):
sim = Sim(SimConfig(jobs=100, seed=2, keep_log=True))
sim.run()
stamps = [line[:23] for line in sim.log.lines]
self.assertEqual(stamps, sorted(stamps))
self.assertIn("accepted job=j-001 ", sim.log.lines[0])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,59 @@
import unittest
from sched.model import DONE, LEASED, Job
from sched.queue import JobQueue
from sched.store import JobStore
def make_job(job_id, kind="email"):
return Job(job_id, kind, {}, "k-" + job_id, "c001", 0.0)
class StoreTests(unittest.TestCase):
def test_put_get_delete(self):
store = JobStore()
store.put(make_job("j-001"))
self.assertIn("j-001", store)
self.assertEqual(store.get("j-001").kind, "email")
self.assertEqual(len(store), 1)
self.assertIsNotNone(store.delete("j-001"))
self.assertIsNone(store.get("j-001"))
self.assertIsNone(store.delete("j-001"))
def test_count_by_status(self):
store = JobStore()
a, b = make_job("j-001"), make_job("j-002")
b.status = LEASED
store.put(a)
store.put(b)
self.assertEqual(store.count(LEASED), 1)
self.assertEqual(store.count(DONE), 0)
class QueueTests(unittest.TestCase):
def test_fifo_within_a_kind(self):
q = JobQueue()
for i in range(3):
q.push("j-00%d" % i, "email")
self.assertEqual([q.pop(("email",)) for _ in range(3)], ["j-000", "j-001", "j-002"])
self.assertIsNone(q.pop(("email",)))
def test_oldest_across_served_kinds(self):
q = JobQueue()
q.push("j-001", "thumbnail")
q.push("j-002", "email")
q.push("j-003", "export")
self.assertEqual(q.pop(("email", "thumbnail")), "j-001")
self.assertEqual(q.pop(("email", "thumbnail")), "j-002")
self.assertIsNone(q.pop(("email", "thumbnail")))
self.assertEqual(q.pop(("export",)), "j-003")
def test_depth(self):
q = JobQueue()
q.push("j-001", "email")
q.push("j-002", "export")
self.assertEqual((len(q), q.depth("email"), q.depth("export"), q.depth("invoice")), (2, 1, 1, 0))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,39 @@
---
id: debuglog-sched
title: Find why a job scheduler loses jobs from a production log, fix it and write it up
kind: debug
expected_rounds: 20-50
---
# debuglog-sched
Notes for the orchestrator (not sent to Codex).
* Seed: `sched/` (a lease-based job scheduler: queue, store, leases, dedupe, retry, metrics, a discrete-event simulator, about 780 lines with `run_sim.py`),
31 visible unit tests (green on the seed) and `logs/service.log` (4730 lines, 417 KB, generated by `gen_log.py` from the seed code; `gen_log.py` is not part of the seed).
Reading the log with grep/sed in slices is the realistic way; `cat`-ing it whole would be about 150k tokens, so context growth towards 100k tokens depends on how much of the log the agent pages through.
* The defect: `sched/ids.py` masks the id sequence to 12 bits (`ID_MASK`), so ids repeat after 4096 jobs. A long-running export job that still holds its lease gets its id issued again to a new job;
`JobStore.put` overwrites the record, so the first ack / heartbeat / claim after that finds nothing (`ack for unknown job`, `claim of unknown job ... dropped`, `job ... vanished: lease expired while running`),
and the client's retry is swallowed by `dedupe.py` (`dedupe hit ... not enqueued`). The log shows the sequence going `j-fff` -> `j-000` (line 927-928), heartbeats of the old job before the reuse,
and four incidents (lines 986/1009, 1456/1655, 2870/3055, 3991/4058).
* Red herrings in the log: transient `failed attempt` retries, `queue_depth counter drifted` warnings (a harmless hand-kept gauge), slow-job warnings, two `dead after 3 attempts` errors,
and one frozen worker whose lease expires (line 2857) which also yields an `ack for unknown job`-like pattern (`claim of unknown job j-194`), but with a `lease expired` line before it and no id reuse.
* Acceptance (`accept.py`): (1) the pristine visible tests (`hidden/tests`, copied over `tests/`) pass on the agent's code; (2) `tests/test_regression.py` exists and passes; (3) the same file FAILS against the original
`sched/` (`hidden/orig/sched`), so a test that cannot detect the bug is rejected; (4) two hidden stress simulations (140,000 jobs / 3 workers, 100,000 jobs / 5 workers, different seeds and traffic) run with the pristine
`sim.py` on top of the agent's service code and must lose and duplicate nothing (about 5 s each); (5) `FINDINGS.md` names `ids.py` and `next_id`/`IdGenerator`, talks about wrap/reuse/collision, and cites a number within 2 of an
evidence line (`hidden/evidence.json`, written by `gen_log.py`). Any fix that stops ids from colliding passes (removing the mask, skipping ids in use, a wider counter, uuid-like ids that keep the pristine tests green).
Because the pristine `sim.py` is used, a fix must keep the `Scheduler` constructor and method signatures.
* The original code loses 18 jobs in stress a and 27 in stress b; the reference fix (`reference/overlay`) loses none. Deterministic: seeded virtual-clock simulation, no wall clock, no network; Python 3.9 .. 3.14.
* To regenerate the log (not needed): `python3 gen_log.py` writes `seed/logs/service.log` and `hidden/evidence.json`; the output is byte-identical on Python 3.9 and 3.12.
## Prompt
<!-- PROMPT BEGIN -->
Production lost some jobs. Customers are complaining that some of their jobs never completed, and on-call saw `ack for unknown job` warnings and `vanished` errors in the scheduler log. The log of the incident is `logs/service.log` (about 4,700 lines, so use grep and sed to look at slices of it rather than printing the whole file). The scheduler code is in `sched/`; `run_sim.py` replays a synthetic workload through the same code on a virtual clock (`python3 run_sim.py --help`), and the unit tests run with `python3 -m unittest discover -s tests`.
Please:
1. Find the root cause of the lost jobs. The log has enough information to localise it.
2. Fix it in the code. Keep the existing tests green.
3. Add a regression test in `tests/test_regression.py` that fails on the old code and passes with your fix.
4. Write `FINDINGS.md` in the repository root with the root cause (file and function), the evidence (line numbers in `logs/service.log`) and the fix you made.
There is no network here and only the Python 3 standard library is available (no pytest). When you are done, reply with a short summary of the root cause and the fix.
<!-- PROMPT END -->
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Acceptance check for task feature-query.
Usage: python3 accept.py WORKSPACE
Exit 0 when the task is done; any other exit code means not done. The workspace is never modified: everything runs in a temporary copy.
"""
import ast
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
PRISTINE = HERE / "hidden" / "pristine_tests"
HIDDEN_TESTS = HERE / "hidden" / "test_hidden_spec.py"
SPEC_SHA256 = hashlib.sha256((HERE / "seed" / "SPEC.md").read_bytes()).hexdigest()
MIN_TEST_METHODS = 25
IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".git")
failed = []
def check(name, ok, detail=""):
if ok:
print("PASS " + name)
else:
print("FAIL %s :: %s" % (name, detail.strip()[-1500:]))
failed.append(name)
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def run_unittest(cwd, start_dir, pattern="test*.py", timeout=100):
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0")
try:
proc = subprocess.run(
[sys.executable, "-m", "unittest", "discover", "-s", start_dir, "-p", pattern],
cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout,
)
except subprocess.TimeoutExpired:
return False, "timeout", 0
output = proc.stdout + proc.stderr
match = re.search(r"^Ran (\d+) tests? in", output, re.M)
return proc.returncode == 0, output, int(match.group(1)) if match else 0
def count_assertive_tests(path):
"""Number of test methods (in classes) that contain at least one assertion call."""
tree = ast.parse(Path(path).read_text(encoding="utf-8"))
total = 0
for node in ast.walk(tree):
if not isinstance(node, ast.ClassDef):
continue
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name.startswith("test"):
asserts = [
n for n in ast.walk(item)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
and (n.func.attr.startswith("assert") or n.func.attr in ("fail", "subTest"))
]
if asserts:
total += 1
return total
def main():
if len(sys.argv) != 2:
print("usage: accept.py WORKSPACE")
return 2
workspace = Path(sys.argv[1]).resolve()
if not workspace.is_dir():
print("FAIL workspace :: not a directory")
return 2
# 1. pristine tests and the specification are untouched
for src in sorted(PRISTINE.rglob("*")):
if not src.is_file() or "__pycache__" in src.parts:
continue
rel = src.relative_to(PRISTINE)
target = workspace / "tests" / rel
check("tests-untouched:" + rel.as_posix(), target.is_file() and digest(target) == digest(src),
"tests/%s is missing or was modified" % rel.as_posix())
spec = workspace / "SPEC.md"
check("spec-untouched", spec.is_file() and digest(spec) == SPEC_SHA256, "SPEC.md is missing or was modified")
with tempfile.TemporaryDirectory() as tmp:
# 2. the existing behaviour, tested with the pristine tests only
pristine_ws = Path(tmp) / "pristine"
shutil.copytree(workspace, pristine_ws, ignore=IGNORE)
shutil.rmtree(pristine_ws / "tests", ignore_errors=True)
shutil.copytree(PRISTINE, pristine_ws / "tests", ignore=IGNORE)
ok, out, ran = run_unittest(pristine_ws, "tests")
check("existing-tests", ok and ran > 0, out)
# 3. spec conformance, tested with hidden cases
hidden_dir = pristine_ws / "_hidden"
hidden_dir.mkdir()
shutil.copy(HIDDEN_TESTS, hidden_dir / "test_hidden_spec.py")
ok, out, ran = run_unittest(pristine_ws, "_hidden")
check("spec-conformance", ok and ran > 0, out)
# 4. the agent's own tests
own = workspace / "tests" / "test_query.py"
exists = own.is_file()
check("own-tests-exist", exists, "tests/test_query.py does not exist")
if exists:
try:
assertive = count_assertive_tests(own)
except SyntaxError as exc:
assertive = 0
print("note: tests/test_query.py does not parse: %s" % exc)
check("own-tests-count", assertive >= MIN_TEST_METHODS,
"%d test methods with assertions, need at least %d" % (assertive, MIN_TEST_METHODS))
text = own.read_text(encoding="utf-8")
check("own-tests-use-feature", "minidb" in text and "where" in text,
"tests/test_query.py does not exercise the where language")
own_ws = Path(tmp) / "own"
shutil.copytree(workspace, own_ws, ignore=IGNORE)
ok, out, ran = run_unittest(own_ws, "tests", pattern="test_query.py")
check("own-tests-pass", ok and ran >= MIN_TEST_METHODS, "ran %d tests; %s" % (ran, out))
# 5. documentation
readme = workspace / "README.md"
text = readme.read_text(encoding="utf-8") if readme.is_file() else ""
check("readme-mentions-where-option", "--where" in text, "README.md does not mention --where")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,133 @@
import contextlib
import io
import os
import tempfile
import unittest
from minidb import Column, Database
from minidb.cli import main, parse_assignments, parse_column_spec
from minidb.csvio import export_csv, import_csv, read_csv, write_csv
from minidb.errors import SchemaError
def people_table():
db = Database()
people = db.create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")])
people.insert_many([
{"name": "Ann", "age": 31, "active": True},
{"name": "Bob, Jr.", "age": None, "active": False},
])
return people
class CsvTests(unittest.TestCase):
def test_write_csv_format(self):
people = people_table()
buffer = io.StringIO()
write_csv(people.select(), people.schema.names(), buffer)
self.assertEqual(buffer.getvalue(), 'id,name,age,active\n1,Ann,31,true\n2,"Bob, Jr.",,false\n')
def test_round_trip_through_a_file(self):
people = people_table()
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "people.csv")
self.assertEqual(export_csv(people, path), 2)
other = Database().create_table("people", [Column("name"), Column("age", "int"), Column("active", "bool")])
self.assertEqual(import_csv(other, path), 2)
self.assertEqual(other.select(), people.select())
def test_import_ignores_id_column_and_checks_header(self):
schema = people_table().schema
rows = read_csv(io.StringIO("id,name\n7,Zed\n"), schema)
self.assertEqual(rows, [{"name": "Zed"}])
with self.assertRaises(SchemaError):
read_csv(io.StringIO("nombre\nZed\n"), schema)
def test_export_with_callable_filter(self):
people = people_table()
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "out.csv")
written = export_csv(people, path, where=lambda row: row["active"], columns=["name"])
with open(path, encoding="utf-8") as handle:
self.assertEqual(handle.read(), "name\nAnn\n")
self.assertEqual(written, 1)
class ParsingTests(unittest.TestCase):
def test_column_specs(self):
self.assertEqual(parse_column_spec("age:int"), Column("age", "int"))
self.assertEqual(parse_column_spec("name:str:required"), Column("name", "str", nullable=False))
with self.assertRaises(SchemaError):
parse_column_spec("age")
with self.assertRaises(SchemaError):
parse_column_spec("age:int:maybe")
def test_assignments(self):
schema = people_table().schema
self.assertEqual(parse_assignments(schema, ["name=Ann", "age=", "active=true"]),
{"name": "Ann", "age": None, "active": True})
with self.assertRaises(SchemaError):
parse_assignments(schema, ["age"])
class CliTests(unittest.TestCase):
def setUp(self):
self._folder = tempfile.TemporaryDirectory()
self.addCleanup(self._folder.cleanup)
self.db = os.path.join(self._folder.name, "test.json")
def run_cli(self, *args):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stderr(err):
code = main(["--db", self.db, *args], out=out)
return code, out.getvalue(), err.getvalue()
def setup_table(self):
self.assertEqual(self.run_cli("create", "people", "name:str:required", "age:int", "city:str")[0], 0)
for assignments in (["name=Ann", "age=31", "city=Berlin"], ["name=Bob", "age=25"], ["name=Cid", "city=Rome"]):
self.assertEqual(self.run_cli("insert", "people", *assignments)[0], 0)
def test_insert_prints_ids_and_select_prints_csv(self):
self.setup_table()
code, out, _ = self.run_cli("select", "people")
self.assertEqual(code, 0)
self.assertEqual(out, "id,name,age,city\n1,Ann,31,Berlin\n2,Bob,25,\n3,Cid,,Rome\n")
def test_select_options(self):
self.setup_table()
_, out, _ = self.run_cli("select", "people", "--columns", "name,age", "--order-by", "age", "--desc", "--limit", "2")
self.assertEqual(out, "name,age\nAnn,31\nBob,25\n")
def test_update_and_delete_by_id(self):
self.setup_table()
self.assertEqual(self.run_cli("update", "people", "--id", "2", "city=Paris", "age=")[1], "updated 1\n")
self.assertEqual(self.run_cli("delete", "people", "--id", "1")[1], "deleted 1\n")
self.assertEqual(self.run_cli("delete", "people", "--id", "77")[1], "deleted 0\n")
_, out, _ = self.run_cli("select", "people")
self.assertEqual(out, "id,name,age,city\n2,Bob,,Paris\n3,Cid,,Rome\n")
def test_data_persists_between_runs(self):
self.setup_table()
self.assertTrue(os.path.exists(self.db))
_, out, _ = self.run_cli("select", "people", "--columns", "id")
self.assertEqual(out.splitlines(), ["id", "1", "2", "3"])
def test_errors_exit_with_status_two(self):
self.setup_table()
for args in (["select", "nobody"], ["insert", "people", "age=3"], ["insert", "people", "name=X", "age=old"],
["select", "people", "--order-by", "height"]):
code, out, err = self.run_cli(*args)
self.assertEqual((code, out), (2, ""), args)
self.assertTrue(err.startswith("error: "), args)
def test_import_and_export(self):
self.setup_table()
path = os.path.join(self._folder.name, "people.csv")
self.assertEqual(self.run_cli("export-csv", "people", path), (0, "exported 3\n", ""))
self.assertEqual(self.run_cli("import-csv", "people", path), (0, "imported 3\n", ""))
_, out, _ = self.run_cli("select", "people", "--columns", "name")
self.assertEqual(out.splitlines(), ["name", "Ann", "Bob", "Cid", "Ann", "Bob", "Cid"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,72 @@
import json
import os
import tempfile
import unittest
from minidb.errors import MiniDBError
from minidb.index import HashIndex
from minidb.storage import JsonFileStorage, MemoryStorage
class HashIndexTests(unittest.TestCase):
def test_add_lookup_remove(self):
index = HashIndex("city")
index.add({"id": 2, "city": "Rome"})
index.add({"id": 1, "city": "Rome"})
index.add({"id": 3, "city": "Paris"})
self.assertEqual(index.lookup("Rome"), [1, 2])
index.remove({"id": 1, "city": "Rome"})
self.assertEqual(index.lookup("Rome"), [2])
self.assertEqual(index.lookup("Oslo"), [])
self.assertEqual(len(index), 2)
def test_nulls_are_not_indexed(self):
index = HashIndex("city")
index.add({"id": 1, "city": None})
self.assertEqual(index.lookup(None), [])
self.assertEqual(len(index), 0)
def test_rebuild(self):
index = HashIndex("n")
index.add({"id": 9, "n": 1})
index.rebuild([{"id": 1, "n": 5}, {"id": 2, "n": 5}])
self.assertEqual(index.lookup(1), [])
self.assertEqual(index.lookup(5), [1, 2])
class StorageTests(unittest.TestCase):
def test_memory_storage_keeps_copies(self):
storage = MemoryStorage()
self.assertIsNone(storage.load())
data = {"tables": {"t": {"rows": [1]}}}
storage.save(data)
data["tables"]["t"]["rows"].append(2)
self.assertEqual(storage.load(), {"tables": {"t": {"rows": [1]}}})
def test_json_file_round_trip(self):
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "db.json")
storage = JsonFileStorage(path)
self.assertIsNone(storage.load())
storage.save({"tables": {}, "version": 1})
self.assertEqual(storage.load(), {"tables": {}, "version": 1})
self.assertFalse(os.path.exists(path + ".tmp"))
def test_corrupt_file_is_reported(self):
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "db.json")
with open(path, "w", encoding="utf-8") as handle:
handle.write("{not json")
with self.assertRaises(MiniDBError):
JsonFileStorage(path).load()
def test_file_is_plain_json(self):
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "db.json")
JsonFileStorage(path).save({"a": [1, 2]})
with open(path, encoding="utf-8") as handle:
self.assertEqual(json.load(handle), {"a": [1, 2]})
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More