1
0

smoke-python-runtime.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107
  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 importlib
  7. import importlib.metadata
  8. import json
  9. import os
  10. import queue
  11. import re
  12. import subprocess
  13. import sys
  14. import sysconfig
  15. import tempfile
  16. import threading
  17. import time
  18. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  19. from pathlib import Path
  20. from typing import TYPE_CHECKING, Callable
  21. if TYPE_CHECKING:
  22. from deepseek_harness import RunResult
  23. EXPECTED_TEXT = "runtime smoke ok"
  24. LIVE_API_SENTINEL = "PYTHON_SDK_LIVE_OK"
  25. CODE_PROMPT = "Use run_code to compute the packaged worker smoke value."
  26. CODE_WORKER_TEXT = "code worker smoke ok"
  27. WORKFLOW_PROMPT = "Use workflow to compute the packaged worker smoke value without agents."
  28. WORKFLOW_WORKER_TEXT = "workflow worker smoke ok"
  29. MINIMAL_PROMPT = "Exercise the packaged minimal agent's persistent shell and string-replacement editor."
  30. MINIMAL_TEXT = "minimal agent smoke ok"
  31. MINIMAL_EDITOR_PATH_PREFIX = "Editor path: "
  32. FS_SEARCH_PROMPT = "Exercise the packaged filesystem search tools."
  33. FS_SEARCH_TEXT = "filesystem search smoke ok"
  34. FS_SEARCH_MARKER = "PACKAGED_FS_SEARCH_OK"
  35. MCP_PROMPT = "Exercise the packaged MCP client with one external stdio server."
  36. MCP_TEXT = "MCP client smoke ok"
  37. PROFILE_PLUGIN_PROMPT = "Verify the Python-installed dsh profile plugin."
  38. PROFILE_PLUGIN_TEXT = "profile plugin smoke ok"
  39. PROFILE_PLUGIN_MARKER = "PYTHON_INSTALLED_DSH_PROFILE_PLUGIN"
  40. IS_WINDOWS = sys.platform == "win32"
  41. MINIMAL_SHELL_TOOL = "pwsh" if IS_WINDOWS else "bash"
  42. MINIMAL_SHELL_COMMAND = (
  43. "$global:dshSdkCounter = [int]$global:dshSdkCounter + 1; "
  44. 'Write-Output "COUNT=$global:dshSdkCounter CWD=$((Get-Location).Path)"; '
  45. "if ($global:dshSdkCounter -eq 1) { Set-Location $env:TEMP }"
  46. if IS_WINDOWS
  47. else (
  48. "counter=$(( ${counter:-0} + 1 )); export counter; "
  49. "printf 'COUNT=%s CWD=%s\\n' \"$counter\" \"$PWD\"; "
  50. "if [ \"$counter\" -eq 1 ]; then cd /tmp; fi"
  51. )
  52. )
  53. MINIMAL_SHELL_SECOND_CWD = str(Path(tempfile.gettempdir()).resolve()) if IS_WINDOWS else "/tmp"
  54. LEGACY_CUSTOM_DISABLED_ROWS = (
  55. "agent-instructions",
  56. "goal",
  57. "goal-round-driver",
  58. "command-goal",
  59. "plan-mode",
  60. "skill",
  61. "skill-filesystem",
  62. "tool-fs",
  63. "tool-fs-search",
  64. "tool-goal",
  65. "tool-ralph",
  66. "tool-skill",
  67. "tool-str-replace-editor",
  68. "tool-subagent-control",
  69. "tool-subagent-list-agents",
  70. "tool-subagent-fork",
  71. "tool-todo",
  72. "tool-web",
  73. )
  74. SNAPSHOT_PROMPT = "Run the advanced packaged-runtime snapshot scenario."
  75. SNAPSHOT_SESSION_ID = "advanced-executable"
  76. SNAPSHOT_DIRECT_CHILD_PROMPT = "Reply with exactly DIRECT_CHILD_OK and nothing else."
  77. SNAPSHOT_WORKFLOW_CHILD_PROMPT = "Reply with exactly WORKFLOW_CHILD_OK and nothing else."
  78. SNAPSHOT_FINAL_TEXT = "ADVANCED_EXECUTABLE_OK"
  79. RESTART_FIRST_PROMPT = "Complete the first isolated Python SDK process turn."
  80. RESTART_FIRST_TEXT = "PROCESS_ONE_OK"
  81. RESTART_SECOND_PROMPT = "Complete the second isolated Python SDK process turn."
  82. RESTART_SECOND_TEXT = "PROCESS_TWO_OK"
  83. RESTART_FIRST_SESSION_ID = "process-one"
  84. RESTART_SECOND_SESSION_ID = "process-two"
  85. SNAPSHOT_PLUGIN_CODE = """\
  86. return (ctx) => {
  87. harness.registerTool(ctx, harness.defineTool({
  88. name: 'snapshot_double',
  89. description: 'Double a number for executable snapshot verification.',
  90. parameters: { value: { type: 'number', required: true } },
  91. output: {
  92. schema: { type: 'number' },
  93. render(_args, value) {
  94. return [{ type: 'text', text: String(value) }]
  95. }
  96. },
  97. async execute(args) {
  98. return args.value * 2
  99. }
  100. }))
  101. }
  102. """
  103. SNAPSHOT_WORKFLOW_SCRIPT = (
  104. "phase('Delegate')\n"
  105. f"const reply = await agent('{SNAPSHOT_WORKFLOW_CHILD_PROMPT}', {{ label: 'workflow-child' }})\n"
  106. "return { reply }"
  107. )
  108. ADVANCED_SNAPSHOT_DIRECTORY = (
  109. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
  110. )
  111. ADVANCED_SNAPSHOT_FILENAMES = (
  112. "result.json", "session.v2.jsonl", "session.1.v2.jsonl", "session.2.v2.jsonl",
  113. )
  114. MINIMAL_SNAPSHOT_DIRECTORY = (
  115. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "minimal"
  116. )
  117. if IS_WINDOWS:
  118. MINIMAL_SNAPSHOT_DIRECTORY /= "win-x64"
  119. MINIMAL_SNAPSHOT_FILENAMES = ("model-visible.json",)
  120. RESTART_SNAPSHOT_DIRECTORY = (
  121. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "restart"
  122. )
  123. RESTART_SNAPSHOT_FILENAMES = (
  124. "result.json", "requests.json", "session.1.v2.jsonl", "session.2.v2.jsonl",
  125. )
  126. MCP_SERVER_SCRIPT = """\
  127. import json
  128. import os
  129. import sys
  130. import time
  131. log_path = os.environ.get("MCP_SMOKE_LOG")
  132. def send(message):
  133. sys.stdout.write(json.dumps(message, separators=(",", ":")) + "\\n")
  134. sys.stdout.flush()
  135. for line in sys.stdin:
  136. request = json.loads(line)
  137. if log_path is not None:
  138. with open(log_path, "a", encoding="utf-8") as log:
  139. log.write(str(request.get("method")) + "\\n")
  140. request_id = request.get("id")
  141. if request_id is None:
  142. continue
  143. method = request.get("method")
  144. if method == "initialize":
  145. send({
  146. "jsonrpc": "2.0",
  147. "id": request_id,
  148. "result": {
  149. "protocolVersion": request["params"]["protocolVersion"],
  150. "capabilities": {"tools": {"listChanged": False}},
  151. "serverInfo": {"name": "python-wheel-fixture", "version": "1.0.0"},
  152. },
  153. })
  154. elif method == "tools/list":
  155. # Keep discovery pending long enough that an SDK runtime answering
  156. # initialize before discovery completes makes its first model request
  157. # without this tool and fails deterministically.
  158. time.sleep(0.25)
  159. send({
  160. "jsonrpc": "2.0",
  161. "id": request_id,
  162. "result": {
  163. "tools": [{
  164. "name": "add",
  165. "description": "Add two numbers.",
  166. "inputSchema": {
  167. "type": "object",
  168. "properties": {"a": {"type": "number"}, "b": {"type": "number"}},
  169. "required": ["a", "b"],
  170. "additionalProperties": False,
  171. },
  172. }],
  173. },
  174. })
  175. elif method == "tools/call":
  176. params = request["params"]
  177. if params.get("name") != "add" or params.get("arguments") != {"a": 19, "b": 23}:
  178. send({
  179. "jsonrpc": "2.0",
  180. "id": request_id,
  181. "error": {"code": -32602, "message": "unexpected tool call"},
  182. })
  183. continue
  184. send({
  185. "jsonrpc": "2.0",
  186. "id": request_id,
  187. "result": {"content": [{"type": "text", "text": "42"}]},
  188. })
  189. else:
  190. send({
  191. "jsonrpc": "2.0",
  192. "id": request_id,
  193. "error": {"code": -32601, "message": f"unsupported method: {method}"},
  194. })
  195. """
  196. def write_profile_patch(
  197. root: Path,
  198. name: str,
  199. sessions: Path,
  200. patches: list[dict[str, object]],
  201. ) -> Path:
  202. """Write one JSON-form dsh profile patch with deterministic persistence."""
  203. path = root / name
  204. path.write_text(json.dumps([
  205. {
  206. "id": "session-persistence-jsonl",
  207. "config": {"root": str(sessions), "compression": "none"},
  208. },
  209. {"id": "session-telemetry-otel", "disabled": True},
  210. *patches,
  211. ], indent=2))
  212. return path
  213. def write_advanced_profile_patch(root: Path, name: str, sessions: Path) -> Path:
  214. """Write the shared custom, snapshot, and restart profile patch."""
  215. return write_profile_patch(root, name, sessions, [
  216. {"id": "tools", "config": {"mode": "both"}},
  217. {
  218. "id": "system-prompt",
  219. "config": {
  220. "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.",
  221. },
  222. },
  223. {"id": "session-log-deepseek", "config": {"enabled": True}},
  224. *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS),
  225. {"id": "tool-bash", "disabled": True},
  226. {"id": "tool-pwsh", "disabled": True},
  227. {
  228. "id": "tool-subagent",
  229. "config": {
  230. "provider": "spawn",
  231. "toolName": "subagent",
  232. "backgroundMode": "one-shot",
  233. },
  234. },
  235. {"insert": [
  236. {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"},
  237. {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"},
  238. {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"},
  239. ]},
  240. ])
  241. def write_mcp_patch(root: Path, sessions: Path, server_script: Path) -> Path:
  242. """Write a profile patch that mounts the packaged MCP client."""
  243. return write_profile_patch(root, "mcp.patch.yml", sessions, [{
  244. "insert": [{
  245. "id": "mcp-fixture",
  246. "name": "@deepseek-ai/dsh-mcp-client",
  247. "config": {
  248. "serverName": "fixture",
  249. "transport": "stdio",
  250. "command": sys.executable,
  251. "args": [str(server_script)],
  252. "env": {"MCP_SMOKE_LOG": str(server_script.with_suffix(".log"))},
  253. "failOnStartupError": True,
  254. "reconnect": {"enabled": False},
  255. },
  256. }],
  257. }])
  258. class MockModelHandler(BaseHTTPRequestHandler):
  259. """Return deterministic text, worker, and orchestration completions."""
  260. requests: list[dict[str, object]] = []
  261. def do_POST(self) -> None:
  262. content_length = int(self.headers.get("content-length", "0"))
  263. body = json.loads(self.rfile.read(content_length))
  264. self.requests.append(body)
  265. self.send_response(200)
  266. self.send_header("content-type", "text/event-stream")
  267. self.end_headers()
  268. chunks = completion_chunks(body)
  269. for chunk in chunks:
  270. self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
  271. self.wfile.write(b"data: [DONE]\n\n")
  272. self.wfile.flush()
  273. def log_message(self, _format: str, *_args: object) -> None:
  274. return
  275. def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
  276. """Choose the next deterministic model response from request history."""
  277. messages = body.get("messages")
  278. if not isinstance(messages, list) or not messages:
  279. raise AssertionError(f"model request has no messages: {body}")
  280. latest = messages[-1]
  281. if not isinstance(latest, dict):
  282. raise AssertionError(f"model request has an invalid latest message: {body}")
  283. if latest.get("role") == "tool":
  284. call_id, tool_name = latest_tool_call(messages)
  285. tool_text = message_text(latest.get("content"))
  286. mcp = mcp_tool_followup(call_id, tool_name, tool_text)
  287. if mcp is not None:
  288. return mcp
  289. fs_search = fs_search_tool_followup(call_id, tool_name, tool_text)
  290. if fs_search is not None:
  291. return fs_search
  292. minimal = minimal_tool_followup(body, call_id, tool_name, tool_text)
  293. if minimal is not None:
  294. return minimal
  295. advanced = advanced_tool_followup(body, call_id, tool_name, tool_text)
  296. if advanced is not None:
  297. return advanced
  298. if "42" not in tool_text:
  299. raise AssertionError(f"{tool_name} worker returned no expected value: {latest}")
  300. if tool_name == "run_code":
  301. return text_chunks(CODE_WORKER_TEXT)
  302. if tool_name == "workflow":
  303. return text_chunks(WORKFLOW_WORKER_TEXT)
  304. raise AssertionError(f"unexpected tool follow-up: {tool_name}")
  305. user_prompts = [
  306. message_text(message.get("content"))
  307. for message in reversed(messages)
  308. if isinstance(message, dict) and message.get("role") == "user"
  309. ]
  310. minimal_prompt = next(
  311. (
  312. prompt
  313. for prompt in user_prompts
  314. if prompt.startswith(f"{MINIMAL_PROMPT}\n{MINIMAL_EDITOR_PATH_PREFIX}")
  315. ),
  316. None,
  317. )
  318. # The minimal composition's assembled system prompt, advertised tool schemas, and
  319. # model-visible messages are pinned by its snapshot, not asserted here.
  320. if minimal_prompt is not None:
  321. return tool_call_chunks(
  322. "minimal-bash-1",
  323. MINIMAL_SHELL_TOOL,
  324. {"command": MINIMAL_SHELL_COMMAND},
  325. )
  326. scenario_prompts = {
  327. SNAPSHOT_DIRECT_CHILD_PROMPT,
  328. SNAPSHOT_WORKFLOW_CHILD_PROMPT,
  329. SNAPSHOT_PROMPT,
  330. CODE_PROMPT,
  331. WORKFLOW_PROMPT,
  332. FS_SEARCH_PROMPT,
  333. MCP_PROMPT,
  334. RESTART_FIRST_PROMPT,
  335. RESTART_SECOND_PROMPT,
  336. PROFILE_PLUGIN_PROMPT,
  337. }
  338. prompt = next(
  339. (candidate for candidate in user_prompts if candidate in scenario_prompts),
  340. message_text(latest.get("content")),
  341. )
  342. if prompt == SNAPSHOT_DIRECT_CHILD_PROMPT:
  343. return text_chunks("DIRECT_CHILD_OK")
  344. if prompt == SNAPSHOT_WORKFLOW_CHILD_PROMPT:
  345. return text_chunks("WORKFLOW_CHILD_OK")
  346. if prompt == SNAPSHOT_PROMPT:
  347. assert_advertised_tool(body, "cordis_define")
  348. return tool_call_chunks(
  349. "advanced-define",
  350. "cordis_define",
  351. {
  352. "plugin": {"kind": "new", "idPrefix": "snap"},
  353. "name": "Snapshot Double",
  354. "purpose": "Expose a deterministic doubling tool for executable snapshot verification.",
  355. "code": {"host": SNAPSHOT_PLUGIN_CODE},
  356. },
  357. )
  358. if prompt == RESTART_FIRST_PROMPT:
  359. return text_chunks(RESTART_FIRST_TEXT)
  360. if prompt == RESTART_SECOND_PROMPT:
  361. if any(
  362. isinstance(message, dict)
  363. and RESTART_FIRST_TEXT in message_text(message.get("content"))
  364. for message in messages
  365. ):
  366. raise AssertionError("second isolated process inherited the first process history")
  367. return text_chunks(RESTART_SECOND_TEXT)
  368. if prompt == CODE_PROMPT:
  369. assert_advertised_tool(body, "run_code")
  370. return tool_call_chunks(
  371. "call-code-worker",
  372. "run_code",
  373. {"code": "return 6 * 7", "description": "Compute the smoke value"},
  374. )
  375. if prompt == WORKFLOW_PROMPT:
  376. assert_advertised_tool(body, "workflow")
  377. return tool_call_chunks(
  378. "call-workflow-worker",
  379. "workflow",
  380. {
  381. "script": "return 6 * 7",
  382. "meta": {
  383. "name": "pkg-worker-smoke",
  384. "description": "exercise the packaged workflow worker",
  385. },
  386. },
  387. )
  388. if prompt == FS_SEARCH_PROMPT:
  389. assert_advertised_tool(body, "grep")
  390. assert_advertised_tool(body, "glob")
  391. return tool_call_chunks(
  392. "fs-search-grep",
  393. "grep",
  394. {"pattern": FS_SEARCH_MARKER, "path": "."},
  395. )
  396. if prompt == MCP_PROMPT:
  397. assert_advertised_tool(body, "mcp__fixture__add")
  398. return tool_call_chunks(
  399. "mcp-add",
  400. "mcp__fixture__add",
  401. {"a": 19, "b": 23},
  402. )
  403. if prompt == PROFILE_PLUGIN_PROMPT:
  404. system_text = "\n".join(
  405. message_text(message.get("content"))
  406. for message in messages
  407. if isinstance(message, dict) and message.get("role") == "system"
  408. )
  409. if PROFILE_PLUGIN_MARKER not in system_text:
  410. raise AssertionError("external profile plugin contributed no model-visible marker")
  411. return text_chunks(PROFILE_PLUGIN_TEXT)
  412. return text_chunks(EXPECTED_TEXT)
  413. def mcp_tool_followup(
  414. call_id: str,
  415. tool_name: str,
  416. tool_text: str,
  417. ) -> list[dict[str, object]] | None:
  418. """Verify one tool call through the packaged MCP client."""
  419. if call_id != "mcp-add":
  420. return None
  421. if tool_name != "mcp__fixture__add" or "42" not in tool_text:
  422. raise AssertionError(f"packaged MCP call returned an unexpected result: {tool_name}: {tool_text}")
  423. return text_chunks(MCP_TEXT)
  424. def fs_search_tool_followup(
  425. call_id: str,
  426. tool_name: str,
  427. tool_text: str,
  428. ) -> list[dict[str, object]] | None:
  429. """Exercise both ripgrep-backed tools through the packaged executable."""
  430. if not call_id.startswith("fs-search-"):
  431. return None
  432. if call_id == "fs-search-grep" and tool_name == "grep":
  433. if "needle.txt" not in tool_text or FS_SEARCH_MARKER not in tool_text:
  434. raise AssertionError(f"packaged grep returned no marker: {tool_text}")
  435. return tool_call_chunks(
  436. "fs-search-glob",
  437. "glob",
  438. {"pattern": "**/*.txt"},
  439. )
  440. if call_id == "fs-search-glob" and tool_name == "glob":
  441. if "needle.txt" not in tool_text:
  442. raise AssertionError(f"packaged glob returned no fixture path: {tool_text}")
  443. return text_chunks(FS_SEARCH_TEXT)
  444. raise AssertionError(f"unexpected filesystem-search follow-up: {call_id} {tool_name}: {tool_text}")
  445. def minimal_tool_followup(
  446. body: dict[str, object],
  447. call_id: str,
  448. tool_name: str,
  449. tool_text: str,
  450. ) -> list[dict[str, object]] | None:
  451. """Verify the checked-in minimal composition's PTY and editor."""
  452. if not call_id.startswith("minimal-"):
  453. return None
  454. if call_id == "minimal-bash-1" and tool_name == MINIMAL_SHELL_TOOL:
  455. if "COUNT=1" not in tool_text:
  456. raise AssertionError(f"first persistent shell call lost its output: {tool_text}")
  457. return tool_call_chunks(
  458. "minimal-bash-2",
  459. MINIMAL_SHELL_TOOL,
  460. {"command": MINIMAL_SHELL_COMMAND},
  461. )
  462. if call_id == "minimal-bash-2" and tool_name == MINIMAL_SHELL_TOOL:
  463. expected = f"COUNT=2 CWD={MINIMAL_SHELL_SECOND_CWD}"
  464. if expected.lower() not in tool_text.lower():
  465. raise AssertionError(f"persistent shell did not retain state: {tool_text}")
  466. messages = body.get("messages")
  467. if not isinstance(messages, list):
  468. raise AssertionError("persistent editor smoke request has no messages")
  469. editor_path = next(
  470. (
  471. text.split(MINIMAL_EDITOR_PATH_PREFIX, 1)[1].strip()
  472. for message in messages
  473. if isinstance(message, dict) and message.get("role") == "user"
  474. for text in [message_text(message.get("content"))]
  475. if MINIMAL_EDITOR_PATH_PREFIX in text
  476. ),
  477. None,
  478. )
  479. if editor_path is None:
  480. raise AssertionError("persistent editor smoke prompt has no editor path")
  481. return tool_call_chunks(
  482. "minimal-editor",
  483. "str_replace_editor",
  484. {
  485. "command": "create",
  486. "path": editor_path,
  487. "file_text": "created by packaged editor\n",
  488. },
  489. )
  490. if call_id == "minimal-editor" and tool_name == "str_replace_editor":
  491. if "New file created successfully" not in tool_text:
  492. raise AssertionError(f"packaged editor did not create its file: {tool_text}")
  493. return text_chunks(MINIMAL_TEXT)
  494. raise AssertionError(f"unexpected minimal-agent follow-up: {call_id} {tool_name}: {tool_text}")
  495. def advanced_tool_followup(
  496. body: dict[str, object],
  497. call_id: str,
  498. tool_name: str,
  499. tool_text: str,
  500. ) -> list[dict[str, object]] | None:
  501. """Advance the executable snapshot's deterministic parent tool chain."""
  502. if not call_id.startswith("advanced-"):
  503. return None
  504. if call_id == "advanced-define" and tool_name == "cordis_define":
  505. if "Defined snap-1/pkg-1 (Snapshot Double)" not in tool_text:
  506. raise AssertionError(f"cordis_define returned no dynamic Package ids: {tool_text}")
  507. if "snapshot_double" in advertised_tool_names(body):
  508. raise AssertionError("snapshot_double was advertised before cordis_run")
  509. assert_advertised_tool(body, "cordis_run")
  510. return tool_call_chunks(
  511. "advanced-run",
  512. "cordis_run",
  513. {"pluginId": "snap-1", "packageId": "pkg-1", "mode": "run"},
  514. )
  515. if call_id == "advanced-run" and tool_name == "cordis_run":
  516. if "snap-1/pkg-1 is running (run-1)" not in tool_text:
  517. raise AssertionError(f"cordis_run returned no running Package ids: {tool_text}")
  518. assert_advertised_tool(body, "run_code")
  519. assert_advertised_tool(body, "snapshot_double")
  520. return tool_call_chunks(
  521. "advanced-code",
  522. "run_code",
  523. {
  524. "code": "return await tools.snapshot_double({ value: 21 })",
  525. "description": "Run the temporary Plugin tool",
  526. },
  527. )
  528. if call_id == "advanced-code" and tool_name == "run_code":
  529. if "42" not in tool_text:
  530. raise AssertionError(f"run_code returned no dynamic-tool value: {tool_text}")
  531. assert_advertised_tool(body, "subagent")
  532. return tool_call_chunks(
  533. "advanced-direct-child",
  534. "subagent",
  535. {
  536. "description": "Check direct child",
  537. "prompt": SNAPSHOT_DIRECT_CHILD_PROMPT,
  538. },
  539. )
  540. if call_id == "advanced-direct-child" and tool_name == "subagent":
  541. if "DIRECT_CHILD_OK" not in tool_text:
  542. raise AssertionError(f"subagent returned no expected child value: {tool_text}")
  543. assert_advertised_tool(body, "workflow")
  544. return tool_call_chunks(
  545. "advanced-workflow",
  546. "workflow",
  547. {
  548. "script": SNAPSHOT_WORKFLOW_SCRIPT,
  549. "meta": {
  550. "name": "advanced-exe-snapshot",
  551. "description": "exercise one packaged workflow child",
  552. },
  553. },
  554. )
  555. if call_id == "advanced-workflow" and tool_name == "workflow":
  556. if "WORKFLOW_CHILD_OK" not in tool_text:
  557. raise AssertionError(f"workflow returned no expected child value: {tool_text}")
  558. assert_advertised_tool(body, "cordis_undefine")
  559. return tool_call_chunks(
  560. "advanced-undefine",
  561. "cordis_undefine",
  562. {"pluginId": "snap-1"},
  563. )
  564. if call_id == "advanced-undefine" and tool_name == "cordis_undefine":
  565. if "Removed dynamic Plugin snap-1 and all of its Packages." not in tool_text:
  566. raise AssertionError(f"cordis_undefine returned no removal result: {tool_text}")
  567. if "snapshot_double" in advertised_tool_names(body):
  568. raise AssertionError("snapshot_double remained advertised after cordis_undefine")
  569. return text_chunks(SNAPSHOT_FINAL_TEXT)
  570. raise AssertionError(f"unexpected advanced tool follow-up: {call_id} {tool_name}: {tool_text}")
  571. def text_chunks(text: str) -> list[dict[str, object]]:
  572. """Build a complete streaming text response."""
  573. return [
  574. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  575. {"choices": [{"delta": {"content": text}}]},
  576. {
  577. "choices": [{"delta": {"content": ""}, "finish_reason": "stop"}],
  578. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  579. },
  580. ]
  581. def tool_call_chunks(call_id: str, name: str, arguments: dict[str, object]) -> list[dict[str, object]]:
  582. """Build a complete streaming function-call response."""
  583. return [
  584. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  585. {
  586. "choices": [{
  587. "delta": {
  588. "tool_calls": [{
  589. "index": 0,
  590. "id": call_id,
  591. "type": "function",
  592. "function": {"name": name, "arguments": json.dumps(arguments)},
  593. }],
  594. },
  595. }],
  596. },
  597. {
  598. "choices": [{"delta": {"content": ""}, "finish_reason": "tool_calls"}],
  599. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  600. },
  601. ]
  602. def latest_tool_call(messages: list[object]) -> tuple[str, str]:
  603. """Find the assistant call id and name paired with the latest tool result."""
  604. for message in reversed(messages[:-1]):
  605. if not isinstance(message, dict):
  606. continue
  607. calls = message.get("tool_calls")
  608. if not isinstance(calls, list):
  609. continue
  610. for call in reversed(calls):
  611. if not isinstance(call, dict):
  612. continue
  613. function = call.get("function")
  614. call_id = call.get("id")
  615. if (
  616. isinstance(call_id, str)
  617. and isinstance(function, dict)
  618. and isinstance(function.get("name"), str)
  619. ):
  620. return call_id, function["name"]
  621. raise AssertionError(f"tool result has no preceding assistant tool call: {messages}")
  622. def message_text(content: object) -> str:
  623. """Read OpenAI text content in either string or block-list form."""
  624. if isinstance(content, str):
  625. return content
  626. if isinstance(content, list):
  627. return "".join(
  628. block.get("text", "")
  629. for block in content
  630. if isinstance(block, dict) and isinstance(block.get("text"), str)
  631. )
  632. return ""
  633. def advertised_tool_names(body: dict[str, object]) -> set[str]:
  634. """Return the model-facing tool names advertised on one request."""
  635. tools = body.get("tools")
  636. if not isinstance(tools, list):
  637. raise AssertionError(f"model request advertised no tools: {body}")
  638. names: set[str] = set()
  639. for tool in tools:
  640. if not isinstance(tool, dict):
  641. continue
  642. function = tool.get("function")
  643. if isinstance(function, dict) and isinstance(function.get("name"), str):
  644. names.add(function["name"])
  645. return names
  646. def assert_advertised_tool(body: dict[str, object], expected: str) -> None:
  647. """Require the packaged deployment to expose the requested tool."""
  648. names = advertised_tool_names(body)
  649. if expected not in names:
  650. raise AssertionError(f"model request did not advertise {expected}: {names}")
  651. class MockModel:
  652. def __enter__(self) -> "MockModel":
  653. MockModelHandler.requests.clear()
  654. self.server = ThreadingHTTPServer(("127.0.0.1", 0), MockModelHandler)
  655. self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
  656. self.thread.start()
  657. host, port = self.server.server_address
  658. self.url = f"http://{host}:{port}"
  659. return self
  660. def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
  661. self.server.shutdown()
  662. self.server.server_close()
  663. self.thread.join(timeout=5)
  664. def main() -> None:
  665. parser = argparse.ArgumentParser(description=__doc__)
  666. parser.add_argument(
  667. "--scenario",
  668. choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-mcp", "sdk-snapshot", "sdk-restart", "sdk-profile-plugin", "sdk-live", "direct"),
  669. default="all",
  670. )
  671. parser.add_argument("--exe", type=Path)
  672. parser.add_argument(
  673. "--installed-wheel",
  674. action="store_true",
  675. help="require a clean virtual environment containing matching installed SDK and runtime wheels",
  676. )
  677. parser.add_argument("--update-snapshots", action="store_true")
  678. args = parser.parse_args()
  679. if args.installed_wheel and args.exe is not None:
  680. parser.error("--installed-wheel resolves the wheel's own runtime and cannot be combined with --exe")
  681. if args.scenario == "sdk-live" and not args.installed_wheel:
  682. parser.error("--scenario sdk-live requires --installed-wheel")
  683. if args.scenario == "sdk-profile-plugin" and not args.installed_wheel:
  684. parser.error("--scenario sdk-profile-plugin requires --installed-wheel")
  685. if args.installed_wheel:
  686. args.exe = assert_installed_wheel_environment()
  687. if args.scenario in {"all", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-snapshot", "sdk-restart", "direct"} and args.exe is None:
  688. parser.error("--exe is required for custom, minimal, snapshot, and direct scenarios")
  689. if args.update_snapshots and args.scenario not in {"all", "sdk-minimal", "sdk-snapshot", "sdk-restart"}:
  690. parser.error("--update-snapshots requires --scenario sdk-minimal, sdk-snapshot, sdk-restart, or all")
  691. if args.exe is not None and not args.exe.is_file():
  692. parser.error(f"runtime executable does not exist: {args.exe}")
  693. if args.scenario == "sdk-live":
  694. smoke_sdk_live()
  695. print("smoke-python-runtime: sdk-live passed")
  696. return
  697. with MockModel() as model:
  698. if args.scenario in {"all", "sdk-default"}:
  699. smoke_sdk_default(model.url)
  700. if args.scenario in {"all", "sdk-custom"}:
  701. assert args.exe is not None
  702. smoke_sdk_custom(model.url, args.exe.resolve())
  703. if args.scenario in {"all", "sdk-minimal"}:
  704. assert args.exe is not None
  705. smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots)
  706. if args.scenario in {"all", "sdk-fs-search"}:
  707. assert args.exe is not None
  708. smoke_sdk_fs_search(model.url, args.exe.resolve())
  709. if args.scenario in {"all", "sdk-mcp"}:
  710. smoke_sdk_mcp(model.url, None if args.exe is None else args.exe.resolve())
  711. if args.scenario in {"all", "sdk-snapshot"}:
  712. assert args.exe is not None
  713. smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  714. if args.scenario in {"all", "sdk-restart"}:
  715. assert args.exe is not None
  716. smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  717. if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}:
  718. smoke_sdk_profile_plugin(model.url)
  719. if args.scenario in {"all", "direct"}:
  720. assert args.exe is not None
  721. smoke_direct(model.url, args.exe.resolve())
  722. if not MockModelHandler.requests:
  723. raise AssertionError("mock model endpoint received no requests")
  724. print(f"smoke-python-runtime: {args.scenario} passed")
  725. def assert_installed_wheel_environment() -> Path:
  726. """Prove that this process imports matching non-editable wheel installations."""
  727. if sys.prefix == sys.base_prefix:
  728. raise AssertionError("installed-wheel smoke must run inside a virtual environment")
  729. if os.environ.get("PYTHONPATH"):
  730. raise AssertionError("installed-wheel smoke requires PYTHONPATH to be unset")
  731. if os.environ.get("DSH_RUNTIME_MODE"):
  732. raise AssertionError("installed-wheel smoke requires DSH_RUNTIME_MODE to be unset")
  733. repo_root = Path(__file__).resolve().parent.parent
  734. cwd = Path.cwd().resolve()
  735. if cwd.is_relative_to(repo_root):
  736. raise AssertionError(f"installed-wheel smoke must run outside the repository, got {cwd}")
  737. sdk_version = importlib.metadata.version("deepseek-harness-sdk")
  738. runtime_version = importlib.metadata.version("deepseek-harness-runtime-bin")
  739. if sdk_version != runtime_version:
  740. raise AssertionError(
  741. f"installed SDK/runtime versions differ: {sdk_version} != {runtime_version}"
  742. )
  743. expected_runtime_requirement = f"deepseek-harness-runtime-bin=={sdk_version}"
  744. requirements = importlib.metadata.requires("deepseek-harness-sdk") or []
  745. if expected_runtime_requirement not in requirements:
  746. raise AssertionError(
  747. f"installed SDK does not require {expected_runtime_requirement}: {requirements}"
  748. )
  749. prefix = Path(sys.prefix).resolve()
  750. imported: dict[str, Path] = {}
  751. for name in ("deepseek_harness", "deepseek_harness_runtime"):
  752. module = importlib.import_module(name)
  753. module_file = getattr(module, "__file__", None)
  754. if not isinstance(module_file, str):
  755. raise AssertionError(f"installed module {name} has no filesystem location")
  756. path = Path(module_file).resolve()
  757. if not path.is_relative_to(prefix):
  758. raise AssertionError(f"installed module {name} came from outside the virtual environment: {path}")
  759. if path.is_relative_to(repo_root):
  760. raise AssertionError(f"installed module {name} came from the repository checkout: {path}")
  761. imported[name] = path
  762. runtime_module = sys.modules["deepseek_harness_runtime"]
  763. executable = runtime_module.bundled_runtime_path().resolve()
  764. runtime_package = imported["deepseek_harness_runtime"].parent
  765. if not executable.is_relative_to(runtime_package):
  766. raise AssertionError(f"bundled runtime came from outside the installed runtime wheel: {executable}")
  767. runtime_files = importlib.metadata.files("deepseek-harness-runtime-bin") or []
  768. if not any(Path(file).name == executable.name for file in runtime_files):
  769. raise AssertionError(f"runtime executable is absent from installed distribution records: {executable}")
  770. return executable
  771. def smoke_sdk_live() -> None:
  772. """Run a real-model, tool-using two-turn task through installed wheels."""
  773. from deepseek_harness import DeepSeekHarness
  774. api_key = os.environ.get("DEEPSEEK_API_KEY")
  775. base_url = os.environ.get("DEEPSEEK_BASE_URL")
  776. if not api_key:
  777. raise AssertionError("sdk-live requires DEEPSEEK_API_KEY")
  778. if not base_url:
  779. raise AssertionError("sdk-live requires an explicit DEEPSEEK_BASE_URL")
  780. with tempfile.TemporaryDirectory(prefix="dsh-sdk-live-") as temporary:
  781. root = Path(temporary).resolve()
  782. dsh_home = root / "home"
  783. sessions = dsh_home / "sessions"
  784. marker = root / "live-api-marker.txt"
  785. session_id = "installed-wheel-live-api"
  786. shell_tool = "pwsh" if IS_WINDOWS else "bash"
  787. create_prompt = (
  788. f"Use the {shell_tool} tool to create the file at the absolute path below with exactly one line "
  789. f"containing {LIVE_API_SENTINEL}. Then reply with exactly {LIVE_API_SENTINEL}.\n{marker}"
  790. )
  791. verify_prompt = (
  792. "Use a tool to read the file created in the previous turn. "
  793. f"If its only line is {LIVE_API_SENTINEL}, reply with exactly {LIVE_API_SENTINEL}."
  794. )
  795. with DeepSeekHarness(
  796. provider="deepseek-official",
  797. model="deepseek-v4-flash",
  798. cwd=str(root),
  799. dsh_home=str(dsh_home),
  800. env={
  801. "DSH_PERMISSION_MODE": "danger-full-access",
  802. "DSH_TELEMETRY_DISABLED": "1",
  803. },
  804. api_key=api_key,
  805. base_url=base_url,
  806. request_timeout_seconds=180,
  807. ) as harness:
  808. created = harness.run(create_prompt, session_id=session_id)
  809. verified = harness.run(verify_prompt, session_id=session_id)
  810. for label, result in (("create", created), ("verify", verified)):
  811. if result.finish_reason != "completed":
  812. event_types = [event.get("type") for event in result.events]
  813. turn_end_data = next(
  814. (event.get("data") for event in reversed(result.events) if event.get("type") == "turn/end"),
  815. None,
  816. )
  817. turn_end = safe_turn_end(turn_end_data)
  818. raise AssertionError(
  819. f"{label} turn ended with {result.finish_reason!r}; "
  820. f"final={result.final_response!r}; turn_end={turn_end!r}; events={event_types}"
  821. )
  822. if not any(event.get("type") == "tool/call" for event in result.events):
  823. raise AssertionError(
  824. f"{label} turn made no model-requested tool call; "
  825. f"final={result.final_response!r}"
  826. )
  827. if result.final_response.strip() != LIVE_API_SENTINEL:
  828. raise AssertionError(f"{label} turn returned {result.final_response!r}")
  829. if not marker.is_file():
  830. raise AssertionError(f"real-model tool turn did not create {marker}")
  831. if marker.read_text(encoding="utf-8").splitlines() != [LIVE_API_SENTINEL]:
  832. raise AssertionError(f"real-model tool turn wrote unexpected text to {marker}")
  833. assert_zstd_session_log(sessions)
  834. def safe_turn_end(value: object) -> object:
  835. """Project a live-provider failure without retaining credential-bearing text."""
  836. if not isinstance(value, dict):
  837. return value
  838. reason = value.get("reason")
  839. if not isinstance(reason, dict):
  840. return {"turn": value.get("turn"), "reason": reason}
  841. error = reason.get("error")
  842. safe_error = None
  843. if isinstance(error, dict):
  844. safe_error = {
  845. key: error.get(key)
  846. for key in ("code", "status")
  847. if error.get(key) is not None
  848. }
  849. return {
  850. "turn": value.get("turn"),
  851. "reason": {
  852. "kind": reason.get("kind"),
  853. **({"error": safe_error} if safe_error is not None else {}),
  854. },
  855. }
  856. def smoke_sdk_default(base_url: str) -> None:
  857. from deepseek_harness import DeepSeekHarness
  858. with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary:
  859. root = Path(temporary).resolve()
  860. dsh_home = root / "home"
  861. sessions = dsh_home / "sessions"
  862. with DeepSeekHarness(
  863. provider="deepseek-official",
  864. model="smoke-model",
  865. cwd=str(root),
  866. dsh_home=str(dsh_home),
  867. env={
  868. "DSH_PERMISSION_MODE": "danger-full-access",
  869. "DSH_TELEMETRY_DISABLED": "1",
  870. },
  871. api_key="sk-keyless-smoke",
  872. base_url=base_url,
  873. request_timeout_seconds=60,
  874. ) as harness:
  875. result = harness.run("reply with the smoke text", session_id="default-smoke")
  876. assert result.final_response == EXPECTED_TEXT, (
  877. f"final={result.final_response!r} finish={result.finish_reason!r} "
  878. f"events={[event.get('type') for event in result.events]!r} "
  879. f"turn_end={safe_turn_end(next((event.get('data', event) for event in reversed(result.events) if event.get('type') == 'turn/end'), {}))!r}"
  880. )
  881. assert_zstd_session_log(sessions)
  882. def smoke_sdk_custom(base_url: str, executable: Path) -> None:
  883. from deepseek_harness import DeepSeekHarness
  884. with tempfile.TemporaryDirectory(prefix="dsh-sdk-custom-") as temporary:
  885. root = Path(temporary).resolve()
  886. dsh_home = root / "home"
  887. sessions = dsh_home / "sessions"
  888. patch = write_advanced_profile_patch(root, "custom.patch.yml", sessions)
  889. with DeepSeekHarness(
  890. provider="deepseek-official",
  891. model="smoke-model",
  892. cwd=str(root),
  893. dsh_bin=str(executable),
  894. dsh_home=str(dsh_home),
  895. patches=(str(patch),),
  896. env={
  897. "DSH_PERMISSION_MODE": "danger-full-access",
  898. "DSH_TELEMETRY_DISABLED": "1",
  899. },
  900. api_key="sk-keyless-smoke",
  901. base_url=base_url,
  902. request_timeout_seconds=60,
  903. ) as harness:
  904. text_result = harness.run("reply with the smoke text", session_id="custom-smoke")
  905. code_result = harness.run(CODE_PROMPT, session_id="custom-smoke")
  906. workflow_result = harness.run(WORKFLOW_PROMPT, session_id="custom-smoke")
  907. assert text_result.final_response == EXPECTED_TEXT, text_result.final_response
  908. assert code_result.final_response == CODE_WORKER_TEXT, code_result.final_response
  909. assert workflow_result.final_response == WORKFLOW_WORKER_TEXT, workflow_result.final_response
  910. assert_session_log(sessions, root, EXPECTED_TEXT, CODE_WORKER_TEXT, WORKFLOW_WORKER_TEXT)
  911. def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) -> None:
  912. """Exercise the shipped standalone minimal profile through the packaged executable."""
  913. from deepseek_harness import DeepSeekHarness
  914. # One mock model serves every scenario of a run, so the snapshot takes this turn's slice.
  915. first_request = len(MockModelHandler.requests)
  916. with tempfile.TemporaryDirectory(prefix="dsh-sdk-minimal-") as temporary:
  917. root = Path(temporary).resolve()
  918. editor_path = root / "created.txt"
  919. prompt = f"{MINIMAL_PROMPT}\n{MINIMAL_EDITOR_PATH_PREFIX}{editor_path}"
  920. dsh_home = root / "home"
  921. sessions = dsh_home / "sessions"
  922. with DeepSeekHarness(
  923. provider="deepseek-official",
  924. model="smoke-model",
  925. cwd=str(root),
  926. dsh_bin=str(executable),
  927. dsh_home=str(dsh_home),
  928. profile="sdk-minimal",
  929. api_key="sk-keyless-smoke",
  930. base_url=base_url,
  931. request_timeout_seconds=60,
  932. ) as harness:
  933. result = harness.run(prompt, session_id="minimal-agent-smoke")
  934. event_text = json.dumps(result.events)
  935. if MINIMAL_TEXT not in event_text:
  936. raise AssertionError(f"minimal agent run emitted no final response: {result.events}")
  937. if editor_path.read_text() != "created by packaged editor\n":
  938. raise AssertionError(f"packaged editor wrote unexpected content: {editor_path.read_text()!r}")
  939. assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2")
  940. files = build_minimal_snapshot_files(MockModelHandler.requests[first_request:], root)
  941. compare_snapshot_files(
  942. files, update_snapshots, MINIMAL_SNAPSHOT_DIRECTORY, MINIMAL_SNAPSHOT_FILENAMES,
  943. )
  944. def smoke_sdk_fs_search(base_url: str, executable: Path) -> None:
  945. """Exercise real grep and glob spawns through the packaged executable."""
  946. from deepseek_harness import DeepSeekHarness
  947. with tempfile.TemporaryDirectory(prefix="dsh-sdk-fs-search-") as temporary:
  948. root = Path(temporary).resolve()
  949. (root / "needle.txt").write_text(f"{FS_SEARCH_MARKER}\n")
  950. dsh_home = root / "home"
  951. sessions = dsh_home / "sessions"
  952. patch = write_profile_patch(root, "fs-search.patch.yml", sessions, [
  953. {"id": "skill-filesystem", "disabled": True},
  954. {"id": "tool-fs-search", "config": {"sampleOverCapGlobResults": False}},
  955. ])
  956. with DeepSeekHarness(
  957. provider="deepseek-official",
  958. model="smoke-model",
  959. cwd=str(root),
  960. dsh_bin=str(executable),
  961. dsh_home=str(dsh_home),
  962. patches=(str(patch),),
  963. env={
  964. "DSH_PERMISSION_MODE": "danger-full-access",
  965. "DSH_TELEMETRY_DISABLED": "1",
  966. },
  967. api_key="sk-keyless-smoke",
  968. base_url=base_url,
  969. request_timeout_seconds=60,
  970. ) as harness:
  971. result = harness.run(FS_SEARCH_PROMPT, session_id="fs-search-smoke")
  972. assert result.final_response == FS_SEARCH_TEXT, result.final_response
  973. assert_session_log(sessions, root, FS_SEARCH_TEXT, FS_SEARCH_MARKER, "needle.txt")
  974. def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None:
  975. """Discover and call an external stdio MCP tool through the packaged client."""
  976. from deepseek_harness import DeepSeekHarness
  977. with tempfile.TemporaryDirectory(prefix="dsh-sdk-mcp-") as temporary:
  978. root = Path(temporary).resolve()
  979. dsh_home = root / "home"
  980. sessions = dsh_home / "sessions"
  981. server_script = root / "mcp_server.py"
  982. server_script.write_text(MCP_SERVER_SCRIPT)
  983. patch = write_mcp_patch(root, sessions, server_script)
  984. discovery_log = server_script.with_suffix(".log")
  985. with DeepSeekHarness(
  986. provider="deepseek-official",
  987. model="smoke-model",
  988. cwd=str(root),
  989. dsh_bin=None if executable is None else str(executable),
  990. dsh_home=str(dsh_home),
  991. patches=(str(patch),),
  992. env={
  993. "DSH_PERMISSION_MODE": "danger-full-access",
  994. "DSH_TELEMETRY_DISABLED": "1",
  995. },
  996. api_key="sk-keyless-smoke",
  997. base_url=base_url,
  998. request_timeout_seconds=60,
  999. ) as harness:
  1000. result = harness.run(MCP_PROMPT, session_id="mcp-smoke")
  1001. assert result.final_response == MCP_TEXT, result.final_response
  1002. assert discovery_log.read_text().splitlines() == [
  1003. "initialize",
  1004. "notifications/initialized",
  1005. "tools/list",
  1006. "tools/call",
  1007. ]
  1008. assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42")
  1009. def smoke_sdk_profile_plugin(base_url: str) -> None:
  1010. """Install an external bundle through Python's dsh command and load it in the SDK."""
  1011. from deepseek_harness import DeepSeekHarness
  1012. with tempfile.TemporaryDirectory(prefix="dsh-sdk-profile-plugin-") as temporary:
  1013. root = Path(temporary).resolve()
  1014. dsh_home = root / "home"
  1015. plugin = root / "plugin"
  1016. plugin.mkdir()
  1017. (plugin / "package.json").write_text(json.dumps({
  1018. "name": "dsh-python-blackbox-plugin",
  1019. "version": "1.0.0",
  1020. "private": True,
  1021. "type": "module",
  1022. "exports": "./index.js",
  1023. "peerDependencies": {"@deepseek-ai/cordis": "*"},
  1024. "dsh": {"bundle": {"patch": "./cordis.patch.yml"}},
  1025. }, indent=2))
  1026. (plugin / "index.js").write_text(
  1027. "import { Context } from '@deepseek-ai/cordis'\n"
  1028. "export const name = 'python-sdk-blackbox-plugin'\n"
  1029. "export const inject = ['systemPrompt']\n"
  1030. "export function apply(ctx) {\n"
  1031. " if (!(ctx instanceof Context)) throw new Error('external plugin loaded a second Cordis instance')\n"
  1032. " ctx.effect(() => ctx.systemPrompt.section({\n"
  1033. " name: 'python-sdk:blackbox-plugin',\n"
  1034. " order: 10,\n"
  1035. f" text: '{PROFILE_PLUGIN_MARKER}',\n"
  1036. " }))\n"
  1037. "}\n"
  1038. )
  1039. (plugin / "cordis.patch.yml").write_text(json.dumps([{
  1040. "insert": [{"id": "python-sdk-blackbox-plugin", "name": "dsh-python-blackbox-plugin"}],
  1041. }], indent=2))
  1042. dsh = Path(sysconfig.get_path("scripts")) / ("dsh.exe" if IS_WINDOWS else "dsh")
  1043. environment = {**os.environ, "DSH_HOME": str(dsh_home)}
  1044. installed = subprocess.run(
  1045. [str(dsh), "plugin", "--profile", "sdk", "add", f"file:{plugin}"],
  1046. cwd=root,
  1047. env=environment,
  1048. text=True,
  1049. capture_output=True,
  1050. check=False,
  1051. )
  1052. if installed.returncode != 0:
  1053. raise AssertionError(
  1054. f"Python-installed dsh could not add the external profile plugin: "
  1055. f"stdout={installed.stdout!r} stderr={installed.stderr!r}"
  1056. )
  1057. manifest = json.loads((dsh_home / "profiles" / "sdk" / "package.json").read_text())
  1058. if "dsh-python-blackbox-plugin" not in manifest.get("dependencies", {}):
  1059. raise AssertionError(f"dsh plugin did not record the external dependency: {manifest}")
  1060. if "dsh-python-blackbox-plugin" not in manifest["dsh"]["profile"]["bundles"]:
  1061. raise AssertionError(f"dsh plugin did not activate the external bundle: {manifest}")
  1062. harness = DeepSeekHarness(
  1063. provider="deepseek-official",
  1064. model="smoke-model",
  1065. cwd=str(root),
  1066. dsh_home=str(dsh_home),
  1067. env={
  1068. "DSH_PERMISSION_MODE": "danger-full-access",
  1069. "DSH_TELEMETRY_DISABLED": "1",
  1070. },
  1071. api_key="sk-keyless-smoke",
  1072. base_url=base_url,
  1073. request_timeout_seconds=60,
  1074. )
  1075. try:
  1076. with harness:
  1077. result = harness.run(PROFILE_PLUGIN_PROMPT, session_id="profile-plugin-smoke")
  1078. except Exception as error:
  1079. raise AssertionError(
  1080. f"external profile plugin runtime failed: {harness.client._runtime_diagnostics()}"
  1081. ) from error
  1082. assert result.final_response == PROFILE_PLUGIN_TEXT, result.final_response
  1083. assert_zstd_session_log(dsh_home / "sessions")
  1084. def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  1085. """Drive and compare the advanced SDK/executable behavioral snapshot."""
  1086. from deepseek_harness import DeepSeekHarness
  1087. with tempfile.TemporaryDirectory(prefix="dsh-sdk-snapshot-") as temporary:
  1088. root = Path(temporary).resolve()
  1089. dsh_home = root / "home"
  1090. sessions = dsh_home / "sessions"
  1091. patch = write_advanced_profile_patch(root, "snapshot.patch.yml", sessions)
  1092. with DeepSeekHarness(
  1093. provider="deepseek-official",
  1094. model="smoke-model",
  1095. cwd=str(root),
  1096. dsh_bin=str(executable),
  1097. dsh_home=str(dsh_home),
  1098. patches=(str(patch),),
  1099. env={
  1100. "DSH_PERMISSION_MODE": "danger-full-access",
  1101. "DSH_TELEMETRY_DISABLED": "1",
  1102. },
  1103. api_key="sk-keyless-smoke",
  1104. base_url=base_url,
  1105. request_timeout_seconds=60,
  1106. ) as harness:
  1107. result = harness.run(SNAPSHOT_PROMPT, session_id=SNAPSHOT_SESSION_ID)
  1108. assert result.final_response == SNAPSHOT_FINAL_TEXT, result.final_response
  1109. methods = [notification.method for notification in result.notifications]
  1110. if methods.count("subagent.started") != 2 or methods.count("subagent.finished") != 2:
  1111. raise AssertionError(f"advanced snapshot emitted unexpected subagent lifecycle: {methods}")
  1112. if not any(event.get("type") == "tool/code-dispatch" for event in result.events):
  1113. raise AssertionError("advanced snapshot emitted no tool/code-dispatch event")
  1114. logs = read_session_logs(sessions)
  1115. child_ids = snapshot_child_ids(result)
  1116. expected_ids = {SNAPSHOT_SESSION_ID, *child_ids}
  1117. if set(logs) != expected_ids:
  1118. raise AssertionError(f"advanced snapshot expected parent plus two child logs: {sorted(logs)}")
  1119. if "DIRECT_CHILD_OK" not in render_jsonl(logs[child_ids[0]]):
  1120. raise AssertionError("first advanced child log has no direct-subagent result")
  1121. if "WORKFLOW_CHILD_OK" not in render_jsonl(logs[child_ids[1]]):
  1122. raise AssertionError("second advanced child log has no workflow-subagent result")
  1123. files = build_snapshot_files(result, logs, child_ids, root)
  1124. compare_snapshot_files(
  1125. files, update_snapshots, ADVANCED_SNAPSHOT_DIRECTORY, ADVANCED_SNAPSHOT_FILENAMES,
  1126. )
  1127. def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  1128. """Snapshot two isolated sessions across complete SDK runtime restarts."""
  1129. from deepseek_harness import DeepSeekHarness
  1130. with tempfile.TemporaryDirectory(prefix="dsh-sdk-restart-") as temporary:
  1131. root = Path(temporary).resolve()
  1132. dsh_home = root / "home"
  1133. sessions = dsh_home / "sessions"
  1134. patch = write_advanced_profile_patch(root, "restart.patch.yml", sessions)
  1135. first_request = len(MockModelHandler.requests)
  1136. def run(prompt: str, session_id: str) -> "RunResult":
  1137. with DeepSeekHarness(
  1138. provider="deepseek-official",
  1139. model="smoke-model",
  1140. cwd=str(root),
  1141. dsh_bin=str(executable),
  1142. dsh_home=str(dsh_home),
  1143. patches=(str(patch),),
  1144. env={
  1145. "DSH_PERMISSION_MODE": "danger-full-access",
  1146. "DSH_TELEMETRY_DISABLED": "1",
  1147. },
  1148. api_key="sk-keyless-smoke",
  1149. base_url=base_url,
  1150. request_timeout_seconds=60,
  1151. ) as harness:
  1152. return harness.run(prompt, session_id=session_id)
  1153. first = run(RESTART_FIRST_PROMPT, RESTART_FIRST_SESSION_ID)
  1154. second = run(RESTART_SECOND_PROMPT, RESTART_SECOND_SESSION_ID)
  1155. requests = MockModelHandler.requests[first_request:]
  1156. if len(requests) != 2:
  1157. raise AssertionError(f"restart snapshot expected two model requests: {requests}")
  1158. if first.final_response != RESTART_FIRST_TEXT or second.final_response != RESTART_SECOND_TEXT:
  1159. raise AssertionError(
  1160. f"restart snapshot responses differ: {first.final_response!r}, {second.final_response!r}"
  1161. )
  1162. logs = read_session_logs(sessions)
  1163. expected_ids = {RESTART_FIRST_SESSION_ID, RESTART_SECOND_SESSION_ID}
  1164. if set(logs) != expected_ids:
  1165. raise AssertionError(f"restart snapshot expected two durable sessions: {sorted(logs)}")
  1166. for session_id, expected in (
  1167. (RESTART_FIRST_SESSION_ID, RESTART_FIRST_TEXT),
  1168. (RESTART_SECOND_SESSION_ID, RESTART_SECOND_TEXT),
  1169. ):
  1170. records = logs[session_id]
  1171. if sum(record.get("type") == "turn/end" for record in records) != 1:
  1172. raise AssertionError(f"restart snapshot {session_id} has an unexpected turn count")
  1173. if expected not in render_jsonl(records):
  1174. raise AssertionError(f"restart snapshot durable log has no {expected}")
  1175. files = build_restart_snapshot_files(
  1176. first,
  1177. second,
  1178. requests,
  1179. logs,
  1180. root,
  1181. sessions,
  1182. compare_released_generations=not update_snapshots,
  1183. )
  1184. compare_snapshot_files(
  1185. files, update_snapshots, RESTART_SNAPSHOT_DIRECTORY, RESTART_SNAPSHOT_FILENAMES,
  1186. )
  1187. def smoke_direct(base_url: str, executable: Path) -> None:
  1188. with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary:
  1189. root = Path(temporary).resolve()
  1190. dsh_home = root / "home"
  1191. sessions = dsh_home / "sessions"
  1192. patch = write_profile_patch(root, "direct.patch.yml", sessions, [])
  1193. environment = {
  1194. **os.environ,
  1195. "DSH_HOME": str(dsh_home),
  1196. "DSH_PERMISSION_MODE": "danger-full-access",
  1197. "DSH_TELEMETRY_DISABLED": "1",
  1198. "DEEPSEEK_API_KEY": "sk-keyless-smoke",
  1199. "DEEPSEEK_BASE_URL": base_url,
  1200. }
  1201. peer = RuntimePeer(
  1202. [str(executable), "--profile", "sdk", "--patch", str(patch)],
  1203. root,
  1204. environment,
  1205. )
  1206. try:
  1207. peer.send({"jsonrpc": "2.0", "id": "initialize", "method": "initialize", "params": {"cwd": str(root), "provider": "deepseek-official", "model": "smoke-model"}})
  1208. peer.read_until(lambda message: message.get("id") == "initialize")
  1209. peer.send({
  1210. "jsonrpc": "2.0",
  1211. "id": "prompt",
  1212. "method": "session/prompt",
  1213. "params": {"sessionId": "direct-smoke", "contentBlocks": [{"type": "text", "text": "reply with the smoke text"}]},
  1214. })
  1215. messages = peer.read_until(lambda message: message.get("id") == "prompt")
  1216. if not any(is_idle_notification(message) for message in messages):
  1217. messages.extend(peer.read_until(is_idle_notification))
  1218. event_text = json.dumps(messages)
  1219. if EXPECTED_TEXT not in event_text:
  1220. raise AssertionError(f"direct runtime emitted no final response: {messages}")
  1221. peer.send({"jsonrpc": "2.0", "id": "shutdown", "method": "shutdown"})
  1222. peer.read_until(lambda message: message.get("id") == "shutdown")
  1223. finally:
  1224. peer.close()
  1225. assert_session_log(sessions, root, EXPECTED_TEXT)
  1226. def is_idle_notification(message: dict[str, object]) -> bool:
  1227. """Return whether a JSON-RPC notification marks a session idle."""
  1228. params = message.get("params")
  1229. return (
  1230. message.get("method") == "session.status"
  1231. and isinstance(params, dict)
  1232. and params.get("status") == "idle"
  1233. )
  1234. class RuntimePeer:
  1235. def __init__(self, argv: list[str], cwd: Path, environment: dict[str, str]) -> None:
  1236. self.process = subprocess.Popen(
  1237. argv,
  1238. cwd=cwd,
  1239. env=environment,
  1240. stdin=subprocess.PIPE,
  1241. stdout=subprocess.PIPE,
  1242. stderr=subprocess.PIPE,
  1243. text=True,
  1244. encoding="utf-8",
  1245. bufsize=1,
  1246. )
  1247. self.stdout: queue.Queue[str | None] = queue.Queue()
  1248. self.stderr: list[str] = []
  1249. threading.Thread(target=self._read_stdout, daemon=True).start()
  1250. threading.Thread(target=self._read_stderr, daemon=True).start()
  1251. def send(self, message: dict[str, object]) -> None:
  1252. if self.process.stdin is None:
  1253. raise RuntimeError("runtime stdin is unavailable")
  1254. self.process.stdin.write(json.dumps(message) + "\n")
  1255. self.process.stdin.flush()
  1256. def read_until(self, predicate: Callable[[dict[str, object]], bool]) -> list[dict[str, object]]:
  1257. deadline = time.monotonic() + 60
  1258. messages: list[dict[str, object]] = []
  1259. while time.monotonic() < deadline:
  1260. try:
  1261. line = self.stdout.get(timeout=min(0.25, deadline - time.monotonic()))
  1262. except queue.Empty:
  1263. continue
  1264. if line is None:
  1265. raise RuntimeError(f"runtime exited before expected message; stderr: {''.join(self.stderr)}")
  1266. try:
  1267. message = json.loads(line)
  1268. except json.JSONDecodeError:
  1269. continue
  1270. messages.append(message)
  1271. if predicate(message):
  1272. return messages
  1273. raise TimeoutError(f"runtime timed out; messages={messages}; stderr={''.join(self.stderr)}")
  1274. def close(self) -> None:
  1275. if self.process.stdin is not None and not self.process.stdin.closed:
  1276. self.process.stdin.close()
  1277. try:
  1278. self.process.wait(timeout=10)
  1279. except subprocess.TimeoutExpired:
  1280. self.process.kill()
  1281. self.process.wait()
  1282. if self.process.returncode not in {0, -15}:
  1283. raise RuntimeError(f"runtime exited {self.process.returncode}; stderr: {''.join(self.stderr)}")
  1284. def _read_stdout(self) -> None:
  1285. assert self.process.stdout is not None
  1286. for line in self.process.stdout:
  1287. self.stdout.put(line)
  1288. self.stdout.put(None)
  1289. def _read_stderr(self) -> None:
  1290. assert self.process.stderr is not None
  1291. self.stderr.extend(self.process.stderr)
  1292. PERSISTED_SESSION_FILENAME = re.compile(r"^session(?:\.v([1-9]\d*))?\.jsonl(\.zstd)?$")
  1293. SNAPSHOT_SESSION_FILENAME = re.compile(
  1294. r"^session(?:\.([1-9]\d*))?(?:\.v([1-9]\d*))?\.jsonl$",
  1295. )
  1296. def persisted_session_filename_version(path: Path, compressed: bool = False) -> int | None:
  1297. """Return one canonical persistence basename's generation for the selected encoding."""
  1298. match = PERSISTED_SESSION_FILENAME.fullmatch(path.name)
  1299. if match is None or (match.group(2) is not None) != compressed:
  1300. return None
  1301. return int(match.group(1) or 0)
  1302. def latest_persisted_session_paths(sessions: Path, compressed: bool = False) -> list[Path]:
  1303. """Select the numeric-highest immutable generation in each physical Session directory."""
  1304. pattern = "*.jsonl.zstd" if compressed else "*.jsonl"
  1305. selected: dict[Path, tuple[int, Path]] = {}
  1306. for path in sessions.rglob(pattern):
  1307. version = persisted_session_filename_version(path, compressed)
  1308. if version is None:
  1309. continue
  1310. previous = selected.get(path.parent)
  1311. if previous is None or version > previous[0]:
  1312. selected[path.parent] = (version, path)
  1313. return sorted((entry[1] for entry in selected.values()), key=lambda path: str(path))
  1314. def session_header_version(content: str, label: str) -> int:
  1315. """Read a non-negative physical Session generation from the first JSONL record."""
  1316. first = next((line for line in content.splitlines() if line), None)
  1317. if first is None:
  1318. raise AssertionError(f"{label}: Session log is empty")
  1319. header = json.loads(first)
  1320. version = header.get("version") if isinstance(header, dict) and header.get("type") == "session" else None
  1321. if not isinstance(version, int) or isinstance(version, bool) or version < 0:
  1322. raise AssertionError(f"{label}: Session header has no non-negative integer version")
  1323. return version
  1324. def assert_persisted_session_version(path: Path, content: str) -> int:
  1325. """Require a raw persistence basename and header to name the same generation."""
  1326. filename_version = persisted_session_filename_version(path)
  1327. if filename_version is None:
  1328. raise AssertionError(f"non-canonical Session persistence filename: {path.name}")
  1329. header_version = session_header_version(content, path.name)
  1330. if filename_version != header_version:
  1331. raise AssertionError(
  1332. f"{path.name}: filename declares Session format v{filename_version}, "
  1333. f"header declares v{header_version}",
  1334. )
  1335. return header_version
  1336. def snapshot_session_filename(index: int, version: int) -> str:
  1337. """Render parent/ordinal snapshot role plus an omitted-v0 generation."""
  1338. if index < 0 or version < 0:
  1339. raise ValueError("snapshot Session index and version must be non-negative")
  1340. ordinal = "" if index == 0 else f".{index}"
  1341. generation = "" if version == 0 else f".v{version}"
  1342. return f"session{ordinal}{generation}.jsonl"
  1343. def parse_snapshot_session_filename(name: str) -> tuple[int, int] | None:
  1344. """Parse one canonical parent/ordinal snapshot filename."""
  1345. match = SNAPSHOT_SESSION_FILENAME.fullmatch(name)
  1346. if match is None:
  1347. if name.startswith("session") and name.endswith(".jsonl"):
  1348. raise AssertionError(f"invalid snapshot Session filename: {name}")
  1349. return None
  1350. return int(match.group(1) or 0), int(match.group(2) or 0)
  1351. def selected_snapshot_session_files(directory: Path) -> dict[int, Path]:
  1352. """Select one highest-generation expected file per parent/ordinal role."""
  1353. selected: dict[int, tuple[int, Path]] = {}
  1354. for path in directory.iterdir():
  1355. if not path.is_file():
  1356. continue
  1357. parsed = parse_snapshot_session_filename(path.name)
  1358. if parsed is None:
  1359. continue
  1360. index, version = parsed
  1361. content = path.read_text(encoding="utf-8")
  1362. header_version = session_header_version(content, path.name)
  1363. if header_version != version:
  1364. raise AssertionError(
  1365. f"{path.name}: filename declares Session format v{version}, header declares v{header_version}",
  1366. )
  1367. previous = selected.get(index)
  1368. if previous is None or version > previous[0]:
  1369. selected[index] = (version, path)
  1370. return {index: value[1] for index, value in selected.items()}
  1371. def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
  1372. logs = latest_persisted_session_paths(sessions)
  1373. if len(logs) != 1:
  1374. raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}")
  1375. content = logs[0].read_text()
  1376. assert_persisted_session_version(logs[0], content)
  1377. lines = content.splitlines()
  1378. header = json.loads(lines[0])
  1379. if header.get("cwd") != str(cwd):
  1380. raise AssertionError(f"session header cwd is not absolute/canonical: {header}")
  1381. rendered = "\n".join(lines)
  1382. for expected in expected_texts:
  1383. if expected not in rendered:
  1384. raise AssertionError(f"session log has no {expected!r} response: {logs[0]}")
  1385. def assert_zstd_session_log(sessions: Path) -> None:
  1386. logs = latest_persisted_session_paths(sessions, compressed=True)
  1387. if len(logs) != 1:
  1388. raise AssertionError(f"expected one Zstandard JSONL session log under {sessions}, found {logs}")
  1389. if not logs[0].read_bytes().startswith(bytes.fromhex("28b52ffd")):
  1390. raise AssertionError(f"session log has no Zstandard magic: {logs[0]}")
  1391. def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]:
  1392. """Parse every persisted JSONL session into a map keyed by header id."""
  1393. logs: dict[str, list[dict[str, object]]] = {}
  1394. for path in latest_persisted_session_paths(sessions):
  1395. content = path.read_text(encoding="utf-8")
  1396. assert_persisted_session_version(path, content)
  1397. records = [
  1398. json.loads(line)
  1399. for line in content.splitlines()
  1400. if line
  1401. ]
  1402. if not records or records[0].get("type") != "session":
  1403. raise AssertionError(f"session log has no header: {path}")
  1404. session_id = records[0].get("id")
  1405. if not isinstance(session_id, str):
  1406. raise AssertionError(f"session log header has no string id: {path}")
  1407. if session_id in logs:
  1408. raise AssertionError(f"duplicate persisted session id: {session_id}")
  1409. logs[session_id] = records
  1410. return logs
  1411. def snapshot_child_ids(result: "RunResult") -> list[str]:
  1412. """Return the two child session ids in their SDK notification order."""
  1413. child_ids: list[str] = []
  1414. for notification in result.notifications:
  1415. if notification.method != "subagent.started":
  1416. continue
  1417. payload = notification.payload
  1418. if payload.get("parentSessionId") != SNAPSHOT_SESSION_ID:
  1419. continue
  1420. child_id = payload.get("childSessionId")
  1421. if isinstance(child_id, str) and child_id not in child_ids:
  1422. child_ids.append(child_id)
  1423. if len(child_ids) != 2:
  1424. raise AssertionError(f"advanced snapshot expected two child session ids: {child_ids}")
  1425. return child_ids
  1426. def build_minimal_snapshot_files(
  1427. requests: list[dict[str, object]],
  1428. cwd: Path,
  1429. ) -> dict[str, str]:
  1430. """Render the minimal composition's model-visible surface as expected output.
  1431. Every assembled system prompt, advertised tool schema, and system or user message is
  1432. kept verbatim: they carry what the deployment actually shows the model, so a plugin
  1433. that contributes an unintended system section or user message cannot pass unnoticed.
  1434. Assistant and tool payloads keep only their call identity because their text differs
  1435. across the platforms this expected output must replay on. The shipped profile omits
  1436. dynamic runtime context, so every message it emits is compared.
  1437. """
  1438. snapshot = []
  1439. for body in requests:
  1440. messages = body.get("messages")
  1441. if not isinstance(messages, list):
  1442. raise AssertionError(f"minimal model request has no messages: {body}")
  1443. snapshot.append({
  1444. "tools": minimal_snapshot_text(body.get("tools"), cwd),
  1445. "messages": [
  1446. minimal_snapshot_message(message, cwd)
  1447. for message in messages
  1448. ],
  1449. })
  1450. return {"model-visible.json": json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"}
  1451. def minimal_snapshot_message(message: object, cwd: Path) -> dict[str, object]:
  1452. """Reduce one model-visible message to its stable, behavior-carrying parts."""
  1453. if not isinstance(message, dict):
  1454. raise AssertionError(f"minimal model request has an invalid message: {message}")
  1455. role = message.get("role")
  1456. if role in ("system", "user"):
  1457. return {"role": role, "text": minimal_snapshot_text(message_text(message.get("content")), cwd)}
  1458. if role == "assistant":
  1459. calls = message.get("tool_calls")
  1460. if not isinstance(calls, list):
  1461. raise AssertionError(f"minimal assistant message has no tool calls: {message}")
  1462. return {
  1463. "role": role,
  1464. "toolCalls": [
  1465. {"id": call.get("id"), "name": (call.get("function") or {}).get("name")}
  1466. for call in calls
  1467. if isinstance(call, dict)
  1468. ],
  1469. }
  1470. if role == "tool":
  1471. return {"role": role, "toolCallId": message.get("tool_call_id"), "text": "{{tool-result}}"}
  1472. raise AssertionError(f"minimal model request has an unexpected message role: {message}")
  1473. def minimal_snapshot_text(value: object, cwd: Path) -> object:
  1474. """Replace the scenario's temporary working directory everywhere it appears."""
  1475. if isinstance(value, str):
  1476. return value.replace(str(cwd), "{{cwd}}")
  1477. if isinstance(value, list):
  1478. return [minimal_snapshot_text(item, cwd) for item in value]
  1479. if isinstance(value, dict):
  1480. return {key: minimal_snapshot_text(item, cwd) for key, item in value.items()}
  1481. return value
  1482. def build_snapshot_files(
  1483. result: "RunResult",
  1484. logs: dict[str, list[dict[str, object]]],
  1485. child_ids: list[str],
  1486. cwd: Path,
  1487. ) -> dict[str, str]:
  1488. """Render the SDK result and three persisted logs into stable expected outputs."""
  1489. replacements = [(str(cwd), "{{cwd}}"), (SNAPSHOT_SESSION_ID, "{{parent}}")]
  1490. replacements.append((snapshot_workflow_run_id(result), "{{workflow-run}}"))
  1491. for index, child_id in enumerate(child_ids, start=1):
  1492. replacements.append((child_id, f"{{{{child-{index}}}}}"))
  1493. agent_id = snapshot_agent_id(result, child_id)
  1494. replacements.append((agent_id, f"{{{{agent-{index}}}}}"))
  1495. replacements.sort(key=lambda pair: len(pair[0]), reverse=True)
  1496. result_value = {
  1497. "session_id": result.session_id,
  1498. "final_response": result.final_response,
  1499. "events": result.events,
  1500. "notifications": [
  1501. {"method": notification.method, "payload": notification.payload}
  1502. for notification in result.notifications
  1503. ],
  1504. }
  1505. normalized_result = normalize_snapshot_value(result_value, replacements)
  1506. parent_records = project_session_snapshot([
  1507. normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]
  1508. ])
  1509. files = {
  1510. "result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
  1511. snapshot_session_filename(
  1512. 0, session_header_version(render_jsonl(parent_records), "advanced parent"),
  1513. ): render_jsonl(parent_records),
  1514. }
  1515. for index, child_id in enumerate(child_ids, start=1):
  1516. child_records = project_session_snapshot([
  1517. normalize_snapshot_value(record, replacements) for record in logs[child_id]
  1518. ])
  1519. child_content = render_jsonl(child_records)
  1520. files[snapshot_session_filename(
  1521. index, session_header_version(child_content, f"advanced child {index}"),
  1522. )] = child_content
  1523. return files
  1524. def build_restart_snapshot_files(
  1525. first: "RunResult",
  1526. second: "RunResult",
  1527. requests: list[dict[str, object]],
  1528. logs: dict[str, list[dict[str, object]]],
  1529. cwd: Path,
  1530. sessions: Path,
  1531. *,
  1532. compare_released_generations: bool,
  1533. ) -> dict[str, str]:
  1534. """Render two SDK processes, isolated model histories, and durable logs."""
  1535. replacements = [
  1536. (str(sessions), "{{sessions}}"),
  1537. (str(cwd), "{{cwd}}"),
  1538. (RESTART_FIRST_SESSION_ID, "{{session-1}}"),
  1539. (RESTART_SECOND_SESSION_ID, "{{session-2}}"),
  1540. ]
  1541. result_value = [
  1542. {
  1543. "session_id": result.session_id,
  1544. "final_response": result.final_response,
  1545. "finish_reason": result.finish_reason,
  1546. "eventTypes": [
  1547. event.get("type")
  1548. for source in result.events
  1549. for event in (
  1550. expand_snapshot_assistant_event(source)
  1551. if compare_released_generations else [source]
  1552. )
  1553. if isinstance(event, dict)
  1554. ],
  1555. "notificationMethods": [
  1556. row.get("method")
  1557. for notification in result.notifications
  1558. for row in (
  1559. expand_snapshot_assistant_event({
  1560. "method": notification.method,
  1561. "payload": notification.payload,
  1562. })
  1563. if compare_released_generations else [{"method": notification.method}]
  1564. )
  1565. if isinstance(row, dict)
  1566. ],
  1567. }
  1568. for result in (first, second)
  1569. ]
  1570. request_value = [
  1571. {
  1572. "model": request.get("model"),
  1573. "messages": restart_request_messages(request),
  1574. "toolNames": sorted(advertised_tool_names(request)),
  1575. }
  1576. for request in requests
  1577. ]
  1578. first_records = project_session_snapshot([
  1579. normalize_snapshot_value(record, replacements) for record in logs[RESTART_FIRST_SESSION_ID]
  1580. ])
  1581. second_records = project_session_snapshot([
  1582. normalize_snapshot_value(record, replacements) for record in logs[RESTART_SECOND_SESSION_ID]
  1583. ])
  1584. first_content = render_jsonl(first_records)
  1585. second_content = render_jsonl(second_records)
  1586. return {
  1587. "result.json": json.dumps(
  1588. normalize_snapshot_value(result_value, replacements), indent=2, ensure_ascii=False,
  1589. ) + "\n",
  1590. "requests.json": json.dumps(
  1591. normalize_snapshot_value(request_value, replacements), indent=2, ensure_ascii=False,
  1592. ) + "\n",
  1593. snapshot_session_filename(
  1594. 1, session_header_version(first_content, "restart Session 1"),
  1595. ): first_content,
  1596. snapshot_session_filename(
  1597. 2, session_header_version(second_content, "restart Session 2"),
  1598. ): second_content,
  1599. }
  1600. def restart_request_messages(request: dict[str, object]) -> list[object]:
  1601. """Project model history while tokenizing composition-owned system prose."""
  1602. messages = request.get("messages")
  1603. if not isinstance(messages, list):
  1604. raise AssertionError(f"restart snapshot request has no messages: {request}")
  1605. return [
  1606. {"role": "system", "content": "{{system}}"}
  1607. if isinstance(message, dict) and message.get("role") == "system"
  1608. else message
  1609. for message in messages
  1610. ]
  1611. def snapshot_workflow_run_id(result: "RunResult") -> str:
  1612. """Return the one workflow run id emitted by the advanced scenario."""
  1613. run_ids: set[str] = set()
  1614. for event in result.events:
  1615. event_type = event.get("type")
  1616. data = event.get("data")
  1617. if not isinstance(event_type, str) or not event_type.startswith("tool-workflow/"):
  1618. continue
  1619. if isinstance(data, dict) and isinstance(data.get("runId"), str):
  1620. run_ids.add(data["runId"])
  1621. if len(run_ids) != 1:
  1622. raise AssertionError(f"advanced snapshot expected one workflow run id: {sorted(run_ids)}")
  1623. return next(iter(run_ids))
  1624. def snapshot_agent_id(result: "RunResult", child_id: str) -> str:
  1625. """Find the successful subagent id paired with one child session."""
  1626. for notification in result.notifications:
  1627. if notification.method != "subagent.finished":
  1628. continue
  1629. payload = notification.payload
  1630. if payload.get("childSessionId") != child_id:
  1631. continue
  1632. if payload.get("provider") != "spawn" or payload.get("status") != "ok":
  1633. raise AssertionError(f"advanced child did not finish successfully: {payload}")
  1634. agent_id = payload.get("agentId")
  1635. if isinstance(agent_id, str):
  1636. return agent_id
  1637. raise AssertionError(f"advanced snapshot has no finished agent for child {child_id}")
  1638. def normalize_snapshot_value(
  1639. value: object,
  1640. replacements: list[tuple[str, str]],
  1641. ) -> object:
  1642. """Scrub volatile values and bulky request headers without losing behavior."""
  1643. if isinstance(value, str):
  1644. normalized = value
  1645. for actual, token in replacements:
  1646. normalized = normalized.replace(actual, token)
  1647. return normalized
  1648. if isinstance(value, list):
  1649. return [normalize_snapshot_value(item, replacements) for item in value]
  1650. if not isinstance(value, dict):
  1651. return value
  1652. normalized = {
  1653. key: normalize_snapshot_value(item, replacements)
  1654. for key, item in value.items()
  1655. }
  1656. if normalized.get("type") == "session" and "createdAt" in normalized:
  1657. normalized["createdAt"] = 0
  1658. if "seq" in normalized and "time" in normalized:
  1659. normalized["time"] = 0
  1660. if normalized.get("type") in ("assistant/message", "assistant/attempt"):
  1661. data = normalized.get("data")
  1662. stream = data.get("stream") if isinstance(data, dict) else None
  1663. if isinstance(stream, list):
  1664. for member in stream:
  1665. if not isinstance(member, dict):
  1666. continue
  1667. if isinstance(member.get("time"), (int, float)):
  1668. member["time"] = 0
  1669. if isinstance(member.get("time0"), (int, float)):
  1670. member["time0"] = 0
  1671. dt = member.get("dt")
  1672. if isinstance(dt, list):
  1673. member["dt"] = [0] * len(dt)
  1674. if isinstance(normalized.get("id"), str) and normalized.get("role") in ("assistant", "user"):
  1675. normalized["id"] = "{{messageId}}"
  1676. scrub_snapshot_header(normalized)
  1677. return normalized
  1678. def scrub_snapshot_header(value: dict[object, object]) -> None:
  1679. """Tokenize full request-header bulk while retaining tool names."""
  1680. data = value.get("data")
  1681. if not isinstance(data, dict):
  1682. return
  1683. if value.get("type") == "request/header":
  1684. header = data.get("header")
  1685. if not isinstance(header, dict):
  1686. return
  1687. if "system" in header:
  1688. header["system"] = "{{system}}"
  1689. tools = header.get("tools")
  1690. if isinstance(tools, list):
  1691. header["tools"] = [
  1692. tool.get("name") if isinstance(tool, dict) else "{{tools}}"
  1693. for tool in tools
  1694. ]
  1695. def render_jsonl(records: list[object]) -> str:
  1696. """Render parsed JSON values as compact, newline-terminated JSONL."""
  1697. return "".join(
  1698. json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
  1699. for record in records
  1700. )
  1701. def project_session_snapshot(records: list[dict[str, object]]) -> list[dict[str, object]]:
  1702. """Omit storage sequence/time envelopes from snapshot body records."""
  1703. projected = [dict(record) for record in records]
  1704. for record in projected[1:]:
  1705. for key in ("seq", "time", "seq0", "time0"):
  1706. record.pop(key, None)
  1707. return projected
  1708. SESSION_FORMAT_PROVENANCE = "{{sessionFormatVersion}}"
  1709. def expand_snapshot_stream_member(member: object) -> list[dict[str, object]]:
  1710. """Expand one compact Assistant stream member into logical provider chunks."""
  1711. if not isinstance(member, dict):
  1712. raise AssertionError(f"snapshot Assistant stream member is not an object: {member!r}")
  1713. member_type = member.get("type")
  1714. if member_type == "chunk":
  1715. chunk = member.get("chunk")
  1716. if not isinstance(chunk, dict):
  1717. raise AssertionError(f"snapshot Assistant chunk member has no chunk: {member!r}")
  1718. return [chunk]
  1719. packed_kinds = {
  1720. "text-chunks": ("texts", "text-delta", "text"),
  1721. "reasoning-chunks": ("texts", "reasoning-delta", "text"),
  1722. "tool-call-chunks": ("args", "tool-call-delta", "argumentsDelta"),
  1723. }
  1724. packed = packed_kinds.get(member_type)
  1725. if packed is None:
  1726. raise AssertionError(f"snapshot Assistant stream has unknown member type: {member_type!r}")
  1727. values_key, chunk_type, value_key = packed
  1728. values = member.get(values_key)
  1729. if not isinstance(values, list):
  1730. raise AssertionError(f"snapshot Assistant stream member has no {values_key}: {member!r}")
  1731. shared = {
  1732. key: member[key]
  1733. for key in ("index", "id", "name")
  1734. if key in member
  1735. }
  1736. return [
  1737. {"type": chunk_type, **shared, value_key: value}
  1738. for value in values
  1739. ]
  1740. def expand_snapshot_assistant_event(value: object) -> list[object]:
  1741. """Expand one direct or SDK-wrapped v2 settlement for generation-neutral comparison."""
  1742. if not isinstance(value, dict):
  1743. return [value]
  1744. event = value
  1745. wrapper_key: str | None = None
  1746. wrapper: dict[str, object] | None = None
  1747. if value.get("method") == "session.event":
  1748. for candidate in ("payload", "params"):
  1749. container = value.get(candidate)
  1750. nested = container.get("event") if isinstance(container, dict) else None
  1751. if isinstance(nested, dict):
  1752. event = nested
  1753. wrapper_key = candidate
  1754. wrapper = container
  1755. break
  1756. if event.get("type") not in ("assistant/message", "assistant/attempt"):
  1757. return [value]
  1758. data = event.get("data")
  1759. stream = data.get("stream") if isinstance(data, dict) else None
  1760. if not isinstance(stream, list):
  1761. return [value]
  1762. def wrap(expanded: dict[str, object]) -> object:
  1763. if wrapper_key is None or wrapper is None:
  1764. return expanded
  1765. return {**value, wrapper_key: {**wrapper, "event": expanded}}
  1766. common = {
  1767. key: data[key]
  1768. for key in ("turn", "step")
  1769. if key in data
  1770. }
  1771. expanded = [
  1772. wrap({
  1773. "type": "assistant/chunk",
  1774. "data": {**common, "chunk": chunk},
  1775. })
  1776. for member in stream
  1777. for chunk in expand_snapshot_stream_member(member)
  1778. ]
  1779. if event.get("type") == "assistant/message":
  1780. expanded.append(wrap({
  1781. **event,
  1782. "data": {key: item for key, item in data.items() if key != "stream"},
  1783. }))
  1784. return expanded
  1785. def normalize_session_format_comparison(
  1786. value: object,
  1787. source_session_version: int | None = None,
  1788. ) -> object:
  1789. """Canonicalize only generation provenance that differs across immutable Session files."""
  1790. if isinstance(value, list):
  1791. return [
  1792. normalize_session_format_comparison(expanded, source_session_version)
  1793. for item in value
  1794. for expanded in expand_snapshot_assistant_event(item)
  1795. ]
  1796. if not isinstance(value, dict):
  1797. return value
  1798. normalized = {
  1799. key: normalize_session_format_comparison(item, source_session_version)
  1800. for key, item in value.items()
  1801. }
  1802. if normalized.get("type") == "session" and "version" in normalized:
  1803. normalized["version"] = SESSION_FORMAT_PROVENANCE
  1804. normalized.setdefault("isSeeded", False)
  1805. ordered_header = {
  1806. key: normalized[key]
  1807. for key in ("type", "version", "id", "createdAt", "cwd", "isSeeded", "delegationDepth")
  1808. if key in normalized
  1809. }
  1810. normalized = {
  1811. **ordered_header,
  1812. **{key: item for key, item in normalized.items() if key not in ordered_header},
  1813. }
  1814. if isinstance(normalized.get("type"), str) and "data" in normalized:
  1815. normalized.pop("seq", None)
  1816. normalized.pop("time", None)
  1817. if source_session_version == 1 and normalized.get("type") == "assistant/message":
  1818. normalized.pop("sourceEventSeqs", None)
  1819. if normalized.get("type") == "session-log-deepseek/delivery-accepted":
  1820. data = normalized.get("data")
  1821. if isinstance(data, dict):
  1822. data.pop("throughSeq", None)
  1823. data.pop("sessionFormatVersion", None)
  1824. data["sessionFormatVersion"] = SESSION_FORMAT_PROVENANCE
  1825. if normalized.get("kind") == "session-reference":
  1826. references = normalized.get("references")
  1827. if isinstance(references, list):
  1828. for reference in references:
  1829. if isinstance(reference, dict):
  1830. reference.pop("capturedFormatVersion", None)
  1831. reference["capturedFormatVersion"] = SESSION_FORMAT_PROVENANCE
  1832. return normalized
  1833. def normalize_snapshot_comparison_text(name: str, content: str) -> str:
  1834. """Normalize Session generation provenance only while comparing committed expected outputs."""
  1835. if name.startswith("session") and name.endswith(".jsonl"):
  1836. parsed = [json.loads(line) for line in content.splitlines() if line]
  1837. header = parsed[0] if parsed else None
  1838. source_version = header.get("version") if isinstance(header, dict) else None
  1839. if not isinstance(source_version, int):
  1840. raise AssertionError(f"{name}: snapshot Session header has no integer format version")
  1841. records = [
  1842. normalize_session_format_comparison(expanded, source_version)
  1843. for record in parsed
  1844. for expanded in expand_snapshot_assistant_event(record)
  1845. ]
  1846. return render_jsonl(records)
  1847. if name.endswith(".json"):
  1848. return json.dumps(
  1849. normalize_session_format_comparison(json.loads(content)),
  1850. indent=2,
  1851. ensure_ascii=False,
  1852. ) + "\n"
  1853. return content
  1854. def compare_snapshot_files(
  1855. files: dict[str, str],
  1856. update: bool,
  1857. directory: Path,
  1858. filenames: tuple[str, ...],
  1859. ) -> None:
  1860. """Write or exactly compare one scenario's expected snapshot files."""
  1861. scenario = directory.name
  1862. if tuple(files) != filenames:
  1863. raise AssertionError(f"{scenario} snapshot builder produced {tuple(files)}, expected {filenames}")
  1864. if update:
  1865. directory.mkdir(parents=True, exist_ok=True)
  1866. for name, content in files.items():
  1867. (directory / name).write_text(content, encoding="utf-8", newline="\n")
  1868. print(f"smoke-python-runtime: updated snapshots in {directory}")
  1869. existing = [path for path in directory.iterdir() if path.is_file()] if directory.is_dir() else []
  1870. expected_non_session = {
  1871. name for name in filenames if parse_snapshot_session_filename(name) is None
  1872. }
  1873. existing_non_session = {
  1874. path.name for path in existing if parse_snapshot_session_filename(path.name) is None
  1875. }
  1876. if existing_non_session != expected_non_session:
  1877. raise AssertionError(
  1878. f"{scenario} snapshot files differ: "
  1879. f"missing={sorted(expected_non_session - existing_non_session)}, "
  1880. f"unexpected={sorted(existing_non_session - expected_non_session)}"
  1881. )
  1882. selected_expected = selected_snapshot_session_files(directory)
  1883. actual_sessions: dict[int, tuple[str, str]] = {}
  1884. for name, content in files.items():
  1885. parsed = parse_snapshot_session_filename(name)
  1886. if parsed is None:
  1887. continue
  1888. index, filename_version = parsed
  1889. header_version = session_header_version(content, name)
  1890. if filename_version != header_version:
  1891. raise AssertionError(
  1892. f"{name}: filename declares Session format v{filename_version}, "
  1893. f"header declares v{header_version}",
  1894. )
  1895. if index in actual_sessions:
  1896. raise AssertionError(f"{scenario} snapshot builder produced duplicate Session role {index}")
  1897. actual_sessions[index] = (name, content)
  1898. if set(selected_expected) != set(actual_sessions):
  1899. raise AssertionError(
  1900. f"{scenario} snapshot Session roles differ: "
  1901. f"expected={sorted(selected_expected)}, actual={sorted(actual_sessions)}",
  1902. )
  1903. for name, actual in files.items():
  1904. parsed = parse_snapshot_session_filename(name)
  1905. expected_path = directory / name if parsed is None else selected_expected[parsed[0]]
  1906. expected_text = expected_path.read_text(encoding="utf-8")
  1907. compared_actual = normalize_snapshot_comparison_text(name, actual)
  1908. compared_expected = normalize_snapshot_comparison_text(expected_path.name, expected_text)
  1909. if compared_actual == compared_expected:
  1910. continue
  1911. diff = "".join(difflib.unified_diff(
  1912. compared_expected.splitlines(keepends=True),
  1913. compared_actual.splitlines(keepends=True),
  1914. fromfile=f"expected/{expected_path.name}",
  1915. tofile=f"actual/{name}",
  1916. ))
  1917. raise AssertionError(
  1918. f"{scenario} executable snapshot mismatch in {name}; "
  1919. "rerun with --update-snapshots after reviewing the behavior\n"
  1920. f"{diff}"
  1921. )
  1922. if __name__ == "__main__":
  1923. main()