#!/usr/bin/env python3 """A scripted stand-in for `strata --serve`, for strata-ctl's integration tests. Speaks the line protocol exactly as the engine's parser emits it: READY/INFO at start, then per GEN: optional RESUME, PP lines, T lines, DONE. Faithful to the real engine's key invariant: **one DONE per request**. A STOP arriving mid-request ends that request with a single DONE and is not answered again; a STOP arriving while idle is ignored (no request to abort). Stdin is read on a background thread so STOP can interrupt a long generation, exactly as the resident engine's own stdin reader does. Scenarios, keyed by the prompt ids sent: * 999999 in ids -> ERR then DONE (a refused id) * 888888 in ids -> long generation (many tokens), interruptible by STOP * 777777 in ids -> total silence (the supervisor's watchdog must fire) * otherwise -> echo five tokens and finish """ import queue import sys import threading import time def out(line: str) -> None: sys.stdout.write(line + "\n") sys.stdout.flush() def reader(cmds: "queue.Queue[str]") -> None: for raw in sys.stdin: cmds.put(raw.strip()) cmds.put(None) # EOF out("INFO version=0.0.0-mock build=test") out("READY 8192 stop hold") cmds: "queue.Queue[str | None]" = queue.Queue() threading.Thread(target=reader, args=(cmds,), daemon=True).start() while True: cmd = cmds.get() if cmd is None or cmd == "QUIT": break if cmd == "STOP": continue # idle STOP: nothing to abort, no reply (as the real engine) if not cmd.startswith("GEN"): out("ERR unknown command") continue parts = cmd.split() if len(parts) < 3: out("ERR GEN: missing ids") continue try: ids = [int(t) for t in parts[-1].split(",")] except ValueError: out("ERR GEN: bad id") continue keys = " ".join(parts[1:-1]) if "bad_key" in keys: out("ERR GEN: unknown/unsupported key bad_key") out("DONE 0 0 0.0 0.0 error") continue if 999999 in ids: out("ERR GEN: id out of range") out("DONE 0 0 0.0 0.0 error") continue if 777777 in ids: # total silence for this request: swallow commands until a STOP ends it while True: nxt = cmds.get() if nxt is None or nxt == "QUIT": sys.exit(0) if nxt == "STOP": out("DONE 0 0 0.0 0.0 abort") break continue if 888888 in ids: out("RESUME 3") out("PP 5 5 1.5 3333.3") n = 0 stopped = False while n < 100000: nxt = cmds.get_nowait() if not cmds.empty() else None if nxt == "STOP": stopped = True break n += 1 out(f"T {n}") if n % 50 == 0: time.sleep(0.001) out(f"DONE {n} {len(ids)} 1.0 2.0 {'abort' if stopped else 'length'}") continue out("RESUME 1") out("PP 2 4 0.9 2222.2") for t in (101, 102, 103, 104, 105): out(f"T {t}") out("DONE 5 4 12.5 34.0 stop 3 4 1")