test_smoke_model.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. from __future__ import annotations
  2. import json
  3. import runpy
  4. import subprocess
  5. from pathlib import Path
  6. from types import SimpleNamespace
  7. import pytest
  8. from deepseek_harness import RunResult
  9. ROOT = Path(__file__).resolve().parents[3]
  10. SMOKE = runpy.run_path(ROOT / "scripts" / "smoke-python-runtime.py")
  11. def live_result(**overrides: object) -> RunResult:
  12. values = {
  13. "session_id": "installed-wheel-live-api",
  14. "final_response": SMOKE["LIVE_API_SENTINEL"],
  15. "finish_reason": "completed",
  16. "events": [{"type": "tool/call", "data": {"name": "unrelated_tool"}}],
  17. "notifications": [],
  18. }
  19. values.update(overrides)
  20. return RunResult(**values)
  21. @pytest.fixture
  22. def live_smoke(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
  23. import deepseek_harness
  24. state = SimpleNamespace(
  25. prompts=[], session_ids=[], challenges=[], checked_logs=[], closed=False,
  26. create_bytes=SMOKE["LIVE_API_SENTINEL"].encode("utf-8"),
  27. create_result=live_result(), verify_result=live_result(), receipt_mode="copy",
  28. )
  29. globals_ = SMOKE["smoke_sdk_live"].__globals__
  30. token_hex = globals_["secrets"].token_hex
  31. def fresh_challenge(size: int) -> str:
  32. assert len(state.prompts) == 1
  33. value = token_hex(size)
  34. state.challenges.append(value)
  35. return value
  36. class ScriptedHarness:
  37. def __init__(self, **kwargs: object) -> None:
  38. state.root = Path(kwargs["cwd"])
  39. assert "toolChoice" not in kwargs
  40. def __enter__(self) -> ScriptedHarness:
  41. return self
  42. def __exit__(self, *args: object) -> None:
  43. state.closed = True
  44. def run(self, prompt: str, *, session_id: str) -> RunResult:
  45. state.prompts.append(prompt)
  46. state.session_ids.append(session_id)
  47. if len(state.prompts) == 1:
  48. state.marker = Path(prompt.splitlines()[-1])
  49. assert state.marker.parent == state.root
  50. if state.create_bytes is not None:
  51. state.marker.write_bytes(state.create_bytes)
  52. return state.create_result
  53. assert len(state.prompts) == 2
  54. assert len(state.challenges) == 1
  55. challenge = state.challenges[0]
  56. assert all(challenge not in sent for sent in state.prompts)
  57. assert str(state.marker) not in prompt
  58. assert "previous turn" in prompt and "changed externally" in prompt
  59. assert state.marker.read_bytes() == challenge.encode("ascii")
  60. receipt = Path(prompt.splitlines()[-1])
  61. assert receipt != state.marker and not receipt.exists()
  62. if state.receipt_mode == "copy":
  63. receipt.write_bytes(state.marker.read_bytes())
  64. elif state.receipt_mode == "stale":
  65. receipt.write_bytes(state.create_bytes)
  66. elif state.receipt_mode == "wrong":
  67. receipt.write_bytes(b"wrong")
  68. elif state.receipt_mode == "newline":
  69. receipt.write_bytes(state.marker.read_bytes() + b"\n")
  70. elif state.receipt_mode == "changed-source":
  71. receipt.write_bytes(state.marker.read_bytes())
  72. state.marker.write_bytes(b"changed")
  73. elif state.receipt_mode != "missing":
  74. raise AssertionError(state.receipt_mode)
  75. return state.verify_result
  76. monkeypatch.setenv("DEEPSEEK_API_KEY", "unit-test-key")
  77. monkeypatch.setenv("DEEPSEEK_BASE_URL", "https://api.invalid")
  78. monkeypatch.setattr(deepseek_harness, "DeepSeekHarness", ScriptedHarness)
  79. monkeypatch.setattr(globals_["secrets"], "token_hex", fresh_challenge)
  80. monkeypatch.setitem(globals_, "assert_zstd_session_log", state.checked_logs.append)
  81. return state
  82. def test_live_smoke_requires_fresh_external_content(live_smoke: SimpleNamespace) -> None:
  83. SMOKE["smoke_sdk_live"]()
  84. assert len(live_smoke.prompts) == 2
  85. assert live_smoke.session_ids == ["installed-wheel-live-api"] * 2
  86. assert len(live_smoke.checked_logs) == 1
  87. assert live_smoke.closed and not live_smoke.root.exists()
  88. @pytest.mark.parametrize("label", ["create", "verify"])
  89. @pytest.mark.parametrize(("overrides", "message"), [
  90. ({"finish_reason": "error"}, "turn ended with 'error'"),
  91. ({"events": []}, "turn made no model-requested tool call"),
  92. ({"final_response": "PYTHON_SDK_LIVE_OK extra"}, "turn returned"),
  93. ])
  94. def test_live_smoke_rejects_invalid_turn_before_continuing(
  95. live_smoke: SimpleNamespace, label: str, overrides: dict[str, object], message: str,
  96. ) -> None:
  97. setattr(live_smoke, f"{label}_result", live_result(**overrides))
  98. with pytest.raises(AssertionError, match=f"{label} {message}"):
  99. SMOKE["smoke_sdk_live"]()
  100. assert len(live_smoke.prompts) == (1 if label == "create" else 2)
  101. assert not live_smoke.checked_logs
  102. assert live_smoke.closed
  103. if label == "create":
  104. assert not live_smoke.challenges
  105. @pytest.mark.parametrize("content", [None, b"wrong", b"PYTHON_SDK_LIVE_OK\n"])
  106. def test_live_smoke_rejects_bad_create_before_host_overwrite(
  107. live_smoke: SimpleNamespace, content: bytes | None,
  108. ) -> None:
  109. live_smoke.create_bytes = content
  110. with pytest.raises(AssertionError, match="create turn (did not create|wrote unexpected bytes)"):
  111. SMOKE["smoke_sdk_live"]()
  112. assert len(live_smoke.prompts) == 1
  113. assert not live_smoke.challenges and not live_smoke.checked_logs
  114. assert live_smoke.closed
  115. @pytest.mark.parametrize(("mode", "message"), [
  116. ("missing", "did not create receipt"),
  117. ("stale", "wrote unexpected bytes to receipt"),
  118. ("wrong", "wrote unexpected bytes to receipt"),
  119. ("newline", "wrote unexpected bytes to receipt"),
  120. ("changed-source", "changed source file"),
  121. ])
  122. def test_live_smoke_rejects_unrelated_tool_without_exact_receipt(
  123. live_smoke: SimpleNamespace, mode: str, message: str,
  124. ) -> None:
  125. live_smoke.receipt_mode = mode
  126. with pytest.raises(AssertionError, match=f"verify turn {message}"):
  127. SMOKE["smoke_sdk_live"]()
  128. assert len(live_smoke.prompts) == 2
  129. assert not live_smoke.checked_logs
  130. assert live_smoke.closed
  131. @pytest.mark.parametrize(
  132. ("prompt_name", "expected"),
  133. [
  134. ("SNAPSHOT_DIRECT_CHILD_PROMPT", "DIRECT_CHILD_OK"),
  135. ("SNAPSHOT_WORKFLOW_CHILD_PROMPT", "WORKFLOW_CHILD_OK"),
  136. ],
  137. )
  138. def test_child_prompt_precedes_runtime_context(prompt_name: str, expected: str) -> None:
  139. chunks = SMOKE["completion_chunks"]({
  140. "messages": [
  141. {"role": "user", "content": SMOKE[prompt_name]},
  142. {"role": "user", "content": "Current runtime context"},
  143. ],
  144. })
  145. assert any(
  146. choice.get("delta", {}).get("content") == expected
  147. for chunk in chunks
  148. for choice in chunk.get("choices", [])
  149. )
  150. def test_mcp_smoke_requests_the_discovered_tool() -> None:
  151. chunks = SMOKE["completion_chunks"]({
  152. "messages": [{"role": "user", "content": SMOKE["MCP_PROMPT"]}],
  153. "tools": [{"type": "function", "function": {"name": "mcp__fixture__add"}}],
  154. })
  155. calls = [
  156. call
  157. for chunk in chunks
  158. for choice in chunk.get("choices", [])
  159. for call in choice.get("delta", {}).get("tool_calls", [])
  160. ]
  161. assert calls[0]["function"] == {
  162. "name": "mcp__fixture__add",
  163. "arguments": '{"a": 19, "b": 23}',
  164. }
  165. def test_mcp_smoke_accepts_the_external_server_result() -> None:
  166. chunks = SMOKE["completion_chunks"]({
  167. "messages": [
  168. {"role": "user", "content": SMOKE["MCP_PROMPT"]},
  169. {
  170. "role": "assistant",
  171. "tool_calls": [{
  172. "id": "mcp-add",
  173. "type": "function",
  174. "function": {"name": "mcp__fixture__add", "arguments": '{}'},
  175. }],
  176. },
  177. {"role": "tool", "tool_call_id": "mcp-add", "content": "42"},
  178. ],
  179. })
  180. assert any(
  181. choice.get("delta", {}).get("content") == SMOKE["MCP_TEXT"]
  182. for chunk in chunks
  183. for choice in chunk.get("choices", [])
  184. )
  185. def test_snapshot_comparison_preserves_opaque_generation_provenance() -> None:
  186. normalize = SMOKE["normalize_session_format_comparison"]
  187. expected = {
  188. "header": {"type": "session", "version": 0, "otherVersion": 7},
  189. "accepted": {
  190. "type": "session-log-deepseek/delivery-accepted",
  191. "data": {"sessionId": "s", "throughSeq": 4},
  192. },
  193. "source": {
  194. "kind": "session-reference",
  195. "references": [{"sessionId": "other", "capturedThroughSeq": 8}],
  196. },
  197. }
  198. actual = {
  199. "header": {"type": "session", "version": 1, "otherVersion": 7},
  200. "accepted": {
  201. "type": "session-log-deepseek/delivery-accepted",
  202. "data": {"sessionId": "s", "sessionFormatVersion": 1, "throughSeq": 4},
  203. },
  204. "source": {
  205. "kind": "session-reference",
  206. "references": [{
  207. "sessionId": "other",
  208. "capturedFormatVersion": 1,
  209. "capturedThroughSeq": 8,
  210. }],
  211. },
  212. }
  213. assert normalize(expected) != normalize(actual)
  214. assert normalize(expected)["header"] == normalize(actual)["header"]
  215. assert normalize(expected)["header"]["otherVersion"] == 7
  216. assert normalize(actual)["accepted"] == actual["accepted"]
  217. assert normalize(actual)["source"] == actual["source"]
  218. def test_snapshot_value_scrubs_system_nodes_without_erasing_header_fields() -> None:
  219. normalize = SMOKE["normalize_snapshot_value"]
  220. system = {
  221. "type": "system/message",
  222. "data": {"message": {"role": "system", "content": [{"type": "text", "text": "prompt"}]}},
  223. }
  224. header = {"type": "request/header", "data": {"header": {"system": "unexpected"}}}
  225. assert normalize(system, [])["data"]["message"]["content"] == [{"type": "text", "text": "{{system}}"}]
  226. assert normalize(header, []) == header
  227. empty = {"type": "system/message", "data": {"message": {"role": "system", "content": []}}}
  228. assert normalize(empty, []) == empty
  229. def test_snapshot_value_normalizes_embedded_assistant_stream_timing() -> None:
  230. normalize = SMOKE["normalize_snapshot_value"]
  231. event = {
  232. "type": "assistant/message",
  233. "seq": 4,
  234. "time": 100,
  235. "data": {
  236. "stream": [
  237. {"type": "chunk", "time": 101, "chunk": {"type": "finish"}},
  238. {"type": "text-chunks", "time0": 102, "dt": [1, 2], "texts": ["a", "b", "c"]},
  239. ],
  240. },
  241. }
  242. normalized = normalize(event, [])
  243. assert normalized["time"] == 0
  244. assert normalized["data"]["stream"] == [
  245. {"type": "chunk", "time": 0, "chunk": {"type": "finish"}},
  246. {"type": "text-chunks", "time0": 0, "dt": [0, 0], "texts": ["a", "b", "c"]},
  247. ]
  248. def test_snapshot_comparison_expands_embedded_assistant_streams() -> None:
  249. normalize = SMOKE["normalize_session_format_comparison"]
  250. expected = [
  251. {
  252. "type": "assistant/chunk",
  253. "seq": 4,
  254. "time": 0,
  255. "data": {"turn": 1, "step": 1, "chunk": {
  256. "type": "text-delta", "index": 0, "text": "done",
  257. }},
  258. },
  259. {
  260. "type": "assistant/message",
  261. "seq": 5,
  262. "time": 0,
  263. "data": {"turn": 1, "step": 1, "message": {"role": "assistant"}},
  264. "sourceEventSeqs": [4],
  265. "surfaceOp": "append",
  266. },
  267. ]
  268. actual = [{
  269. "type": "assistant/message",
  270. "seq": 4,
  271. "time": 0,
  272. "data": {
  273. "turn": 1,
  274. "step": 1,
  275. "message": {"role": "assistant"},
  276. "stream": [{
  277. "type": "text-chunks", "time0": 0, "index": 0, "dt": [], "texts": ["done"],
  278. }],
  279. },
  280. "surfaceOp": "append",
  281. }]
  282. assert normalize(actual, 2) == normalize(expected, 1)
  283. tool_result = {
  284. "type": "tool/result",
  285. "data": {"turn": 1, "step": 1},
  286. "sourceEventSeqs": [4],
  287. }
  288. assert normalize(tool_result, 1)["sourceEventSeqs"] == [4]
  289. assert normalize(tool_result, 2)["sourceEventSeqs"] == [4]
  290. def test_snapshot_stream_expands_reasoning_and_tool_call_records() -> None:
  291. expand = SMOKE["expand_snapshot_stream_member"]
  292. assert expand({
  293. "type": "reasoning-chunks", "time0": 0, "index": 1,
  294. "dt": [], "texts": ["think"],
  295. }) == [{"type": "reasoning-delta", "index": 1, "text": "think"}]
  296. assert expand({
  297. "type": "tool-call-chunks", "time0": 0, "index": 2,
  298. "id": "call-1", "name": "read", "dt": [1], "args": ["{", "}"],
  299. }) == [
  300. {"type": "tool-call-delta", "index": 2, "id": "call-1", "name": "read", "argumentsDelta": "{"},
  301. {"type": "tool-call-delta", "index": 2, "id": "call-1", "name": "read", "argumentsDelta": "}"},
  302. ]
  303. def test_snapshot_file_builder_order_is_checked_outside_update_mode(tmp_path: Path) -> None:
  304. compare = SMOKE["compare_snapshot_files"]
  305. with pytest.raises(AssertionError, match="snapshot builder produced"):
  306. compare({}, False, tmp_path, ("result.json",))
  307. def test_snapshot_comparison_expands_sdk_wrapped_attempts() -> None:
  308. normalize = SMOKE["normalize_session_format_comparison"]
  309. actual = [{
  310. "method": "session.event",
  311. "payload": {
  312. "sessionId": "s",
  313. "event": {
  314. "type": "assistant/attempt",
  315. "seq": 7,
  316. "time": 0,
  317. "data": {
  318. "turn": 1,
  319. "step": 1,
  320. "stream": [{"type": "chunk", "time": 0, "chunk": {"type": "finish"}}],
  321. },
  322. },
  323. },
  324. }]
  325. assert normalize(actual) == [{
  326. "method": "session.event",
  327. "payload": {
  328. "sessionId": "s",
  329. "event": {
  330. "type": "assistant/chunk",
  331. "data": {"turn": 1, "step": 1, "chunk": {"type": "finish"}},
  332. },
  333. },
  334. }]
  335. def test_snapshot_generation_names_select_highest_role_without_double_counting(
  336. tmp_path: Path,
  337. ) -> None:
  338. render = SMOKE["snapshot_session_filename"]
  339. select = SMOKE["selected_snapshot_session_files"]
  340. assert render(0, 0) == "session.jsonl"
  341. assert render(0, 2) == "session.v2.jsonl"
  342. assert render(3, 0) == "session.3.jsonl"
  343. assert render(3, 2) == "session.3.v2.jsonl"
  344. (tmp_path / "session.jsonl").write_text(
  345. '{"type":"session","version":0}\n', encoding="utf-8",
  346. )
  347. (tmp_path / "session.v1.jsonl").write_text(
  348. '{"type":"session","version":1}\n', encoding="utf-8",
  349. )
  350. (tmp_path / "session.1.jsonl").write_text(
  351. '{"type":"session","version":0}\n', encoding="utf-8",
  352. )
  353. assert {index: path.name for index, path in select(tmp_path).items()} == {
  354. 0: "session.v1.jsonl",
  355. 1: "session.1.jsonl",
  356. }
  357. def test_snapshot_comparison_accepts_v3_output_against_v2_without_rewriting(tmp_path: Path) -> None:
  358. predecessor = '{"type":"session","version":2}\n'
  359. successor = '{"type":"session","version":3}\n'
  360. old_path = tmp_path / "session.v2.jsonl"
  361. old_path.write_text(predecessor, encoding="utf-8")
  362. files = {"session.v3.jsonl": successor}
  363. SMOKE["compare_snapshot_files"](files, False, tmp_path, ("session.v2.jsonl",))
  364. assert old_path.read_text(encoding="utf-8") == predecessor
  365. assert not (tmp_path / "session.v3.jsonl").exists()
  366. SMOKE["compare_snapshot_files"](files, True, tmp_path, ("session.v2.jsonl",))
  367. assert old_path.read_text(encoding="utf-8") == predecessor
  368. assert (tmp_path / "session.v3.jsonl").read_text(encoding="utf-8") == successor
  369. assert SMOKE["selected_snapshot_session_files"](tmp_path) == {0: tmp_path / "session.v3.jsonl"}
  370. @pytest.mark.parametrize("filenames", [
  371. ("session.1.v2.jsonl", "session.v2.jsonl"),
  372. ("session.v2.jsonl",),
  373. ("session.v2.jsonl", "session.2.v2.jsonl"),
  374. ])
  375. def test_snapshot_builder_checks_role_order_and_count_across_generations(
  376. tmp_path: Path, filenames: tuple[str, ...],
  377. ) -> None:
  378. files = {"session.v3.jsonl": "", "session.1.v3.jsonl": ""}
  379. with pytest.raises(AssertionError, match="snapshot builder produced"):
  380. SMOKE["compare_snapshot_files"](files, False, tmp_path, filenames)
  381. def test_snapshot_generation_comparison_rejects_changed_payload(tmp_path: Path) -> None:
  382. (tmp_path / "session.v2.jsonl").write_text(
  383. '{"type":"session","version":2,"id":"expected"}\n', encoding="utf-8",
  384. )
  385. with pytest.raises(AssertionError, match="executable snapshot mismatch"):
  386. SMOKE["compare_snapshot_files"](
  387. {"session.v3.jsonl": '{"type":"session","version":3,"id":"changed"}\n'},
  388. False, tmp_path, ("session.v2.jsonl",),
  389. )
  390. @pytest.mark.parametrize("version", [2, 4])
  391. @pytest.mark.parametrize("update", [False, True])
  392. def test_snapshot_comparison_rejects_noncurrent_writer(
  393. tmp_path: Path, version: int, update: bool,
  394. ) -> None:
  395. golden = '{"type":"session","version":2}\n'
  396. (tmp_path / "session.v2.jsonl").write_text(golden, encoding="utf-8")
  397. content = json.dumps({"type": "session", "version": version}) + "\n"
  398. with pytest.raises(AssertionError, match="expected current Session format v3"):
  399. SMOKE["compare_snapshot_files"](
  400. {f"session.v{version}.jsonl": content}, update, tmp_path, ("session.v2.jsonl",),
  401. )
  402. assert (tmp_path / "session.v2.jsonl").read_text(encoding="utf-8") == golden
  403. assert not (tmp_path / "session.v4.jsonl").exists()
  404. @pytest.mark.parametrize("version", [2, 3, 4])
  405. def test_persisted_session_requires_current_writer(version: int) -> None:
  406. content = json.dumps({"type": "session", "version": version}) + "\n"
  407. path = Path(f"session.v{version}.jsonl")
  408. if version == 3:
  409. assert SMOKE["assert_persisted_session_version"](path, content) == version
  410. else:
  411. with pytest.raises(AssertionError, match="expected current Session format v3"):
  412. SMOKE["assert_persisted_session_version"](path, content)
  413. def test_snapshot_generation_filename_must_match_header(tmp_path: Path) -> None:
  414. (tmp_path / "session.v1.jsonl").write_text(
  415. '{"type":"session","version":0}\n', encoding="utf-8",
  416. )
  417. with pytest.raises(AssertionError, match="filename declares Session format v1"):
  418. SMOKE["selected_snapshot_session_files"](tmp_path)
  419. @pytest.mark.parametrize("returncode", [1, -1073741819, 3221225477])
  420. def test_profile_plugin_failure_reports_native_exit_status(monkeypatch: pytest.MonkeyPatch, returncode: int) -> None:
  421. def failed_install(*args: object, **kwargs: object) -> subprocess.CompletedProcess[str]:
  422. return subprocess.CompletedProcess(args=[], returncode=returncode, stdout="", stderr="")
  423. monkeypatch.setattr(subprocess, "run", failed_install)
  424. with pytest.raises(AssertionError) as error:
  425. SMOKE["smoke_sdk_profile_plugin"]("http://127.0.0.1:1")
  426. message = str(error.value)
  427. assert f"returncode={returncode}" in message
  428. assert f"0x{returncode & 0xffffffff:08x}" in message
  429. assert "stdout='' stderr=''" in message