test_smoke_model.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. from __future__ import annotations
  2. import json
  3. import runpy
  4. import subprocess
  5. from pathlib import Path
  6. import pytest
  7. ROOT = Path(__file__).resolve().parents[3]
  8. SMOKE = runpy.run_path(ROOT / "scripts" / "smoke-python-runtime.py")
  9. @pytest.mark.parametrize(
  10. ("prompt_name", "expected"),
  11. [
  12. ("SNAPSHOT_DIRECT_CHILD_PROMPT", "DIRECT_CHILD_OK"),
  13. ("SNAPSHOT_WORKFLOW_CHILD_PROMPT", "WORKFLOW_CHILD_OK"),
  14. ],
  15. )
  16. def test_child_prompt_precedes_runtime_context(prompt_name: str, expected: str) -> None:
  17. chunks = SMOKE["completion_chunks"]({
  18. "messages": [
  19. {"role": "user", "content": SMOKE[prompt_name]},
  20. {"role": "user", "content": "Current runtime context"},
  21. ],
  22. })
  23. assert any(
  24. choice.get("delta", {}).get("content") == expected
  25. for chunk in chunks
  26. for choice in chunk.get("choices", [])
  27. )
  28. def test_mcp_smoke_requests_the_discovered_tool() -> None:
  29. chunks = SMOKE["completion_chunks"]({
  30. "messages": [{"role": "user", "content": SMOKE["MCP_PROMPT"]}],
  31. "tools": [{"type": "function", "function": {"name": "mcp__fixture__add"}}],
  32. })
  33. calls = [
  34. call
  35. for chunk in chunks
  36. for choice in chunk.get("choices", [])
  37. for call in choice.get("delta", {}).get("tool_calls", [])
  38. ]
  39. assert calls[0]["function"] == {
  40. "name": "mcp__fixture__add",
  41. "arguments": '{"a": 19, "b": 23}',
  42. }
  43. def test_mcp_smoke_accepts_the_external_server_result() -> None:
  44. chunks = SMOKE["completion_chunks"]({
  45. "messages": [
  46. {"role": "user", "content": SMOKE["MCP_PROMPT"]},
  47. {
  48. "role": "assistant",
  49. "tool_calls": [{
  50. "id": "mcp-add",
  51. "type": "function",
  52. "function": {"name": "mcp__fixture__add", "arguments": '{}'},
  53. }],
  54. },
  55. {"role": "tool", "tool_call_id": "mcp-add", "content": "42"},
  56. ],
  57. })
  58. assert any(
  59. choice.get("delta", {}).get("content") == SMOKE["MCP_TEXT"]
  60. for chunk in chunks
  61. for choice in chunk.get("choices", [])
  62. )
  63. def test_snapshot_comparison_normalizes_only_session_generation_provenance() -> None:
  64. normalize = SMOKE["normalize_session_format_comparison"]
  65. expected = {
  66. "header": {"type": "session", "version": 0, "otherVersion": 7},
  67. "accepted": {
  68. "type": "session-log-deepseek/delivery-accepted",
  69. "data": {"sessionId": "s", "throughSeq": 4},
  70. },
  71. "source": {
  72. "kind": "session-reference",
  73. "references": [{"sessionId": "other", "capturedThroughSeq": 8}],
  74. },
  75. }
  76. actual = {
  77. "header": {"type": "session", "version": 1, "otherVersion": 7},
  78. "accepted": {
  79. "type": "session-log-deepseek/delivery-accepted",
  80. "data": {"sessionId": "s", "sessionFormatVersion": 1, "throughSeq": 4},
  81. },
  82. "source": {
  83. "kind": "session-reference",
  84. "references": [{
  85. "sessionId": "other",
  86. "capturedFormatVersion": 1,
  87. "capturedThroughSeq": 8,
  88. }],
  89. },
  90. }
  91. assert normalize(expected) == normalize(actual)
  92. assert normalize(expected)["header"]["otherVersion"] == 7
  93. def test_snapshot_value_normalizes_embedded_assistant_stream_timing() -> None:
  94. normalize = SMOKE["normalize_snapshot_value"]
  95. event = {
  96. "type": "assistant/message",
  97. "seq": 4,
  98. "time": 100,
  99. "data": {
  100. "stream": [
  101. {"type": "chunk", "time": 101, "chunk": {"type": "finish"}},
  102. {"type": "text-chunks", "time0": 102, "dt": [1, 2], "texts": ["a", "b", "c"]},
  103. ],
  104. },
  105. }
  106. normalized = normalize(event, [])
  107. assert normalized["time"] == 0
  108. assert normalized["data"]["stream"] == [
  109. {"type": "chunk", "time": 0, "chunk": {"type": "finish"}},
  110. {"type": "text-chunks", "time0": 0, "dt": [0, 0], "texts": ["a", "b", "c"]},
  111. ]
  112. def test_snapshot_comparison_expands_embedded_assistant_streams() -> None:
  113. normalize = SMOKE["normalize_session_format_comparison"]
  114. expected = [
  115. {
  116. "type": "assistant/chunk",
  117. "seq": 4,
  118. "time": 0,
  119. "data": {"turn": 1, "step": 1, "chunk": {
  120. "type": "text-delta", "index": 0, "text": "done",
  121. }},
  122. },
  123. {
  124. "type": "assistant/message",
  125. "seq": 5,
  126. "time": 0,
  127. "data": {"turn": 1, "step": 1, "message": {"role": "assistant"}},
  128. "sourceEventSeqs": [4],
  129. "surfaceOp": "append",
  130. },
  131. ]
  132. actual = [{
  133. "type": "assistant/message",
  134. "seq": 4,
  135. "time": 0,
  136. "data": {
  137. "turn": 1,
  138. "step": 1,
  139. "message": {"role": "assistant"},
  140. "stream": [{
  141. "type": "text-chunks", "time0": 0, "index": 0, "dt": [], "texts": ["done"],
  142. }],
  143. },
  144. "surfaceOp": "append",
  145. }]
  146. assert normalize(actual, 2) == normalize(expected, 1)
  147. tool_result = {
  148. "type": "tool/result",
  149. "data": {"turn": 1, "step": 1},
  150. "sourceEventSeqs": [4],
  151. }
  152. assert normalize(tool_result, 1)["sourceEventSeqs"] == [4]
  153. assert normalize(tool_result, 2)["sourceEventSeqs"] == [4]
  154. def test_snapshot_stream_expands_reasoning_and_tool_call_records() -> None:
  155. expand = SMOKE["expand_snapshot_stream_member"]
  156. assert expand({
  157. "type": "reasoning-chunks", "time0": 0, "index": 1,
  158. "dt": [], "texts": ["think"],
  159. }) == [{"type": "reasoning-delta", "index": 1, "text": "think"}]
  160. assert expand({
  161. "type": "tool-call-chunks", "time0": 0, "index": 2,
  162. "id": "call-1", "name": "read", "dt": [1], "args": ["{", "}"],
  163. }) == [
  164. {"type": "tool-call-delta", "index": 2, "id": "call-1", "name": "read", "argumentsDelta": "{"},
  165. {"type": "tool-call-delta", "index": 2, "id": "call-1", "name": "read", "argumentsDelta": "}"},
  166. ]
  167. def test_snapshot_file_builder_order_is_checked_outside_update_mode(tmp_path: Path) -> None:
  168. compare = SMOKE["compare_snapshot_files"]
  169. with pytest.raises(AssertionError, match="snapshot builder produced"):
  170. compare({}, False, tmp_path, ("result.json",))
  171. def test_snapshot_comparison_expands_sdk_wrapped_attempts() -> None:
  172. normalize = SMOKE["normalize_session_format_comparison"]
  173. actual = [{
  174. "method": "session.event",
  175. "payload": {
  176. "sessionId": "s",
  177. "event": {
  178. "type": "assistant/attempt",
  179. "seq": 7,
  180. "time": 0,
  181. "data": {
  182. "turn": 1,
  183. "step": 1,
  184. "stream": [{"type": "chunk", "time": 0, "chunk": {"type": "finish"}}],
  185. },
  186. },
  187. },
  188. }]
  189. assert normalize(actual) == [{
  190. "method": "session.event",
  191. "payload": {
  192. "sessionId": "s",
  193. "event": {
  194. "type": "assistant/chunk",
  195. "data": {"turn": 1, "step": 1, "chunk": {"type": "finish"}},
  196. },
  197. },
  198. }]
  199. def test_snapshot_generation_names_select_highest_role_without_double_counting(
  200. tmp_path: Path,
  201. ) -> None:
  202. render = SMOKE["snapshot_session_filename"]
  203. select = SMOKE["selected_snapshot_session_files"]
  204. assert render(0, 0) == "session.jsonl"
  205. assert render(0, 2) == "session.v2.jsonl"
  206. assert render(3, 0) == "session.3.jsonl"
  207. assert render(3, 2) == "session.3.v2.jsonl"
  208. (tmp_path / "session.jsonl").write_text(
  209. '{"type":"session","version":0}\n', encoding="utf-8",
  210. )
  211. (tmp_path / "session.v1.jsonl").write_text(
  212. '{"type":"session","version":1}\n', encoding="utf-8",
  213. )
  214. (tmp_path / "session.1.jsonl").write_text(
  215. '{"type":"session","version":0}\n', encoding="utf-8",
  216. )
  217. assert {index: path.name for index, path in select(tmp_path).items()} == {
  218. 0: "session.v1.jsonl",
  219. 1: "session.1.jsonl",
  220. }
  221. def test_snapshot_comparison_accepts_v3_output_against_v2_without_rewriting(tmp_path: Path) -> None:
  222. predecessor = '{"type":"session","version":2}\n'
  223. successor = '{"type":"session","version":3}\n'
  224. old_path = tmp_path / "session.v2.jsonl"
  225. old_path.write_text(predecessor, encoding="utf-8")
  226. files = {"session.v3.jsonl": successor}
  227. SMOKE["compare_snapshot_files"](files, False, tmp_path, ("session.v2.jsonl",))
  228. assert old_path.read_text(encoding="utf-8") == predecessor
  229. assert not (tmp_path / "session.v3.jsonl").exists()
  230. SMOKE["compare_snapshot_files"](files, True, tmp_path, ("session.v2.jsonl",))
  231. assert old_path.read_text(encoding="utf-8") == predecessor
  232. assert (tmp_path / "session.v3.jsonl").read_text(encoding="utf-8") == successor
  233. assert SMOKE["selected_snapshot_session_files"](tmp_path) == {0: tmp_path / "session.v3.jsonl"}
  234. @pytest.mark.parametrize("filenames", [
  235. ("session.1.v2.jsonl", "session.v2.jsonl"),
  236. ("session.v2.jsonl",),
  237. ("session.v2.jsonl", "session.2.v2.jsonl"),
  238. ])
  239. def test_snapshot_builder_checks_role_order_and_count_across_generations(
  240. tmp_path: Path, filenames: tuple[str, ...],
  241. ) -> None:
  242. files = {"session.v3.jsonl": "", "session.1.v3.jsonl": ""}
  243. with pytest.raises(AssertionError, match="snapshot builder produced"):
  244. SMOKE["compare_snapshot_files"](files, False, tmp_path, filenames)
  245. def test_snapshot_generation_comparison_rejects_changed_payload(tmp_path: Path) -> None:
  246. (tmp_path / "session.v2.jsonl").write_text(
  247. '{"type":"session","version":2,"id":"expected"}\n', encoding="utf-8",
  248. )
  249. with pytest.raises(AssertionError, match="executable snapshot mismatch"):
  250. SMOKE["compare_snapshot_files"](
  251. {"session.v3.jsonl": '{"type":"session","version":3,"id":"changed"}\n'},
  252. False, tmp_path, ("session.v2.jsonl",),
  253. )
  254. @pytest.mark.parametrize("version", [2, 4])
  255. @pytest.mark.parametrize("update", [False, True])
  256. def test_snapshot_comparison_rejects_noncurrent_writer(
  257. tmp_path: Path, version: int, update: bool,
  258. ) -> None:
  259. golden = '{"type":"session","version":2}\n'
  260. (tmp_path / "session.v2.jsonl").write_text(golden, encoding="utf-8")
  261. content = json.dumps({"type": "session", "version": version}) + "\n"
  262. with pytest.raises(AssertionError, match="expected current Session format v3"):
  263. SMOKE["compare_snapshot_files"](
  264. {f"session.v{version}.jsonl": content}, update, tmp_path, ("session.v2.jsonl",),
  265. )
  266. assert (tmp_path / "session.v2.jsonl").read_text(encoding="utf-8") == golden
  267. assert not (tmp_path / "session.v4.jsonl").exists()
  268. @pytest.mark.parametrize("version", [2, 3, 4])
  269. def test_persisted_session_requires_current_writer(version: int) -> None:
  270. content = json.dumps({"type": "session", "version": version}) + "\n"
  271. path = Path(f"session.v{version}.jsonl")
  272. if version == 3:
  273. assert SMOKE["assert_persisted_session_version"](path, content) == version
  274. else:
  275. with pytest.raises(AssertionError, match="expected current Session format v3"):
  276. SMOKE["assert_persisted_session_version"](path, content)
  277. def test_snapshot_generation_filename_must_match_header(tmp_path: Path) -> None:
  278. (tmp_path / "session.v1.jsonl").write_text(
  279. '{"type":"session","version":0}\n', encoding="utf-8",
  280. )
  281. with pytest.raises(AssertionError, match="filename declares Session format v1"):
  282. SMOKE["selected_snapshot_session_files"](tmp_path)
  283. @pytest.mark.parametrize("returncode", [1, -1073741819, 3221225477])
  284. def test_profile_plugin_failure_reports_native_exit_status(monkeypatch: pytest.MonkeyPatch, returncode: int) -> None:
  285. def failed_install(*args: object, **kwargs: object) -> subprocess.CompletedProcess[str]:
  286. return subprocess.CompletedProcess(args=[], returncode=returncode, stdout="", stderr="")
  287. monkeypatch.setattr(subprocess, "run", failed_install)
  288. with pytest.raises(AssertionError) as error:
  289. SMOKE["smoke_sdk_profile_plugin"]("http://127.0.0.1:1")
  290. message = str(error.value)
  291. assert f"returncode={returncode}" in message
  292. assert f"0x{returncode & 0xffffffff:08x}" in message
  293. assert "stdout='' stderr=''" in message