1
0

smoke-python-runtime.py 31 KB

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