#!/usr/bin/env python3 """A scripted stand-in "model" for the e2e client: a stdio token engine for `fake_runtime` (TEST TOOLING ONLY, not shipped). fake_runtime ... --engine fake_llm_engine.py --engine-arg TOKENIZER_DIR --engine-arg STRATA_NEXT_BINARY It speaks the stdio wire protocol (`READY`, `GEN [k=v...] ids`, `T `, `DONE ...`, `STOP`, `QUIT`), decodes the prompt with `strata-next model detokenize`, picks a canned reply from the last user turn and streams it token by token. It exists so the e2e client and the API stack can be exercised without a GPU and so the client's own checks can be tested; it says nothing about the real model. Prefix reuse is emulated as the common prefix with the previous prompt. """ import json import re import subprocess import sys import threading import time TOK, BIN = sys.argv[2], sys.argv[3] # argv[1] is --serve DELAY = 0.012 # seconds per token (cancel tests need a stream that lasts) def run(*args): return subprocess.run([BIN, "model", *args], capture_output=True, text=True, check=True).stdout.strip() def detok(ids): return json.loads(run("detokenize", TOK, ",".join(map(str, ids)))) def tok(text): return json.loads(run("tokenize", TOK, text, "--special")) def last_user(prompt): parts = prompt.split("<|im_start|>user\n") return parts[-1].split("<|im_end|>")[0] if len(parts) > 1 else prompt def reply(prompt, max_new): u = last_user(prompt) tools = "# Tools" in prompt think_open = prompt.rstrip().endswith("") pre = "I will answer directly.\n\n\n" if think_open else "" if "" in u: return pre + "The listing shows a Cargo.toml, a README.md and a src directory." if tools and "shell tool" in u: return pre + '\n\n\n["ls","-la"]\n\n\n' if tools and "read_file tool" in u: return pre + "\n\n\nsrc/main.rs\n\n\n1\n\n\n40\n\n\n" if tools and "update_plan tool" in u: plan = '[{"step":"inspect the code","status":"completed"},{"step":"fix the bug","status":"in_progress"},{"step":"run the tests","status":"pending"}]' return pre + f"\n\n\n{plan}\n\n\n" if tools and "Plan the work" in u: return pre + '\n\n\n[{"step":"write tests","status":"in_progress"},{"step":"implement","status":"pending"}]\n\n\n' if tools and "date" in u and "shell tool" in u: return pre + '\n\n\n["date"]\n\n\n' if "the quick brown fox jumps" in u: return pre + "the quick brown fox jumps" if "Count from 1 to 120" in u: return pre + "\n".join(str(i) for i in range(1, 121)) if "essay" in u: return pre + ("Programming languages evolved from machine code to assemblers to compilers. " * 60) if "BETA" in u: return pre + "BETA" if "GAMMA" in u: return pre + "GAMMA" if "name of my project" in u: return pre + "Leleka" if "what does it serve" in u.lower() or "And what does it" in u: return pre + "A Qwen model on one GPU" if "12 * 13" in u and "Now multiply" not in u: return pre + "12 * 13 = 156\n\n\n156" if think_open else "156" if "Now multiply" in u: return pre + "312" if "programming languages, comma" in u: return pre + "Rust, C, Python, Go, Zig" if "Summarize" in u or "Question:" in u: return pre + "The worker lives in control-plane/src/backend_worker.rs in the strata-control crate." return pre + "OK" def main(): print("READY 262144 stop", flush=True) state = {"stop": False} prev = [] lines = [] cond = threading.Condition() def reader(): for line in sys.stdin: line = line.strip() if line == "STOP": state["stop"] = True else: with cond: lines.append(line) cond.notify() if line == "QUIT": break with cond: lines.append("QUIT") cond.notify() threading.Thread(target=reader, daemon=True).start() while True: with cond: while not lines: cond.wait() line = lines.pop(0) if line == "QUIT": return if not line.startswith("GEN "): print("ERR unexpected request", flush=True) continue state["stop"] = False fields = line.split(" ") max_new = int(fields[1]) ids = [int(x) for x in fields[-1].split(",")] print(f"fake-llm: GEN max_new={max_new} prompt_tokens={len(ids)}", file=sys.stderr, flush=True) prompt = detok(ids) text = reply(prompt, max_new) out = tok(text) print(f"fake-llm: reply {len(out)} tokens", file=sys.stderr, flush=True) n = 0 while n < len(prev) and n < len(ids) and prev[n] == ids[n]: n += 1 reused = max(0, n - 1) prev = ids t0 = time.monotonic() # prefill takes time proportional to the non-reused prompt; emit progress for long ones todo = len(ids) - reused spent = 0 while spent < todo and not state["stop"]: step = min(2048, todo - spent) time.sleep(0.0004 * step) spent += step print(f"PP {reused + spent} {len(ids)} 1 {1000 * (time.monotonic() - t0):.1f}", flush=True) print(f"REUSED {reused}", flush=True) t1 = time.monotonic() produced = 0 finish = "stop" if state["stop"]: finish = "cancel" else: for t in out: if state["stop"]: finish = "cancel" break if produced >= max_new: finish = "length" break print(f"T {t}", flush=True) produced += 1 time.sleep(DELAY) print(f"DONE {produced} {len(ids)} {1000 * (t1 - t0):.1f} {1000 * (time.monotonic() - t1):.1f} {finish} 0 0 {reused} 0 0", flush=True) if __name__ == "__main__": main()