1
0

smoke-python-runtime.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. #!/usr/bin/env python3
  2. """Keyless full-turn and snapshot smoke for the Python SDK runtime."""
  3. from __future__ import annotations
  4. import argparse
  5. import difflib
  6. import json
  7. import os
  8. import queue
  9. import subprocess
  10. import tempfile
  11. import threading
  12. import time
  13. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  14. from pathlib import Path
  15. from typing import TYPE_CHECKING, Callable
  16. if TYPE_CHECKING:
  17. from deepseek_harness import TurnResult
  18. EXPECTED_TEXT = "runtime smoke ok"
  19. CODE_PROMPT = "Use run_code to compute the packaged worker smoke value."
  20. CODE_WORKER_TEXT = "code worker smoke ok"
  21. WORKFLOW_PROMPT = "Use workflow to compute the packaged worker smoke value without agents."
  22. WORKFLOW_WORKER_TEXT = "workflow worker smoke ok"
  23. SNAPSHOT_PROMPT = "Run the advanced packaged-runtime snapshot scenario."
  24. SNAPSHOT_SESSION_ID = "advanced-executable"
  25. SNAPSHOT_DIRECT_CHILD_PROMPT = "Reply with exactly DIRECT_CHILD_OK and nothing else."
  26. SNAPSHOT_WORKFLOW_CHILD_PROMPT = "Reply with exactly WORKFLOW_CHILD_OK and nothing else."
  27. SNAPSHOT_FINAL_TEXT = "ADVANCED_EXECUTABLE_OK"
  28. SNAPSHOT_MOUNT_CODE = """\
  29. return (ctx) => {
  30. harness.registerTool(ctx, harness.defineTool({
  31. name: 'snapshot_double',
  32. description: 'Double a number for executable snapshot verification.',
  33. parameters: { value: { type: 'number', required: true } },
  34. async execute(args) {
  35. return [{ type: 'text', text: String(args.value * 2) }]
  36. }
  37. }))
  38. }
  39. """
  40. SNAPSHOT_WORKFLOW_SCRIPT = (
  41. "phase('Delegate')\n"
  42. f"const reply = await agent('{SNAPSHOT_WORKFLOW_CHILD_PROMPT}', {{ label: 'workflow-child' }})\n"
  43. "return { reply }"
  44. )
  45. SNAPSHOT_DIRECTORY = (
  46. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
  47. )
  48. SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
  49. CUSTOM_CORDIS = """\
  50. - id: jsonrpc
  51. name: '@deepseek-ai/dsh-jsonrpc'
  52. - id: agent-core
  53. name: '@deepseek-ai/dsh-agent-spine-demo'
  54. config:
  55. workspaceContext: false
  56. tools:
  57. mode: both
  58. - id: sessions
  59. name: '@deepseek-ai/dsh-session-persistence-jsonl'
  60. config:
  61. root: !!js process.env.DSH_SESSION_ROOT
  62. - id: bash
  63. name: '@deepseek-ai/dsh-bash-local'
  64. config:
  65. cwd: !!js process.env.DSH_CWD
  66. - id: code-runtime
  67. name: '@deepseek-ai/dsh-code-runtime-worker'
  68. - id: subagents
  69. name: '@deepseek-ai/dsh-subagent'
  70. - id: subagent-spawn
  71. name: '@deepseek-ai/dsh-subagent-spawn'
  72. config:
  73. providerName: spawn
  74. - id: subagent-tool
  75. name: '@deepseek-ai/dsh-tool-subagent'
  76. config:
  77. provider: spawn
  78. - id: workflow-engine
  79. name: '@deepseek-ai/dsh-workflow-workerthread'
  80. config:
  81. provider: spawn
  82. - id: workflow-tool
  83. name: '@deepseek-ai/dsh-tool-workflow'
  84. - id: cordis-tool
  85. name: '@deepseek-ai/dsh-tool-cordis'
  86. """
  87. class MockModelHandler(BaseHTTPRequestHandler):
  88. """Return deterministic text, worker, and orchestration completions."""
  89. requests: list[dict[str, object]] = []
  90. def do_POST(self) -> None:
  91. content_length = int(self.headers.get("content-length", "0"))
  92. body = json.loads(self.rfile.read(content_length))
  93. self.requests.append(body)
  94. self.send_response(200)
  95. self.send_header("content-type", "text/event-stream")
  96. self.end_headers()
  97. chunks = completion_chunks(body)
  98. for chunk in chunks:
  99. self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
  100. self.wfile.write(b"data: [DONE]\n\n")
  101. self.wfile.flush()
  102. def log_message(self, _format: str, *_args: object) -> None:
  103. return
  104. def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
  105. """Choose the next deterministic model response from request history."""
  106. messages = body.get("messages")
  107. if not isinstance(messages, list) or not messages:
  108. raise AssertionError(f"model request has no messages: {body}")
  109. latest = messages[-1]
  110. if not isinstance(latest, dict):
  111. raise AssertionError(f"model request has an invalid latest message: {body}")
  112. if latest.get("role") == "tool":
  113. call_id, tool_name = latest_tool_call(messages)
  114. tool_text = message_text(latest.get("content"))
  115. advanced = advanced_tool_followup(body, call_id, tool_name, tool_text)
  116. if advanced is not None:
  117. return advanced
  118. if "42" not in tool_text:
  119. raise AssertionError(f"{tool_name} worker returned no expected value: {latest}")
  120. if tool_name == "run_code":
  121. return text_chunks(CODE_WORKER_TEXT)
  122. if tool_name == "workflow":
  123. return text_chunks(WORKFLOW_WORKER_TEXT)
  124. raise AssertionError(f"unexpected tool follow-up: {tool_name}")
  125. prompt = message_text(latest.get("content"))
  126. if prompt == SNAPSHOT_DIRECT_CHILD_PROMPT:
  127. return text_chunks("DIRECT_CHILD_OK")
  128. if prompt == SNAPSHOT_WORKFLOW_CHILD_PROMPT:
  129. return text_chunks("WORKFLOW_CHILD_OK")
  130. if prompt == SNAPSHOT_PROMPT:
  131. assert_advertised_tool(body, "cordis_mount")
  132. return tool_call_chunks(
  133. "advanced-mount",
  134. "cordis_mount",
  135. {"code": SNAPSHOT_MOUNT_CODE},
  136. )
  137. if prompt == CODE_PROMPT:
  138. assert_advertised_tool(body, "run_code")
  139. return tool_call_chunks("call-code-worker", "run_code", {"code": "return 6 * 7"})
  140. if prompt == WORKFLOW_PROMPT:
  141. assert_advertised_tool(body, "workflow")
  142. return tool_call_chunks(
  143. "call-workflow-worker",
  144. "workflow",
  145. {
  146. "script": "return 6 * 7",
  147. "meta": {
  148. "name": "pkg-worker-smoke",
  149. "description": "exercise the packaged workflow worker",
  150. },
  151. },
  152. )
  153. return text_chunks(EXPECTED_TEXT)
  154. def advanced_tool_followup(
  155. body: dict[str, object],
  156. call_id: str,
  157. tool_name: str,
  158. tool_text: str,
  159. ) -> list[dict[str, object]] | None:
  160. """Advance the executable snapshot's deterministic parent tool chain."""
  161. if not call_id.startswith("advanced-"):
  162. return None
  163. if call_id == "advanced-mount" and tool_name == "cordis_mount":
  164. if "mounted dyn-1" not in tool_text:
  165. raise AssertionError(f"cordis_mount returned no mount id: {tool_text}")
  166. assert_advertised_tool(body, "run_code")
  167. assert_advertised_tool(body, "snapshot_double")
  168. return tool_call_chunks(
  169. "advanced-code",
  170. "run_code",
  171. {"code": "return await tools.snapshot_double({ value: 21 })"},
  172. )
  173. if call_id == "advanced-code" and tool_name == "run_code":
  174. if "42" not in tool_text:
  175. raise AssertionError(f"run_code returned no dynamic-tool value: {tool_text}")
  176. assert_advertised_tool(body, "subagent")
  177. return tool_call_chunks(
  178. "advanced-direct-child",
  179. "subagent",
  180. {
  181. "description": "Check direct child",
  182. "prompt": SNAPSHOT_DIRECT_CHILD_PROMPT,
  183. },
  184. )
  185. if call_id == "advanced-direct-child" and tool_name == "subagent":
  186. if "DIRECT_CHILD_OK" not in tool_text:
  187. raise AssertionError(f"subagent returned no expected child value: {tool_text}")
  188. assert_advertised_tool(body, "workflow")
  189. return tool_call_chunks(
  190. "advanced-workflow",
  191. "workflow",
  192. {
  193. "script": SNAPSHOT_WORKFLOW_SCRIPT,
  194. "meta": {
  195. "name": "advanced-exe-snapshot",
  196. "description": "exercise one packaged workflow child",
  197. },
  198. },
  199. )
  200. if call_id == "advanced-workflow" and tool_name == "workflow":
  201. if "WORKFLOW_CHILD_OK" not in tool_text:
  202. raise AssertionError(f"workflow returned no expected child value: {tool_text}")
  203. assert_advertised_tool(body, "cordis_unmount")
  204. return tool_call_chunks(
  205. "advanced-unmount",
  206. "cordis_unmount",
  207. {"id": "dyn-1"},
  208. )
  209. if call_id == "advanced-unmount" and tool_name == "cordis_unmount":
  210. if "unmounted dyn-1" not in tool_text:
  211. raise AssertionError(f"cordis_unmount returned no disposal result: {tool_text}")
  212. if "snapshot_double" in advertised_tool_names(body):
  213. raise AssertionError("snapshot_double remained advertised after cordis_unmount")
  214. return text_chunks(SNAPSHOT_FINAL_TEXT)
  215. raise AssertionError(f"unexpected advanced tool follow-up: {call_id} {tool_name}: {tool_text}")
  216. def text_chunks(text: str) -> list[dict[str, object]]:
  217. """Build a complete streaming text response."""
  218. return [
  219. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  220. {"choices": [{"delta": {"content": text}}]},
  221. {
  222. "choices": [{"delta": {"content": ""}, "finish_reason": "stop"}],
  223. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  224. },
  225. ]
  226. def tool_call_chunks(call_id: str, name: str, arguments: dict[str, object]) -> list[dict[str, object]]:
  227. """Build a complete streaming function-call response."""
  228. return [
  229. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  230. {
  231. "choices": [{
  232. "delta": {
  233. "tool_calls": [{
  234. "index": 0,
  235. "id": call_id,
  236. "type": "function",
  237. "function": {"name": name, "arguments": json.dumps(arguments)},
  238. }],
  239. },
  240. }],
  241. },
  242. {
  243. "choices": [{"delta": {"content": ""}, "finish_reason": "tool_calls"}],
  244. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  245. },
  246. ]
  247. def latest_tool_call(messages: list[object]) -> tuple[str, str]:
  248. """Find the assistant call id and name paired with the latest tool result."""
  249. for message in reversed(messages[:-1]):
  250. if not isinstance(message, dict):
  251. continue
  252. calls = message.get("tool_calls")
  253. if not isinstance(calls, list):
  254. continue
  255. for call in reversed(calls):
  256. if not isinstance(call, dict):
  257. continue
  258. function = call.get("function")
  259. call_id = call.get("id")
  260. if (
  261. isinstance(call_id, str)
  262. and isinstance(function, dict)
  263. and isinstance(function.get("name"), str)
  264. ):
  265. return call_id, function["name"]
  266. raise AssertionError(f"tool result has no preceding assistant tool call: {messages}")
  267. def message_text(content: object) -> str:
  268. """Read OpenAI text content in either string or block-list form."""
  269. if isinstance(content, str):
  270. return content
  271. if isinstance(content, list):
  272. return "".join(
  273. block.get("text", "")
  274. for block in content
  275. if isinstance(block, dict) and isinstance(block.get("text"), str)
  276. )
  277. return ""
  278. def advertised_tool_names(body: dict[str, object]) -> set[str]:
  279. """Return the model-facing tool names advertised on one request."""
  280. tools = body.get("tools")
  281. if not isinstance(tools, list):
  282. raise AssertionError(f"model request advertised no tools: {body}")
  283. names: set[str] = set()
  284. for tool in tools:
  285. if not isinstance(tool, dict):
  286. continue
  287. function = tool.get("function")
  288. if isinstance(function, dict) and isinstance(function.get("name"), str):
  289. names.add(function["name"])
  290. return names
  291. def assert_advertised_tool(body: dict[str, object], expected: str) -> None:
  292. """Require the packaged deployment to expose the requested tool."""
  293. names = advertised_tool_names(body)
  294. if expected not in names:
  295. raise AssertionError(f"model request did not advertise {expected}: {names}")
  296. class MockModel:
  297. def __enter__(self) -> "MockModel":
  298. MockModelHandler.requests.clear()
  299. self.server = ThreadingHTTPServer(("127.0.0.1", 0), MockModelHandler)
  300. self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
  301. self.thread.start()
  302. host, port = self.server.server_address
  303. self.url = f"http://{host}:{port}"
  304. return self
  305. def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
  306. self.server.shutdown()
  307. self.server.server_close()
  308. self.thread.join(timeout=5)
  309. def main() -> None:
  310. parser = argparse.ArgumentParser(description=__doc__)
  311. parser.add_argument(
  312. "--scenario",
  313. choices=("all", "sdk-default", "sdk-custom", "sdk-snapshot", "direct"),
  314. default="all",
  315. )
  316. parser.add_argument("--exe", type=Path)
  317. parser.add_argument("--update-snapshots", action="store_true")
  318. args = parser.parse_args()
  319. if args.scenario in {"all", "sdk-custom", "sdk-snapshot", "direct"} and args.exe is None:
  320. parser.error("--exe is required for custom, snapshot, and direct scenarios")
  321. if args.update_snapshots and args.scenario not in {"all", "sdk-snapshot"}:
  322. parser.error("--update-snapshots requires --scenario sdk-snapshot or all")
  323. if args.exe is not None and not args.exe.is_file():
  324. parser.error(f"runtime executable does not exist: {args.exe}")
  325. with MockModel() as model:
  326. if args.scenario in {"all", "sdk-default"}:
  327. smoke_sdk_default(model.url)
  328. if args.scenario in {"all", "sdk-custom"}:
  329. assert args.exe is not None
  330. smoke_sdk_custom(model.url, args.exe.resolve())
  331. if args.scenario in {"all", "sdk-snapshot"}:
  332. assert args.exe is not None
  333. smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  334. if args.scenario in {"all", "direct"}:
  335. assert args.exe is not None
  336. smoke_direct(model.url, args.exe.resolve())
  337. if not MockModelHandler.requests:
  338. raise AssertionError("mock model endpoint received no requests")
  339. print(f"smoke-python-runtime: {args.scenario} passed")
  340. def smoke_sdk_default(base_url: str) -> None:
  341. from deepseek_harness import DeepSeekHarness
  342. with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary:
  343. root = Path(temporary).resolve()
  344. sessions = root / "sessions"
  345. with DeepSeekHarness(
  346. provider="deepseek",
  347. model="smoke-model",
  348. cwd=str(root),
  349. session_root=str(sessions),
  350. api_key="sk-keyless-smoke",
  351. base_url=base_url,
  352. request_timeout_seconds=60,
  353. ) as harness:
  354. result = harness.run("reply with the smoke text", session_id="default-smoke")
  355. assert result.status == "ok", result
  356. assert result.final_response == EXPECTED_TEXT, result.final_response
  357. assert_session_log(sessions, root, EXPECTED_TEXT)
  358. def smoke_sdk_custom(base_url: str, executable: Path) -> None:
  359. from deepseek_harness import DeepSeekHarness
  360. with tempfile.TemporaryDirectory(prefix="dsh-sdk-custom-") as temporary:
  361. root = Path(temporary).resolve()
  362. sessions = root / "sessions"
  363. cordis = root / "cordis.yml"
  364. cordis.write_text(CUSTOM_CORDIS)
  365. with DeepSeekHarness(
  366. provider="deepseek",
  367. model="smoke-model",
  368. cwd=str(root),
  369. session_root=str(sessions),
  370. cordis=str(cordis),
  371. runtime_bin=str(executable),
  372. api_key="sk-keyless-smoke",
  373. base_url=base_url,
  374. request_timeout_seconds=60,
  375. ) as harness:
  376. text_result = harness.run("reply with the smoke text", session_id="custom-smoke")
  377. code_result = harness.run(CODE_PROMPT, session_id="custom-smoke")
  378. workflow_result = harness.run(WORKFLOW_PROMPT, session_id="custom-smoke")
  379. assert text_result.status == "ok", text_result
  380. assert text_result.final_response == EXPECTED_TEXT, text_result.final_response
  381. assert code_result.status == "ok", code_result
  382. assert code_result.final_response == CODE_WORKER_TEXT, code_result.final_response
  383. assert workflow_result.status == "ok", workflow_result
  384. assert workflow_result.final_response == WORKFLOW_WORKER_TEXT, workflow_result.final_response
  385. assert_session_log(sessions, root, EXPECTED_TEXT, CODE_WORKER_TEXT, WORKFLOW_WORKER_TEXT)
  386. def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  387. """Drive and compare the advanced SDK/executable behavioral snapshot."""
  388. from deepseek_harness import DeepSeekHarness
  389. with tempfile.TemporaryDirectory(prefix="dsh-sdk-snapshot-") as temporary:
  390. root = Path(temporary).resolve()
  391. sessions = root / "sessions"
  392. cordis = root / "cordis.yml"
  393. cordis.write_text(CUSTOM_CORDIS)
  394. with DeepSeekHarness(
  395. provider="deepseek",
  396. model="smoke-model",
  397. cwd=str(root),
  398. session_root=str(sessions),
  399. cordis=str(cordis),
  400. runtime_bin=str(executable),
  401. api_key="sk-keyless-smoke",
  402. base_url=base_url,
  403. request_timeout_seconds=60,
  404. ) as harness:
  405. result = harness.run(SNAPSHOT_PROMPT, session_id=SNAPSHOT_SESSION_ID)
  406. assert result.status == "ok", result
  407. assert result.final_response == SNAPSHOT_FINAL_TEXT, result.final_response
  408. methods = [notification.method for notification in result.notifications]
  409. if methods.count("subagent.started") != 2 or methods.count("subagent.finished") != 2:
  410. raise AssertionError(f"advanced snapshot emitted unexpected subagent lifecycle: {methods}")
  411. if not any(event.get("type") == "tool/code-dispatch" for event in result.events):
  412. raise AssertionError("advanced snapshot emitted no tool/code-dispatch event")
  413. logs = read_session_logs(sessions)
  414. child_ids = snapshot_child_ids(result)
  415. expected_ids = {SNAPSHOT_SESSION_ID, *child_ids}
  416. if set(logs) != expected_ids:
  417. raise AssertionError(f"advanced snapshot expected parent plus two child logs: {sorted(logs)}")
  418. if "DIRECT_CHILD_OK" not in render_jsonl(logs[child_ids[0]]):
  419. raise AssertionError("first advanced child log has no direct-subagent result")
  420. if "WORKFLOW_CHILD_OK" not in render_jsonl(logs[child_ids[1]]):
  421. raise AssertionError("second advanced child log has no workflow-subagent result")
  422. files = build_snapshot_files(result, logs, child_ids, root)
  423. compare_snapshot_files(files, update_snapshots)
  424. def smoke_direct(base_url: str, executable: Path) -> None:
  425. with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary:
  426. root = Path(temporary).resolve()
  427. sessions = root / "sessions"
  428. cordis = root / "cordis.yml"
  429. cordis.write_text(CUSTOM_CORDIS)
  430. environment = {
  431. **os.environ,
  432. "DSH_CORDIS_CONFIG": str(cordis),
  433. "DSH_SESSION_ROOT": str(sessions),
  434. "DSH_CWD": str(root),
  435. "DEEPSEEK_API_KEY": "sk-keyless-smoke",
  436. "DEEPSEEK_BASE_URL": base_url,
  437. }
  438. peer = RuntimePeer([str(executable)], root, environment)
  439. try:
  440. peer.send({"jsonrpc": "2.0", "id": "initialize", "method": "initialize", "params": {"cwd": str(root), "provider": "deepseek", "model": "smoke-model"}})
  441. peer.read_until(lambda message: message.get("id") == "initialize")
  442. peer.send({
  443. "jsonrpc": "2.0",
  444. "id": "prompt",
  445. "method": "session/prompt",
  446. "params": {"sessionId": "direct-smoke", "contentBlocks": [{"type": "text", "text": "reply with the smoke text"}]},
  447. })
  448. messages = peer.read_until(lambda message: message.get("id") == "prompt")
  449. if not any(message.get("method") == "session.finished" and message.get("params", {}).get("status") == "ok" for message in messages):
  450. messages.extend(peer.read_until(lambda message: message.get("method") == "session.finished"))
  451. event_text = json.dumps(messages)
  452. if EXPECTED_TEXT not in event_text:
  453. raise AssertionError(f"direct runtime emitted no final response: {messages}")
  454. peer.send({"jsonrpc": "2.0", "id": "shutdown", "method": "shutdown"})
  455. peer.read_until(lambda message: message.get("id") == "shutdown")
  456. finally:
  457. peer.close()
  458. assert_session_log(sessions, root, EXPECTED_TEXT)
  459. class RuntimePeer:
  460. def __init__(self, argv: list[str], cwd: Path, environment: dict[str, str]) -> None:
  461. self.process = subprocess.Popen(
  462. argv,
  463. cwd=cwd,
  464. env=environment,
  465. stdin=subprocess.PIPE,
  466. stdout=subprocess.PIPE,
  467. stderr=subprocess.PIPE,
  468. text=True,
  469. encoding="utf-8",
  470. bufsize=1,
  471. )
  472. self.stdout: queue.Queue[str | None] = queue.Queue()
  473. self.stderr: list[str] = []
  474. threading.Thread(target=self._read_stdout, daemon=True).start()
  475. threading.Thread(target=self._read_stderr, daemon=True).start()
  476. def send(self, message: dict[str, object]) -> None:
  477. if self.process.stdin is None:
  478. raise RuntimeError("runtime stdin is unavailable")
  479. self.process.stdin.write(json.dumps(message) + "\n")
  480. self.process.stdin.flush()
  481. def read_until(self, predicate: Callable[[dict[str, object]], bool]) -> list[dict[str, object]]:
  482. deadline = time.monotonic() + 60
  483. messages: list[dict[str, object]] = []
  484. while time.monotonic() < deadline:
  485. try:
  486. line = self.stdout.get(timeout=min(0.25, deadline - time.monotonic()))
  487. except queue.Empty:
  488. continue
  489. if line is None:
  490. raise RuntimeError(f"runtime exited before expected message; stderr: {''.join(self.stderr)}")
  491. try:
  492. message = json.loads(line)
  493. except json.JSONDecodeError:
  494. continue
  495. messages.append(message)
  496. if predicate(message):
  497. return messages
  498. raise TimeoutError(f"runtime timed out; messages={messages}; stderr={''.join(self.stderr)}")
  499. def close(self) -> None:
  500. if self.process.stdin is not None and not self.process.stdin.closed:
  501. self.process.stdin.close()
  502. try:
  503. self.process.wait(timeout=10)
  504. except subprocess.TimeoutExpired:
  505. self.process.kill()
  506. self.process.wait()
  507. if self.process.returncode not in {0, -15}:
  508. raise RuntimeError(f"runtime exited {self.process.returncode}; stderr: {''.join(self.stderr)}")
  509. def _read_stdout(self) -> None:
  510. assert self.process.stdout is not None
  511. for line in self.process.stdout:
  512. self.stdout.put(line)
  513. self.stdout.put(None)
  514. def _read_stderr(self) -> None:
  515. assert self.process.stderr is not None
  516. self.stderr.extend(self.process.stderr)
  517. def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
  518. logs = list(sessions.rglob("*.jsonl"))
  519. if len(logs) != 1:
  520. raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}")
  521. lines = logs[0].read_text().splitlines()
  522. header = json.loads(lines[0])
  523. if header.get("cwd") != str(cwd):
  524. raise AssertionError(f"session header cwd is not absolute/canonical: {header}")
  525. rendered = "\n".join(lines)
  526. for expected in expected_texts:
  527. if expected not in rendered:
  528. raise AssertionError(f"session log has no {expected!r} response: {logs[0]}")
  529. def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]:
  530. """Parse every persisted JSONL session into a map keyed by header id."""
  531. logs: dict[str, list[dict[str, object]]] = {}
  532. for path in sorted(sessions.rglob("*.jsonl")):
  533. records = [
  534. json.loads(line)
  535. for line in path.read_text(encoding="utf-8").splitlines()
  536. if line
  537. ]
  538. if not records or records[0].get("type") != "session":
  539. raise AssertionError(f"session log has no header: {path}")
  540. session_id = records[0].get("id")
  541. if not isinstance(session_id, str):
  542. raise AssertionError(f"session log header has no string id: {path}")
  543. if session_id in logs:
  544. raise AssertionError(f"duplicate persisted session id: {session_id}")
  545. logs[session_id] = records
  546. return logs
  547. def snapshot_child_ids(result: "TurnResult") -> list[str]:
  548. """Return the two child session ids in their SDK notification order."""
  549. child_ids: list[str] = []
  550. for notification in result.notifications:
  551. if notification.method != "subagent.started":
  552. continue
  553. payload = notification.payload
  554. if payload.get("parentSessionId") != SNAPSHOT_SESSION_ID:
  555. continue
  556. child_id = payload.get("childSessionId")
  557. if isinstance(child_id, str) and child_id not in child_ids:
  558. child_ids.append(child_id)
  559. if len(child_ids) != 2:
  560. raise AssertionError(f"advanced snapshot expected two child session ids: {child_ids}")
  561. return child_ids
  562. def build_snapshot_files(
  563. result: "TurnResult",
  564. logs: dict[str, list[dict[str, object]]],
  565. child_ids: list[str],
  566. cwd: Path,
  567. ) -> dict[str, str]:
  568. """Render the SDK result and three persisted logs into stable goldens."""
  569. replacements = [(str(cwd), "{{cwd}}"), (SNAPSHOT_SESSION_ID, "{{parent}}")]
  570. for index, child_id in enumerate(child_ids, start=1):
  571. replacements.append((child_id, f"{{{{child-{index}}}}}"))
  572. agent_id = snapshot_agent_id(result, child_id)
  573. replacements.append((agent_id, f"{{{{agent-{index}}}}}"))
  574. replacements.sort(key=lambda pair: len(pair[0]), reverse=True)
  575. result_value = {
  576. "session_id": result.session_id,
  577. "status": result.status,
  578. "final_response": result.final_response,
  579. "events": result.events,
  580. "notifications": [
  581. {"method": notification.method, "payload": notification.payload}
  582. for notification in result.notifications
  583. ],
  584. "session_root": result.session_root,
  585. }
  586. normalized_result = normalize_snapshot_value(result_value, replacements)
  587. files = {
  588. "result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
  589. "session.jsonl": render_jsonl(
  590. [normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]]
  591. ),
  592. }
  593. for index, child_id in enumerate(child_ids, start=1):
  594. files[f"session.{index}.jsonl"] = render_jsonl(
  595. [normalize_snapshot_value(record, replacements) for record in logs[child_id]]
  596. )
  597. if tuple(files) != SNAPSHOT_FILENAMES:
  598. raise AssertionError(f"advanced snapshot file set drifted: {tuple(files)}")
  599. return files
  600. def snapshot_agent_id(result: "TurnResult", child_id: str) -> str:
  601. """Find the successful subagent id paired with one child session."""
  602. for notification in result.notifications:
  603. if notification.method != "subagent.finished":
  604. continue
  605. payload = notification.payload
  606. if payload.get("childSessionId") != child_id:
  607. continue
  608. if payload.get("provider") != "spawn" or payload.get("status") != "ok":
  609. raise AssertionError(f"advanced child did not finish successfully: {payload}")
  610. agent_id = payload.get("agentId")
  611. if isinstance(agent_id, str):
  612. return agent_id
  613. raise AssertionError(f"advanced snapshot has no finished agent for child {child_id}")
  614. def normalize_snapshot_value(
  615. value: object,
  616. replacements: list[tuple[str, str]],
  617. ) -> object:
  618. """Scrub volatile values and bulky request headers without losing behavior."""
  619. if isinstance(value, str):
  620. normalized = value
  621. for actual, token in replacements:
  622. normalized = normalized.replace(actual, token)
  623. return normalized
  624. if isinstance(value, list):
  625. return [normalize_snapshot_value(item, replacements) for item in value]
  626. if not isinstance(value, dict):
  627. return value
  628. normalized = {
  629. key: normalize_snapshot_value(item, replacements)
  630. for key, item in value.items()
  631. }
  632. if normalized.get("type") == "session" and "createdAt" in normalized:
  633. normalized["createdAt"] = 0
  634. if "seq" in normalized and "time" in normalized:
  635. normalized["time"] = 0
  636. scrub_snapshot_header(normalized)
  637. return normalized
  638. def scrub_snapshot_header(value: dict[object, object]) -> None:
  639. """Tokenize full request-header bulk while retaining tool names."""
  640. data = value.get("data")
  641. if not isinstance(data, dict):
  642. return
  643. if value.get("type") == "request/header":
  644. header = data.get("header")
  645. if not isinstance(header, dict):
  646. return
  647. if "system" in header:
  648. header["system"] = "{{system}}"
  649. tools = header.get("tools")
  650. if isinstance(tools, list):
  651. header["tools"] = [
  652. tool.get("name") if isinstance(tool, dict) else "{{tools}}"
  653. for tool in tools
  654. ]
  655. if isinstance(header.get("messagePrefix"), list):
  656. header["messagePrefix"] = ["{{messagePrefix}}" for _ in header["messagePrefix"]]
  657. def render_jsonl(records: list[object]) -> str:
  658. """Render parsed JSON values as compact, newline-terminated JSONL."""
  659. return "".join(
  660. json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
  661. for record in records
  662. )
  663. def compare_snapshot_files(files: dict[str, str], update: bool) -> None:
  664. """Write or exactly compare the advanced executable snapshot files."""
  665. if update:
  666. SNAPSHOT_DIRECTORY.mkdir(parents=True, exist_ok=True)
  667. for name, content in files.items():
  668. (SNAPSHOT_DIRECTORY / name).write_text(content, encoding="utf-8")
  669. print(f"smoke-python-runtime: updated snapshots in {SNAPSHOT_DIRECTORY}")
  670. existing = {
  671. path.name
  672. for path in SNAPSHOT_DIRECTORY.iterdir()
  673. if path.is_file()
  674. } if SNAPSHOT_DIRECTORY.is_dir() else set()
  675. expected = set(SNAPSHOT_FILENAMES)
  676. if existing != expected:
  677. raise AssertionError(
  678. "advanced snapshot files differ: "
  679. f"missing={sorted(expected - existing)}, unexpected={sorted(existing - expected)}"
  680. )
  681. for name, actual in files.items():
  682. expected_text = (SNAPSHOT_DIRECTORY / name).read_text(encoding="utf-8")
  683. if actual == expected_text:
  684. continue
  685. diff = "".join(difflib.unified_diff(
  686. expected_text.splitlines(keepends=True),
  687. actual.splitlines(keepends=True),
  688. fromfile=f"expected/{name}",
  689. tofile=f"actual/{name}",
  690. ))
  691. raise AssertionError(
  692. f"advanced executable snapshot mismatch in {name}; "
  693. "rerun with --update-snapshots after reviewing the behavior\n"
  694. f"{diff}"
  695. )
  696. if __name__ == "__main__":
  697. main()