From 7d580590d2b5a4cb9efb373a08fac7db4f738aea Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 13 Nov 2026 00:17:01 +0100 Subject: [PATCH 1/2] Orchestrator sub-agent smoke: mock sub-agent server (P0), task builder, job, queue stub, run analysis Co-Authored-By: Claude Sonnet 5.5 --- .../orchestrator/analyze_orchestrator_run.py | 212 ++++++++++++++++++ .../orchestrator/make_orchestrator_tasks.py | 92 ++++++++ .../orchestrator/mock_subagent_server.py | 117 ++++++++++ .../orchestrator/orchestrator_smoke_job.sh | 126 +++++++++++ .../orchestrator/orchestrator_smoke_stub.sh | 9 + .../orchestrator/setup_orchestrator_inputs.sh | 39 ++++ 6 files changed, 595 insertions(+) create mode 100644 scripts/e2e/codex/orchestrator/analyze_orchestrator_run.py create mode 100644 scripts/e2e/codex/orchestrator/make_orchestrator_tasks.py create mode 100644 scripts/e2e/codex/orchestrator/mock_subagent_server.py create mode 100644 scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh create mode 100644 scripts/e2e/codex/orchestrator/orchestrator_smoke_stub.sh create mode 100644 scripts/e2e/codex/orchestrator/setup_orchestrator_inputs.sh diff --git a/scripts/e2e/codex/orchestrator/analyze_orchestrator_run.py b/scripts/e2e/codex/orchestrator/analyze_orchestrator_run.py new file mode 100644 index 00000000..7f954d9c --- /dev/null +++ b/scripts/e2e/codex/orchestrator/analyze_orchestrator_run.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Analyse one orchestrator sub-agent cell of the Codex smoke job (TEST TOOLING, stdlib only, read-only on the run). + + analyze_orchestrator_run.py RUN_DIR/LEL CELL_NAME [--json OUT.json] + +Reads //{cell.json, codex-events.jsonl, engine-slice.log, proxy/rounds.jsonl, proxy/rounds/*.resp.sse.gz} and +/stack/{requests.log, api.log, log-offsets.txt}. Prints markdown: the cell outcome, the agents and their request counts, one table row per model +request (gateway view from the proxy, queue wait and TTFT from the API log, cached tokens, prefix switch and import cost from the engine log), the +histogram of concurrently open requests, the tool-call integrity check and the Codex command failures. +""" +import argparse +import collections +import gzip +import json +import os +import re +from datetime import datetime, timezone + + +def jsonl(path): + if not os.path.exists(path): + return [] + out = [] + for line in open(path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def utc_ms(text): + return int(datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc).timestamp() * 1000) + + +def load_rounds(cell_dir): + rounds = [r for r in jsonl(os.path.join(cell_dir, "proxy", "rounds.jsonl")) if r.get("round")] + return sorted(rounds, key=lambda r: r["t_start_unix_ms"]) + + +def sse_items(path): + """The output items (output_item.done) of one stored response, plus the terminal event type.""" + if not os.path.exists(path): + return [], None + text = gzip.open(path, "rb").read().decode("utf-8", errors="replace") + items, terminal = [], None + for line in text.splitlines(): + if not line.startswith("data:"): + continue + try: + d = json.loads(line[5:].strip()) + except ValueError: + continue + if d.get("type") == "response.output_item.done": + items.append(d.get("item") or {}) + elif d.get("type") in ("response.completed", "response.incomplete", "response.failed"): + terminal = d["type"] + return items, terminal + + +def declared_tools(cell_dir): + """name -> parameter schema of every tool of the first request (namespace tools flattened as namespace.name).""" + path = os.path.join(cell_dir, "proxy", "rounds", "%04d.req.json.gz" % 1) + tools = {} + for t in json.loads(gzip.open(path, "rb").read()).get("tools", []): + if t.get("type") == "namespace": + for x in t.get("tools", []): + tools["%s.%s" % (t["name"], x["name"])] = x.get("parameters") or {} + elif t.get("name"): + tools[t["name"]] = t.get("parameters") or {} + return tools + + +def check_call(item, tools): + """-> list of problems of one function_call item (unknown tool, arguments not JSON, missing required, wrong type).""" + name = ("%s.%s" % (item["namespace"], item["name"])) if item.get("namespace") else item.get("name") + if name not in tools: + return ["unknown tool %s" % name] + try: + args = json.loads(item.get("arguments") or "") + except ValueError: + return ["%s: arguments are not JSON" % name] + if not isinstance(args, dict): + return ["%s: arguments are not an object" % name] + schema = tools[name] + bad = ["%s: missing %s" % (name, k) for k in schema.get("required", []) if k not in args] + types = {"string": str, "number": (int, float), "boolean": bool, "array": list, "object": dict} + for k, v in args.items(): + want = (schema.get("properties", {}).get(k) or {}).get("type") + if want in types and not isinstance(v, types[want]): + bad.append("%s: %s is not a %s" % (name, k, want)) + return bad + + +def integrity(cell_dir, rounds): + tools = declared_tools(cell_dir) + calls, problems, terminals = collections.Counter(), [], collections.Counter() + for r in rounds: + items, terminal = sse_items(os.path.join(cell_dir, "proxy", "rounds", "%04d.resp.sse.gz" % r["seq"])) + terminals[terminal or "none"] += 1 + for it in items: + if it.get("type") == "function_call": + calls[it.get("name")] += 1 + problems += ["round %d: %s" % (r["round"], p) for p in check_call(it, tools)] + return {"calls": dict(calls), "problems": problems, "terminals": dict(terminals)} + + +def roles(rounds, events): + """thread id -> 'root' or 'child N' (children in the order Codex reported them spawned).""" + root = rounds[0]["req_headers"].get("thread-id") if rounds else None + out = {root: "root"} + for e in events: + it = e.get("item") or {} + if it.get("type") == "collab_tool_call" and it.get("tool") == "spawn_agent" and e.get("type") == "item.completed": + for tid in it.get("receiver_thread_ids") or []: + out.setdefault(tid, "child %d" % len(out)) + return out + + +def api_requests(stack_dir, task): + """requests.log lines written during the cell (byte offsets recorded by the job).""" + marks = [l.split() for l in open(os.path.join(stack_dir, "log-offsets.txt")) if l.startswith(task + " ")] + start, end = [int(m[1]) for m in marks if m[-1] == "start"][-1], [int(m[1]) for m in marks if m[-1] == "end"][-1] + data = open(os.path.join(stack_dir, "requests.log"), "rb").read()[start:end].decode("utf-8", errors="replace") + return [d for d in (json.loads(l) for l in data.splitlines() if l.startswith("{")) if d.get("ev") == "request"] + + +def engine_requests(cell_dir): + """Engine log slice -> {rid: {prefix fields, engine JSON}} (the 'prefix request' line precedes the JSON line of its request).""" + out, pending = {}, {} + for line in open(os.path.join(cell_dir, "engine-slice.log"), encoding="utf-8", errors="replace"): + m = re.match(r"leleka-serve prefix request: n=(\d+) hit=(\w+) resume=(\d+) switched=(\w+) .*?import_ms=([\d.]+)", line) + if m: + pending = {"n": int(m[1]), "hit": m[2], "resume": int(m[3]), "switched": m[4] == "true", "import_ms": float(m[5])} + elif line.startswith("{") and '"ev":"request"' in line: + d = json.loads(line) + out[d["rid"]] = {**pending, **d} + pending = {} + return out + + +def join_requests(rounds, api, engine): + """Attach the API log record (by token counts and nearest end time) and the engine record (by rid) to every proxy round.""" + free = list(api) + for r in rounds: + resp = r.get("resp") or {} + key = (resp.get("input_tokens"), resp.get("output_tokens")) + cands = [a for a in free if (a.get("ptok"), a.get("otok")) == key] + a = min(cands, key=lambda x: abs(utc_ms(x["ts"]) - r["t_end_unix_ms"]), default=None) + if a: + free.remove(a) + r["api"], r["eng"] = a, (engine.get(a["rid"]) if a else None) + return rounds + + +def concurrency(rounds): + """Seconds spent with k requests open at the proxy (k = 0 is time between requests inside the span).""" + marks = sorted([(r["t_start_unix_ms"], 1) for r in rounds] + [(r["t_end_unix_ms"], -1) for r in rounds]) + hist, open_n, last = collections.Counter(), 0, marks[0][0] + for t, d in marks: + hist[open_n] += (t - last) / 1000.0 + open_n, last = open_n + d, t + return dict(sorted(hist.items())) + + +def command_failures(events): + done = [(e.get("item") or {}) for e in events if e.get("type") == "item.completed"] + cmds = [i for i in done if i.get("type") == "command_execution"] + return len(cmds), [i for i in cmds if i.get("exit_code") not in (0, None)] + + +def row(r, t0, role): + a, e = r.get("api") or {}, r.get("eng") or {} + return "| %d | %s | %.1f | %.1f | %.1f | %s | %s | %s | %s | %s | %s | %s |" % ( + r["round"], role, (r["t_start_unix_ms"] - t0) / 1000, (r["t_end_unix_ms"] - t0) / 1000, (r["t_end_unix_ms"] - r["t_start_unix_ms"]) / 1000, + a.get("q_ms", "?"), a.get("ttft_ms", "?"), (r.get("resp") or {}).get("input_tokens"), e.get("ctok", "?"), (r.get("resp") or {}).get("output_tokens"), + "%s/%s" % (e.get("switched", "?"), e.get("import_ms", "?")), ",".join(i.get("name") or i["type"] for i in (r.get("resp") or {}).get("items", []))) + + +def render(cell_dir, rounds, events, names, integ): + cj = json.load(open(os.path.join(cell_dir, "cell.json"))) + t0 = rounds[0]["t_start_unix_ms"] + out = ["cell %s: wall %.1f s, termination %s, accepted %s, codex rc %s" % (cj["task"], cj["wall_s"], cj["termination"], cj["accepted"], cj["codex_rc"]), ""] + per = collections.Counter(names.get(r["req_headers"].get("thread-id"), "?") for r in rounds) + out += ["requests per agent: %s" % dict(per), "tool calls: %s" % integ["calls"], "response terminals: %s" % integ["terminals"], + "tool-call problems: %s" % (integ["problems"] or "none"), "", "concurrently open requests (seconds): %s" % {k: round(v, 1) for k, v in concurrency(rounds).items()}, ""] + n_cmd, bad = command_failures(events) + out += ["commands run %d, non-zero exit %d" % (n_cmd, len(bad)), ""] + out += ["| # | agent | start s | end s | dur s | queue ms | ttft ms | prompt tok | cached | out tok | switched/import ms | output |", "|---|---|---|---|---|---|---|---|---|---|---|---|"] + out += [row(r, t0, names.get(r["req_headers"].get("thread-id"), "?")) for r in rounds] + return "\n".join(out) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("variant_dir") + ap.add_argument("cell") + ap.add_argument("--json") + a = ap.parse_args() + cell_dir = os.path.join(a.variant_dir, a.cell) + task = json.load(open(os.path.join(cell_dir, "cell.json")))["task"] + rounds, events = load_rounds(cell_dir), jsonl(os.path.join(cell_dir, "codex-events.jsonl")) + api = api_requests(os.path.join(a.variant_dir, "stack"), task) + join_requests(rounds, api, engine_requests(cell_dir)) + integ = integrity(cell_dir, rounds) + print(render(cell_dir, rounds, events, roles(rounds, events), integ)) + if a.json: + json.dump({"rounds": rounds, "integrity": integ, "concurrency": concurrency(rounds)}, open(a.json, "w"), indent=1) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/codex/orchestrator/make_orchestrator_tasks.py b/scripts/e2e/codex/orchestrator/make_orchestrator_tasks.py new file mode 100644 index 00000000..02ccb75e --- /dev/null +++ b/scripts/e2e/codex/orchestrator/make_orchestrator_tasks.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Build the task root of the orchestrator sub-agent smoke job (TEST TOOLING, stdlib only). + + make_orchestrator_tasks.py SOURCE_TASKS_ROOT OUT_TASKS_ROOT + +Copies smoke-mini (warm-up cell) and nestng-crm (single-agent control) from the frozen task root of the Codex comparison, and adds +`nestng-crm-orch`: the same seed, the same acceptance script, and a prompt that is the nestng-crm specification cut at the Backend and +Frontend sections (word for word) inside an orchestrator frame that tells the model to spawn two sub-agents. A fresh MANIFEST.sha256 is +written for the three tasks. The orchestrator prompt is derived from the control prompt, so the specification cannot drift. +""" +import os +import shutil +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..", "delta")) +import taskfile # noqa: E402 + +ORCH_ID = "nestng-crm-orch" +FRAME_HEAD = ( + "You are the orchestrator of a small team of sub-agents. Your job is to get the work below done by delegating it to " + "sub-agents and then integrating their results.\n\n" +) +PLAN = ( + "Plan for the team (follow it exactly):\n" + "1. In your very first response call the spawn_agent tool twice, so that both sub-agents start at the same time: one backend " + "worker for `backend/` and one frontend worker for `frontend/`. A sub-agent cannot see this conversation, so each message must " + "contain the full specification of its part (copy the Backend or the Frontend section below word for word), tell it to work " + "only inside its own directory, to run the commands that verify its part, and to reply with a short summary and the list of " + "files it changed.\n" + "2. Do not write the backend or the frontend yourself while the sub-agents work. Use wait_agent until both sub-agents have " + "finished.\n" + "3. Then write the short top-level README.md that says how to run everything and verify the result yourself: run `npm test`, " + "`npm run test:e2e` and `npm run build` in `backend/`, `npm run build` in `frontend/`, start the server and exercise it with " + "curl. If something fails, fix it yourself with small edits. Do not spawn any other sub-agents.\n\n" +) +CLOSING = "When all of this works, reply with a short summary of what was built and how it was verified." + + +def split_control_prompt(prompt): + """-> (intro, backend_section, frontend_section) of the nestng-crm prompt; fails loudly when the layout changes.""" + i_back, i_front, i_work = prompt.index("\nBackend ("), prompt.index("\nFrontend ("), prompt.index("\nWork step by step") + if not 0 < i_back < i_front < i_work: + raise ValueError("unexpected section order in the nestng-crm prompt") + return prompt[:i_back].strip("\n"), prompt[i_back:i_front].strip("\n"), prompt[i_front:i_work].strip("\n") + + +def orchestrator_prompt(control_prompt): + intro, backend, frontend = split_control_prompt(control_prompt) + return FRAME_HEAD + intro + "\n\n" + PLAN + backend + "\n\n" + frontend + "\n\n" + CLOSING + + +def orchestrator_task_md(control_md, control_prompt): + head, rest = control_md.split("## Prompt", 1) + head = head.replace("id: nestng-crm\n", "id: %s\n" % ORCH_ID).replace("title: Simple NestJS + Angular CRM", "title: Simple NestJS + Angular CRM, orchestrator with two sub-agents") + ext = rest.split("", 1)[1] + note = "\nOrchestrator variant of nestng-crm (docs/experiments/orchestrator-subagents-smoke.md): same seed and acceptance, prompt built by make_orchestrator_tasks.py.\n\n" + return head.rstrip("\n") + "\n" + note + "## Prompt\n\n" + orchestrator_prompt(control_prompt) + "\n" + ext + + +def copy_task(src_root, out_root, task_id, as_id=None): + """Copy a task directory (no reference solution, no node_modules; the source files are read-only, the copies are not).""" + dst = os.path.join(out_root, as_id or task_id) + shutil.copytree(os.path.join(src_root, task_id), dst, ignore=shutil.ignore_patterns("reference", "node_modules"), copy_function=shutil.copyfile) + return dst + + +def write_manifest(out_root): + lines = taskfile.manifest_lines(out_root) + with open(os.path.join(out_root, "MANIFEST.sha256"), "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines) + "\n") + return lines + + +def build(src_root, out_root): + os.makedirs(out_root) + copy_task(src_root, out_root, "smoke-mini") + copy_task(src_root, out_root, "nestng-crm") + orch_dir = copy_task(src_root, out_root, "nestng-crm", ORCH_ID) + control_md = open(os.path.join(src_root, "nestng-crm", "task.md"), encoding="utf-8", newline="").read() + prompt = taskfile.read_task(src_root, "nestng-crm")["prompt"] + with open(os.path.join(orch_dir, "task.md"), "w", encoding="utf-8", newline="\n") as f: + f.write(orchestrator_task_md(control_md, prompt)) + return write_manifest(out_root) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print(__doc__) + sys.exit(2) + out = build(sys.argv[1], sys.argv[2]) + print("%d manifest lines" % len(out)) diff --git a/scripts/e2e/codex/orchestrator/mock_subagent_server.py b/scripts/e2e/codex/orchestrator/mock_subagent_server.py new file mode 100644 index 00000000..bcbc22a3 --- /dev/null +++ b/scripts/e2e/codex/orchestrator/mock_subagent_server.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""A throw-away /v1/responses server that makes the Codex CLI spawn sub-agents (TEST TOOLING, no model, no GPU, stdlib only). + + mock_subagent_server.py PORT CAPTURE.jsonl [N_CHILDREN] [CHILD_DELAY_S] + +Step P0 of docs/experiments/orchestrator-subagents-smoke.md. The root thread (the thread of the first request) is scripted: its first request is +answered with N_CHILDREN `multi_agent_v1.spawn_agent` calls in one response, the next request with a `wait_agent` call on the agent ids that +the spawn outputs returned, the last one with a final text. Every other thread (a sub-agent) answers with a one-line message after +CHILD_DELAY_S seconds. CAPTURE.jsonl gets one line per request: arrival and finish time, thread id, agent name, input and tool counts, the +tool names called in the answer. It shows whether the CLI fans out under `codex exec`, how many requests overlap and what the children send. +""" +import json +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +PORT, CAPTURE = int(sys.argv[1]), sys.argv[2] +N_CHILDREN = int(sys.argv[3]) if len(sys.argv) > 3 else 2 +CHILD_DELAY_S = float(sys.argv[4]) if len(sys.argv) > 4 else 3.0 +LOCK = threading.Lock() +T0 = time.time() +ROOT_REQUESTS = {"n": 0, "thread": None} + + +def is_root_thread(thread_id): + """The thread of the first request is the root; the sub-agents send their own thread ids (their agent_name header says /root too).""" + with LOCK: + if ROOT_REQUESTS["thread"] is None: + ROOT_REQUESTS["thread"] = thread_id + return ROOT_REQUESTS["thread"] == thread_id + + +def spawned_ids(body): + """Agent ids in the function_call_output items of the request (the spawn_agent results).""" + ids = [] + for item in body.get("input") or []: + if item.get("type") == "function_call_output": + out = item.get("output") + text = out if isinstance(out, str) else json.dumps(out) + try: + ids.append(json.loads(text).get("agent_id")) + except (ValueError, AttributeError): + pass + return [i for i in ids if i] + + +def call_item(n, name, args): + return {"id": "fc_%d" % n, "type": "function_call", "call_id": "call_%d" % n, "name": name, "namespace": "multi_agent_v1", + "arguments": json.dumps(args), "status": "completed"} + + +def text_item(text): + return {"id": "msg_1", "type": "message", "role": "assistant", "status": "completed", + "content": [{"type": "output_text", "text": text, "annotations": []}]} + + +def root_answer(body): + """The scripted root: spawn, then wait, then finish.""" + with LOCK: + ROOT_REQUESTS["n"] += 1 + k = ROOT_REQUESTS["n"] + if k == 1: + return [call_item(i, "spawn_agent", {"message": "mock task %d: reply with one word" % i}) for i in range(N_CHILDREN)] + ids = spawned_ids(body) + waited = any(i.get("type") == "function_call" and i.get("name") == "wait_agent" for i in body.get("input") or []) + if ids and not waited: + return [call_item(10, "wait_agent", {"targets": ids, "timeout_ms": 60000})] + return [text_item("mock root finished")] + + +def sse(output): + resp = {"id": "resp_mock", "object": "response", "status": "completed", "model": "mock", "output": output, + "usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 2, + "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 12}} + events = [("response.created", {"response": {**resp, "status": "in_progress", "output": []}})] + for i, item in enumerate(output): + events.append(("response.output_item.done", {"output_index": i, "item": item})) + events.append(("response.completed", {"response": resp})) + return b"".join(("event: %s\ndata: %s\n\n" % (n, json.dumps({"type": n, "sequence_number": i, **d}))).encode() + for i, (n, d) in enumerate(events)) + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_POST(self): + t_in = time.time() - T0 + body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0)))) + agent = "root" if is_root_thread(self.headers.get("thread-id")) else "child" + if agent == "root": + output = root_answer(body) + else: + time.sleep(CHILD_DELAY_S) + output = [text_item("mock child done")] + data = sse(output) + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + self.record(body, agent, t_in, output) + + def record(self, body, agent, t_in, output): + rec = {"t_in_s": round(t_in, 3), "t_out_s": round(time.time() - T0, 3), "agent": agent, "thread": self.headers.get("thread-id"), + "n_input": len(body.get("input") or []), "n_tools": len(body.get("tools") or []), + "prefix_sha": hash(json.dumps(body.get("tools"), sort_keys=True)), + "called": [i.get("name") for i in output if i.get("type") == "function_call"], + "tool_outputs": [str(i.get("output"))[:300] for i in body.get("input") or [] if i.get("type") == "function_call_output"]} + with LOCK, open(CAPTURE, "a") as f: + f.write(json.dumps(rec) + "\n") + + +ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh b/scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh new file mode 100644 index 00000000..fd612a75 --- /dev/null +++ b/scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Orchestrator sub-agent smoke job (docs/experiments/orchestrator-subagents-smoke.md). Test tooling, never in serving. Runs ON the 5090 server inside a holder +# job (inherits the sealed KAR memfd), derived from cmp_codex_job_profile.sh (arm "ours" only): the release package, `leleka up --foreground --kar-fd`, +# shipped configuration, the cell runner of the Codex comparison (logging proxy, temperature 0, real Codex CLI 0.163.0, task acceptance). +# +# ONE BLOCK = one stack start, then three cells: the warm-up (smoke-mini), the ORCHESTRATOR cell (nestng-crm-orch: Codex told to spawn a backend and a frontend +# sub-agent, `features.multi_agent = true`, `agents.max_threads = 3`) and, when CMP_CONTROL=1, the single-agent CONTROL (nestng-crm, the unchanged task). +# Guards before any cell: input digests (INPUTS.sha256), task manifest, Codex binary digest, package PROVENANCE git_commit == CMP_OURS_TAG, SHA256SUMS of the +# package, and after the start the engine environment line and the run configuration (leleka.json) against the references of the owner-default series. +set -uo pipefail +TAG=${CMP_OURS_TAG:-83bdd85bb482} +TARBALL=${CMP_TARBALL:-/data/leleka-e2e/prefill-latency/release-s22/leleka-0.1.0-83bdd85bb482-linux-x86_64.tar.xz} +ORCH=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke +RUN=${CMP_RUN:-/data/leleka-e2e/prefill-latency/runs/codex-orchestrator-subagents-smoke-crm-release-$TAG} +CMP=/data/leleka-e2e/codex-compare +CODEX=/home/para/work/codex-e2e/bin/codex +CODEX_SHA=399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215 +LOCK=/data/leleka-e2e/gpu.lock +G=$HOME/work/gpu-runs +CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib +WALL_ORCH=${CMP_WALL_ORCH:-1500}; WALL_CONTROL=${CMP_WALL_CONTROL:-900}; ROUNDS=${CMP_ROUNDS:-400} +NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin 2>/dev/null | tail -1) +NM=$CMP/nm +VAR=LEL +mkdir -p "$RUN" "$RUN/$VAR" +exec > >(tee -a "$RUN/job-$VAR.log") 2>&1 +log() { echo "[orch $(date -u +%T)] $*"; } +note() { echo "[$(date -u +%FT%TZ)] [DEV orchestrator-smoke] $*" >>/data/leleka-e2e/decode/notes.md; } +die() { echo "REFUSED: $1"; exit "${2:-3}"; } + +# ---- guards (before the GPU lock) ------------------------------------------------------------------------------------------------------------- +( cd "$CMP" && sha256sum --quiet -c INSTALL.sha256 ) || die "installed comparison tools differ from INSTALL.sha256" +( cd "$ORCH" && sha256sum --quiet -c INPUTS.sha256 ) || die "orchestrator inputs differ from INPUTS.sha256" +python3 -I "$ORCH/tools/delta/taskfile.py" check "$ORCH/tasks" >"$RUN/tasks-check.txt" 2>&1 || die "task files differ from their manifest" +[ -x "$CODEX" ] && [ "$(sha256sum "$CODEX" | cut -c1-64)" = "$CODEX_SHA" ] || die "codex binary missing or not the pinned 0.163.0 digest" +[ -n "$NODE_BIN" ] && [ -x "$NODE_BIN/node" ] && [ -f "$CMP/toolchain/NESTNG_OK" ] || die "node toolchain or NESTNG_OK missing" +[ -d "$NM/backend/node_modules" ] && [ -d "$NM/frontend/node_modules" ] || die "shared node_modules missing" +FD=${LELEKA_STRA169_KAR_FD:-} +readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || die "needs the holder's sealed memfd" +[ -d "$G/MODEL.lock" ] || die "MODEL.lock is not held" +got=0 +for _ in $(seq 1 4320); do + if mkdir "$LOCK" 2>/dev/null; then echo "codex-orchestrator-smoke $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi + sleep 5 +done +[ $got = 1 ] || die "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)" +SUP_PID=; MON_PID= +stop_stack() { + if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi + SUP_PID= +} +cleanup() { + stop_stack + [ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null + pkill -KILL -f "$CMP/ours-prefix-$TAG/bin/" 2>/dev/null + sleep 3 + rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null + note "orchestrator smoke block ended: $RUN" +} +trap cleanup EXIT +note "orchestrator smoke started: $RUN release=$TAG wall_orch=$WALL_ORCH control=${CMP_CONTROL:-1}; holds gpu.lock" +if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then die "something uses the GPU"; fi +if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then die "a stack process exists"; fi +for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && die "port $p in use"; done +export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/cmp-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1 +{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; $CODEX --version; node --version; sha256sum "$CODEX"; } | tee "$RUN/$VAR/host.txt" +STK=$RUN/$VAR/stack; mkdir -p "$STK" +nvidia-smi --query-gpu=timestamp,temperature.gpu,clocks.sm,clocks.mem,power.draw,utilization.gpu --format=csv -l 10 >"$STK/mon.csv" 2>/dev/null & MON_PID=$! + +# ---- the release package (prepared once into $CMP/ours-*-$TAG by the owner-default series, reused) -------------------------------------------- +P=$CMP/ours-pkg-$TAG; AS=$CMP/ours-assets; ST=$CMP/ours-state-$TAG; PFX=$CMP/ours-prefix-$TAG; BIN=$P/bin +PROV=/data/leleka-e2e/prefill-latency/tools/prov_commit.py +[ -x "$P/bin/leleka" ] || { mkdir -p "$P" && tar -xJf "$TARBALL" -C "$P" --strip-components=1 || die "unpack failed" 5; } +python3 -I "$PROV" "$P/PROVENANCE.json" "$TAG" >/dev/null || { head -20 "$P/PROVENANCE.json"; die "package PROVENANCE git_commit does not match $TAG" 5; } +log "package provenance: commit $(python3 -I $PROV $P/PROVENANCE.json), tarball sha256 $(sha256sum $TARBALL | cut -c1-16)" +( cd "$P" && sha256sum --quiet -c SHA256SUMS && echo "SHA256SUMS ok" ) || die "package SHA256SUMS" 5 +"$BIN/leleka" version | tee "$STK/version.txt"; sha256sum "$TARBALL" | tee -a "$STK/version.txt" +[ "$(sha256sum "$TARBALL" | cut -c1-64)" = "$(cat $ORCH/reference/tarball.sha256)" ] || die "tarball sha256 differs from the owner-default series" 5 +COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD" +[ -f "$ST/leleka.json" ] || die "state of $TAG is not prepared (run the owner-default series first)" 6 +log "leleka up --foreground (shipped configuration)" +t0=$(date +%s) +setsid "$BIN/leleka" up --foreground $COMMON --timeout-s 1800 >"$STK/up-foreground.txt" 2>&1 & +SUP_PID=$! +ready=0 +for _ in $(seq 1 700); do + if "$PFX/bin/leleka" status --state-dir "$ST" >/dev/null 2>&1; then ready=1; break; fi + kill -0 "$SUP_PID" 2>/dev/null || break + sleep 3 +done +[ $ready = 1 ] || { log "NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$STK/up-foreground.txt" | cut -c1-240; exit 7; } +log "ready after $(( $(date +%s) - t0 )) s"; echo "$(( $(date +%s) - t0 ))" >"$STK/ready_s.txt" +"$PFX/bin/leleka" status --state-dir "$ST" >"$STK/status.txt" 2>&1; "$PFX/bin/leleka" status --state-dir "$ST" --json >"$STK/status.json" 2>&1 +"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick.txt" 2>&1 + +# ---- configuration proof: the engine environment line and the run configuration must equal the owner-default series -------------------------------- +grep -m1 'engine environment:' "$STK/up-foreground.txt" >"$STK/engine-environment.txt" +if ! cmp -s "$STK/engine-environment.txt" "$ORCH/reference/engine-environment.txt"; then + log "ENGINE ENVIRONMENT DIFFERS from the owner-default series"; diff "$STK/engine-environment.txt" "$ORCH/reference/engine-environment.txt" | cut -c1-400; exit 8 +fi +cp "$ST/leleka.json" "$STK/leleka.json"; cp "$ST/profile.json" "$STK/profile.json" 2>/dev/null +[ "$(sha256sum "$ST/leleka.json" | cut -c1-64)" = "$(cat $ORCH/reference/leleka-json.sha256)" ] || { log "leleka.json DIFFERS from the owner-default series"; exit 8; } +log "configuration proof ok: engine environment line and leleka.json identical to the owner-default series" + +run_cell() { # $1 task $2 rep $3 wall s $4 extra config ('|' separates lines) $5 cell dir + local task=$1 rep=$2 wall=$3 extra=$4 cell=$5 link="" t1 rc + [ -f "$cell/cell.json" ] && { log "cell $cell already done: skipped"; return; } + case "$task" in nestng-crm*) link="--link-tree backend/node_modules=$NM/backend/node_modules --link-tree frontend/node_modules=$NM/frontend/node_modules";; esac + echo "$task $(wc -c <"$ST/logs/requests.log") $(wc -c <"$ST/logs/engine.log") $(date -u +%FT%TZ) start" >>"$STK/log-offsets.txt" + t1=$(date +%s) + E2E_API_KEY=$KEY CLD_CODEX=$CODEX timeout $((wall + 900)) python3 -I "$ORCH/tools/delta/cell.py" --cell-dir "$cell" --variant "$VAR" --task "$task" --rep "$rep" \ + --tasks-root "$ORCH/tasks" --upstream http://127.0.0.1:8081 --upstream-model qwen-iq3 --codex-bin "$CODEX" --codex-sha256 "$CODEX_SHA" --wall-limit "$wall" --max-rounds "$ROUNDS" \ + --engine-log "$ST/logs/engine.log" --active-dir "$RUN/active-$VAR" --config-extra "$extra" $link >"$cell.out" 2>&1; rc=$? + echo "$task $(wc -c <"$ST/logs/requests.log") $(wc -c <"$ST/logs/engine.log") $(date -u +%FT%TZ) end" >>"$STK/log-offsets.txt" + log "cell $task r$rep rc=$rc $(( $(date +%s) - t1 )) s: $(tail -1 "$cell.out" | cut -c1-200)" +} +KEY=$(cat "$ST/api-key") +BASE_EXTRA='model_auto_compact_token_limit = 100000000' +run_cell smoke-mini 101 3000 "$BASE_EXTRA" "$RUN/$VAR/smoke-mini-r101" +run_cell nestng-crm-orch 1 "$WALL_ORCH" "$BASE_EXTRA|features.multi_agent = true|agents.max_threads = 3" "$RUN/$VAR/nestng-crm-orch-r1" +[ "${CMP_CONTROL:-1}" = 1 ] && run_cell nestng-crm 1 "$WALL_CONTROL" "$BASE_EXTRA" "$RUN/$VAR/nestng-crm-r1" +cp "$ST/logs/engine.log" "$STK/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$STK/requests.log" 2>/dev/null; cp "$ST/logs/api.log" "$STK/api.log" 2>/dev/null +"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick-end.txt" 2>&1 +stop_stack +log "done" diff --git a/scripts/e2e/codex/orchestrator/orchestrator_smoke_stub.sh b/scripts/e2e/codex/orchestrator/orchestrator_smoke_stub.sh new file mode 100644 index 00000000..d1ac4e0c --- /dev/null +++ b/scripts/e2e/codex/orchestrator/orchestrator_smoke_stub.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Queue stub of the orchestrator sub-agent smoke (docs/experiments/orchestrator-subagents-smoke.md): the real Codex CLI 0.163.0 told to act as an orchestrator on the +# nestng-crm task (spawn a backend and a frontend sub-agent), release 83bdd85bb482 (owner default), 1 repetition, orchestrator cell wall limit 1500 s, then the +# single-agent control cell (unchanged nestng-crm, wall limit 900 s). The job refuses to start when an input differs from INPUTS.sha256 or the PROVENANCE commit is not 83bdd85bb482. +unset CMP_ARM CMP_TASKS CMP_OPTIONAL CMP_REPS CMP_VANILLA_LOSSY CMP_WALL CMP_ROUNDS CMP_RUN CMP_TARBALL CMP_ARM_PROFILE_SET CMP_ARM_PROFILE_OFF CMP_OURS_TAG CMP_CONTROL CMP_WALL_ORCH CMP_WALL_CONTROL +export CMP_OURS_TAG=83bdd85bb482 CMP_CONTROL=1 CMP_WALL_ORCH=1500 CMP_WALL_CONTROL=900 CMP_ROUNDS=400 +J=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke/tools/orchestrator_smoke_job.sh +[ "$(sha256sum $J | cut -c1-64)" = "9a3590bbb5c1fbb9b2f02809f8f4203abf7d2e5d502754137ba853b998a45772" ] || { echo "job script differs from the reviewed one"; exit 3; } +exec bash $J diff --git a/scripts/e2e/codex/orchestrator/setup_orchestrator_inputs.sh b/scripts/e2e/codex/orchestrator/setup_orchestrator_inputs.sh new file mode 100644 index 00000000..459533d0 --- /dev/null +++ b/scripts/e2e/codex/orchestrator/setup_orchestrator_inputs.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Run ON the 5090 server, once: setup_orchestrator_inputs.sh REPO_SCRIPT_DIR +# Builds the frozen inputs of the orchestrator sub-agent smoke job under /data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke (AGENTS.md: a measurement +# input lives in one named directory, is read-only and is recorded with its sha256; the job refuses to start when one differs): +# tools/delta/{cell.py,logproxy.py,taskfile.py} the cell runner of the Codex comparison; logproxy.py additionally writes UNIX wall-clock milliseconds +# (t_start_unix_ms, t_end_unix_ms) into every rounds.jsonl line, so requests can be joined with requests.log +# tools/config.toml.tmpl the Codex config template of the comparison +# tasks/ smoke-mini, nestng-crm (control) and nestng-crm-orch (make_orchestrator_tasks.py), with a fresh MANIFEST.sha256 +# reference/ what the owner-default series of release 83bdd85bb482 recorded: engine environment line, leleka.json digest, tarball digest +# INPUTS.sha256 digest of every file above +set -euo pipefail +SRC=${1:?directory with make_orchestrator_tasks.py} +TAG=83bdd85bb482 +ORCH=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke +CMP=/data/leleka-e2e/codex-compare +OWNER_RUN=/data/leleka-e2e/prefill-latency/runs/e2e-codex-ttt-and-crm-release-$TAG-owner-default/LEL/stack-r1 +[ -e "$ORCH/INPUTS.sha256" ] && { echo "already frozen: $ORCH/INPUTS.sha256"; exit 0; } +mkdir -p "$ORCH/tools/delta" "$ORCH/reference" +cp "$CMP/delta/cell.py" "$CMP/delta/taskfile.py" "$ORCH/tools/delta/" +python3 -I - "$CMP/delta/logproxy.py" "$ORCH/tools/delta/logproxy.py" <<'PY' +import sys +src = open(sys.argv[1]).read() +a = '"t_start_ms": t_start,\n' +b = 'rec.update({"t_first_byte_ms": t_first, "t_end_ms": st.ms(),' +assert src.count(a) == 1 and src.count(b) == 1 +src = src.replace(a, a + ' "t_start_unix_ms": int(time.time() * 1000),\n') +src = src.replace(b, 'rec["t_end_unix_ms"] = int(time.time() * 1000)\n ' + b) +open(sys.argv[2], "w").write(src) +PY +python3 -I -c "import ast,sys; ast.parse(open('$ORCH/tools/delta/logproxy.py').read())" +cp "$CMP/config.toml.tmpl" "$ORCH/tools/config.toml.tmpl" +python3 -I "$SRC/make_orchestrator_tasks.py" "$CMP/tasks" "$ORCH/tasks" +grep -m1 'engine environment:' "$OWNER_RUN/up-foreground.txt" >"$ORCH/reference/engine-environment.txt" +sha256sum "$CMP/ours-state-$TAG/leleka.json" | cut -c1-64 >"$ORCH/reference/leleka-json.sha256" +sed -n 's/^\([0-9a-f]\{64\}\) .*\.tar\.xz$/\1/p' "$OWNER_RUN/version.txt" >"$ORCH/reference/tarball.sha256" +[ "$(wc -c <"$ORCH/reference/tarball.sha256")" = 65 ] || { echo "no tarball digest in $OWNER_RUN/version.txt"; exit 1; } +( cd "$ORCH" && find tools tasks reference -type f ! -name orchestrator_smoke_job.sh | sort | xargs sha256sum >INPUTS.sha256 ) +chmod -R a-w "$ORCH/tools/delta" "$ORCH/tasks" "$ORCH/reference" "$ORCH/INPUTS.sha256" +( cd "$ORCH" && sha256sum --quiet -c INPUTS.sha256 && echo "frozen: $(wc -l Date: Fri, 13 Nov 2026 01:53:12 +0100 Subject: [PATCH 2/2] Orchestrator sub-agent smoke: result page (model spawns two workers, no tool-call defects, queue gain about 1.08x, no-go for the full 6g matrix) Co-Authored-By: Claude Sonnet 5.5 --- .../orchestrator-subagents-smoke.md | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 docs/experiments/orchestrator-subagents-smoke.md diff --git a/docs/experiments/orchestrator-subagents-smoke.md b/docs/experiments/orchestrator-subagents-smoke.md new file mode 100644 index 00000000..918d839c --- /dev/null +++ b/docs/experiments/orchestrator-subagents-smoke.md @@ -0,0 +1,108 @@ +# Orchestrator mode with sub-agents: smoke test of Qwen3.5 on Leleka (plan 6g, step P1) + +Question of the owner (2026-11-13): can OUR model (Qwen3.5 MoE IQ3, served by Leleka release 83bdd85bb482) work in the Codex orchestrator mode, i.e. when Codex is told that it +is an orchestrator and spawns sub-agents? In that mode concurrent requests reach Leleka for certain, which is the premise of the multiplexing idea (plan 6g, +`docs/experiments/async-park-compression-and-orchestrator-bench.md` section B). This page is the cheap smoke run that comes before the 3-3.5 GPU-hour matrix of that page. + +Labels: **M** = measured in this run (source named), **C** = read from the Codex binary or its documentation, **E** = estimate by arithmetic from M numbers. + +## 0. Result + +| Question | Answer | +|---|---| +| Does the model orchestrate? | **Yes, on the first try.** In its very first response it wrote one sentence and called `multi_agent_v1.spawn_agent` twice (parallel tool calls), a backend worker and a frontend worker, each with a self-contained 3.6 KB / 3.0 KB specification and the right directory restriction (M, round 1, 8.9 s, 1,849 output tokens). It then used `wait_agent` twice and `close_agent` twice, and did the integration (README, builds, tests) itself. | +| How many sub-agents | 2 (as asked; `agents.max_threads = 3` was the cap). 122 model requests: orchestrator 34, backend worker 69, frontend worker 19. | +| Tool-call integrity | **No defect.** 122 of 122 responses `response.completed`; 161 function calls (155 `exec_command`, 2 `spawn_agent`, 2 `wait_agent`, 2 `close_agent`), every name declared, every `arguments` valid JSON with the required fields and types (checker in `analyze_orchestrator_run.py`); no `generation failed` in `api.log` during the cell; no 429, no timeout. | +| Concurrency at the gateway | Up to **3 requests open at once** (18 s), 2 or more open for **250 s = 32 % of the wall**; 44 of 122 requests overlapped another one in time; the engine had work for 92 % of the wall (M, proxy timestamps). | +| How Leleka's queue handled it | FIFO, one generation at a time, as designed. Queue wait p50 2 ms, p90 5.0 s, max 51 s (sum 268 s); 42 of 122 requests waited more than 1 s, 4 more than 10 s. TTFT p50 0.68 s, p90 6.3 s, max 51.8 s. While both workers were alive each request took 13.0 s instead of 6.1 s (6.5 s queue + 6.5 s service): each session ran at half pace. | +| Cache switch cost | **Negligible.** 48 of 122 requests (39 %) switched the live session; import 29 ms median, 48 ms maximum (1.4 ms without a switch); cached share of the prompt tokens 98.1 %. Expert tier VRAM share 87.6 % on a switch against 90.4 % without (-2.8 points). | +| End result | Codex exit 0 after **791 s**. Acceptance **55/56 strict, 56/56 relaxed** (the gate of the ledger); the one strict failure is the board check that the single-agent cells fail too. | +| Faster than one agent? | **No.** Same boot, same task, single agent: 766 s, 96 requests, 55/56 strict, 56/56 relaxed. Orchestrator 791 s (1.03x slower, inside the run-to-run noise: the stored owner-default single-agent cells of this release took 427 / 539 / 651 s). The orchestrator generated 32 % more tokens (127,288 against 96,647) at the same decode speed (186 and 184 tok/s median), so the engine was simply busier: 724 s against 664 s of engine time. Against the sequential execution of the same 122 requests the overlap is worth about **1.08x** (E, section 5). | +| Go / no-go for the big 6g benchmark | **No-go for the full matrix as designed (3-3.5 GPU-h); the premise is answered.** See section 7. | + +## 1. How Codex 0.163.0 exposes sub-agents + +* **Feature flags (C, `codex features list` on the harness binary):** `multi_agent` is `stable` and **on by default**; `multi_agent_v2` is `stable` and off (the newer tool surface with path addressing, not used here). Because of that every request of this version already carried the `multi_agent_v1` tool namespace (10 KB) in the earlier runs; the model had simply never been asked to use it (`docs/experiments/multiplexing-feasibility.md`: no `multi_agent_v1` call in 750 recorded rounds). +* **Tools (M, tool list of the first request):** namespace `multi_agent_v1` with `spawn_agent` (`message` or `items`, `fork_context`, `model`, `reasoning_effort`), `wait_agent` (`targets` list of agent ids, `timeout_ms` default 30 s, min 10 s, max 1 h; returns when ANY of them reaches a final state), `send_input`, `resume_agent`, `close_agent`. A sub-agent has its own thread id; its tool list has 7 entries against the root's 8, because the whole `multi_agent_v1` namespace is missing (no spawning at depth 1, M). +* **When the model spawns (C, text of the `spawn_agent` description):** "Do not spawn sub-agents unless the user or applicable AGENTS.md/skill instructions explicitly ask for sub-agents, delegation, or parallel agent work." The prompt must ask. The public documentation says the same (spawn on request, "spawn two agents", "one agent per point", then wait and summarise). +* **Config (C, public docs and `--strict-config` on the binary):** `[agents]`: `enabled` (default true), `max_threads` (legacy alias of `max_concurrent_threads_per_session`; concurrent spawned threads), `max_depth` (default 1), `default_subagent_model`, `default_subagent_reasoning_effort`; `features.multi_agent`. This run set `features.multi_agent = true` and `agents.max_threads = 3` through `--config-extra`; `codex --strict-config exec` accepted both. +* **`codex exec` (non-interactive) works (M, step P0 and the run):** the root turn ends when the root model ends it; children run as threads of the same process, each with its own `thread-id` / `session-id` HTTP headers and `x-codex-turn-metadata` (`agent_name` is `/root` in every request of this version, so the thread id, not the name, tells the agents apart). Children's own tool calls are NOT in the root's `codex --json` event stream (38 `command_execution` events against 155 `exec_command` calls); the proxy log and the rollout files are the complete record. +* **Step P0 (CPU only, done):** `mock_subagent_server.py` scripts a root that spawns two children and waits. The real binary fanned out under `codex exec`, both children's requests overlapped for the whole 3-4 s the mock held them, and the spawn results carry `{"agent_id", "nickname"}`. This validated the config keys and the proxy chain before GPU time was spent. + +## 2. The job + +* Queue stub `codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482` (server `~/work/gpu-runs/holder2/jobs/`, inserted into `PRIORITY` directly behind the running CPU-kernel A/B job; backup `PRIORITY.bak-orchestrator-smoke`). Job script `scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh` (sha256 9a3590bb... pinned in the stub), derived from `cmp_codex_job_profile.sh`: release package, `leleka up --foreground --kar-fd`, shipped configuration, the cell runner `cell.py` of the Codex comparison (logging proxy, temperature 0, real Codex CLI 0.163.0 sha256 399ff69c..., task acceptance). +* **Provenance and configuration proof (M, first lines of `job-LEL.log`):** package `PROVENANCE.json` `git_commit` 83bdd85bb48226a41bcec6034d87e1ea6528b570 equals the tag; tarball sha256 3837a32b... equals the one recorded by the owner-default series; `SHA256SUMS` ok; the line `engine environment:` of `up-foreground.txt` is byte-identical to the owner-default series (`LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no`, `PCIE_FRAC=0.65`, `SEED=off`, ...) and `leleka.json` has the same sha256 (the job exits 8 before any cell otherwise). Inputs (cell runner, tasks, references) are frozen read-only with `INPUTS.sha256`; the job refuses to start when one differs. +* **Task `nestng-crm-orch`** (built by `make_orchestrator_tasks.py` from the frozen `nestng-crm`; same seed, same acceptance script, so the specification cannot drift): the original prompt cut at its Backend and Frontend sections, inside an orchestrator frame: "You are the orchestrator of a small team of sub-agents ... in your very first response call the spawn_agent tool twice ... each message must contain the full specification of its part ... do not write the backend or the frontend yourself while the sub-agents work; use wait_agent until both have finished; then write README.md and verify the result yourself; do not spawn any other sub-agents." +* Cells in ONE stack start: warm-up `smoke-mini`, orchestrator cell (wall limit 1,500 s), and, because it fitted, the single-agent control (unchanged `nestng-crm`, wall limit 900 s). One repetition each, so everything below is n = 1. +* Recording: the logging proxy of `cell.py`, patched only to add UNIX milliseconds (`t_start_unix_ms`, `t_end_unix_ms`) to every `rounds.jsonl` line (request and response bytes unchanged), so requests can be joined with `requests.log` (queue, TTFT) and `engine-slice.log` (prefix switch, import ms, tier shares). The analysis is `analyze_orchestrator_run.py`. +* Run: 2026-11-13 00:20-00:49 UTC, RTX 5090 server, ready after 118 s, orchestrator cell 791 s, control 766 s. Data: `/data/leleka-e2e/prefill-latency/runs/codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482/` (`LEL//proxy`, `LEL/stack/{requests.log,engine.log,api.log,log-offsets.txt}`, `analysis/{orch,control}.{md,json}`, `analysis/accept/`). + +## 3. Timeline of the orchestrator cell (M) + +| t (s) | Event | +|---:|---| +| 0.0 | Root request 1 (10.6k prompt tokens). | +| 8.9 | Root answers: one message and two `spawn_agent` calls in one response. Both workers start at once. | +| 8.9-29 | The three sessions interleave on the one engine: the root inspects the scaffold (6 requests), the workers start (backend and frontend each begin with a 7.7k / 7.6k-token prompt, below the 8,192-token cache block, so `cached = 0`). | +| 26-81 | The backend worker writes one large file in a single request (10,239 tokens, 54 s). The frontend worker's request 12 arrives behind it and waits **51 s** (first-come-first-served, no preemption). | +| 29-260 | Both workers alive: requests alternate between them, each takes 13 s instead of 6 s. | +| 260 | The frontend worker finishes (19 requests, "Build is green"); root `wait_agent` returns for it. | +| 260-602 | Only the backend worker (and the root's idle `wait_agent`) is active: no queue wait (0 ms), 6.1 s per request. This tail is the critical path. | +| 602-790 | Root closes both workers, writes README.md and verifies everything itself (34 requests in all), including an in-process supertest shim because the sandbox forbids sockets (the same constraint hits the control). | + +The split was unbalanced (backend 602 s of its own session against frontend 260 s) and the root's final verification is serial; both limit what any scheduler could gain on this task. + +Per agent (M): root 34 requests, 30,199 output tokens, 179 s engine time; backend worker 69 / 73,135 / 413 s; frontend worker 19 / 23,954 / 132 s. Engine time in total 724 s of the 790 s span (92 %); the control 664 s of 766 s (87 %). + +## 4. Numbers against the single-agent control (same boot) + +| | Orchestrator | Control (single agent) | +|---|---:|---:| +| Wall (s) | 791 | 766 | +| Model requests | 122 | 96 | +| Output tokens | 127,288 | 96,647 | +| Aggregate output tok/s over the span | 161 | 126 | +| Decode tok/s (median, requests with > 200 tokens) | 186 | 184 | +| Engine busy (prefill + decode ms) | 724 s (92 %) | 664 s (87 %) | +| Time with no request open | 63 s | 100 s | +| Time with 2 / 3 requests open | 232 s / 18 s | 0 / 0 | +| Queue wait p50 / p90 / max | 2 ms / 5.0 s / 51 s | 2 ms / 3 ms / 4 ms | +| TTFT p50 / p90 / max | 0.68 s / 6.3 s / 51.8 s | 0.57 s / 5.8 s / 8.5 s | +| Sessions switched at the prefix store | 48 of 122 | 2 of 96 | +| Import ms on a switch (median / max) | 29 / 48 | 2 / 2 | +| Cached share of prompt tokens | 98.1 % | 90.3 % | +| Acceptance strict / relaxed | 55/56 / 56/56 | 55/56 / 56/56 | + +Reading: the aggregate tok/s (+28 %) is a fuller engine plus more work, not a shorter time to the result. The orchestrator did 32 % more generation than the single agent (three contexts to read, two worker summaries, a full re-verification) and finished in the same time because the engine, not the tool waits, was the limit. The cached-share difference comes from different trajectories (the workers' contexts stay shorter: at most 95k prompt tokens against 140k in the control); it is reported, not interpreted. + +## 5. Aggregate against sequential execution (E) + +Sequential execution of the same 122 requests (one agent after another, engine never shared) would cost the engine time (724 s) plus the tool gaps of a single session. The control shows 766 - 664 = 102 s of gaps for 96 requests = 1.06 s per request; for 122 requests that is 129 s. Sequential wall about 724 + 129 = **853 s** against 790 s measured: **1.08x**, the upper end of the 0.97-1.18x (central 1.03-1.08x) predicted in section B.6 of the 6g analysis. Against the single agent doing the whole task alone (766 s) there is no gain. n = 1 and a wall sd of 21-112 s on 430-650 s mean that an effect of this size is not resolvable by a three-repetition matrix. + +## 6. Failures and oddities + +* **Head-of-line blocking:** one 54-s generation (10k tokens in one tool call) held the other worker for 51 s. FIFO without preemption is the only queueing defect seen, and it is a latency, not a correctness, issue. +* First requests of each worker (prompt below 8,192 tokens) have `cached = 0`; the cache block grid is 8,192 (profile `rtx5090-32g`). Cost: two cold prefills of 7.6-7.7k tokens, 3-7 s. +* A child's tool list differs from the root's (no `multi_agent_v1` namespace), so the root and its children do not share the first prompt bytes (the children's first prompts are 7.6-7.7k tokens, below the 8,192 grid in any case). +* Codex printed `Model metadata for qwen-local not found` (harmless, same in all cells) and rejected one `rm -f /tmp/...` command by its own sandbox policy (once in each cell). Root commands: 38 of 38 exit 0; the workers' commands are not in the event stream; in their last requests 1 non-zero exit (a `git` call, 128). Control: 8 of 77 commands non-zero. +* One `generation failed: reasoning ended without ` was logged by the API during the warm-up cell `smoke-mini` (known pattern, the cell was accepted); none during the two task cells. +* The sandbox blocks sockets: neither the control nor the orchestrator could run `node dist/main.js` + curl; both verified with an in-process harness. +* Run output is 874 MB by `du` (the node_modules are hard links to the shared tree; the new bytes are small). + +## 7. Recommendation for the big 6g benchmark + +1. **The premise holds:** the model orchestrates correctly with Codex 0.163.0 and the gateway/engine path deals with the concurrency without a single protocol or tool-call failure; the cache switch costs 29 ms on average. So the "can it" question is closed, and the earlier fallback (N parallel `codex exec` sessions started by the harness) is not needed. +2. **No-go for the full matrix of B.4-B.7 (3-3.5 GPU-h, arms S1/S2/H2/O x 3 blocks).** The smoke already shows the thing the matrix would measure: with a strictly serial engine at 92 % duty the queue cannot give more than about 1.08x (E) and no gain over one agent; the resolution of n = 3 on this task (wall sd 21-112 s) cannot tell 1.08x from 1.0x. The money would buy the same conclusion with error bars. +3. **What would still be worth a GPU hour:** (a) a balanced split with long tool waits (four equal sub-tasks, builds and test suites in the workers) to see the gamma term of B.6 become large; (b) the real lever, simultaneous decode of two sessions (E 1.0-1.3x at N = 2 per `multiplexing-feasibility.md` 3.2), with this task as its workload; (c) a scheduling fix for the head-of-line case (a long generation delaying another session by 51 s), which affects TTFT p90, not throughput. +4. The harness for any later run exists: `orchestrator_smoke_job.sh` (change the cell list), `make_orchestrator_tasks.py`, `analyze_orchestrator_run.py` (agents, overlap histogram, queue, TTFT, switch cost, integrity check). + +## 8. Files + +* Added: `scripts/e2e/codex/orchestrator/{mock_subagent_server.py, make_orchestrator_tasks.py, setup_orchestrator_inputs.sh, orchestrator_smoke_job.sh, orchestrator_smoke_stub.sh, analyze_orchestrator_run.py}`, this page. +* Server (all under `/data/leleka-e2e/prefill-latency/`): `orchestrator-subagents-smoke/{tools,tasks,reference,INPUTS.sha256,p0}` (frozen inputs and the P0 capture), `runs/codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482/`; the queue stub and the `PRIORITY` backup in `~/work/gpu-runs/holder2/jobs/`. The stack state, package and prefix directories of release 83bdd85bb482 under `codex-compare/ours-*-83bdd85bb482` were reused as the owner-default series left them (the job writes the stack's own logs there). + +## Sources + +* Repo: `docs/experiments/async-park-compression-and-orchestrator-bench.md` (B), `docs/experiments/multiplexing-feasibility.md`, `docs/e2e-run.md` 7, `scripts/e2e/codex/compare/cmp_codex_job.sh` and the server `cmp_codex_job_profile.sh`. +* Public (secondary for this exact version; the tool list, flags and gating text above were read from the 0.163.0 binary and its requests): [Codex subagents documentation](https://learn.chatgpt.com/docs/agent-configuration/subagents) (formerly developers.openai.com/codex/subagents), [Codex multi-agent notes](https://developers.openai.com/codex/multi-agent), third-party notes on `max_threads` / `max_depth` and `multi_agent_v2` at [codex.danielvaughan.com](https://codex.danielvaughan.com/2026/03/26/codex-cli-subagents-toml-parallelism/) and [morphllm.com/codex-multi-agent](https://www.morphllm.com/codex-multi-agent).