返回 last30days-skill
test_x_chain_failover.py
根目录 / tests / test_x_chain_failover.py
1 """grok must never be a dead end: every failure falls through to the next backend.
2
3 Grok is opt-in only (not in the auto chain), but when pinned via
4 LAST30DAYS_X_BACKEND=grok, any way grok can come back empty or error must
5 surface properly so the run reports the failure honestly rather than silently
6 leaving X uncovered.
7 """
8
9 from unittest import mock
10
11 import pytest
12
13 from lib import grok_x, pipeline
14
15
16 @pytest.fixture(autouse=True)
17 def _audited_grok(monkeypatch):
18 """Version rejection is exercised separately in test_grok_tool_boundary."""
19 monkeypatch.setattr(grok_x, "_check_cli_version", lambda *args: (None, "grok 1.0.70 (f50904eaee6c)"))
20
21
22 def _stub_grok(monkeypatch, stdout="", returncode=0, raises=None):
23 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
24
25 def fake_run(cmd, **kwargs):
26 if raises:
27 raise raises
28 import subprocess
29 return subprocess.CompletedProcess(cmd, returncode, stdout, "")
30
31 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
32
33
34 def test_grok_cli_missing_yields_an_error_for_failover(monkeypatch):
35 monkeypatch.setattr(grok_x, "binary_path", lambda: None)
36 result = grok_x.search_x("topic", "2026-07-14", "2026-08-13")
37 assert result["items"] == []
38 assert result["error"], "a missing CLI must surface an error so the chain logs it"
39
40
41 def test_grok_timeout_yields_an_error_for_failover(monkeypatch):
42 import subprocess
43 _stub_grok(monkeypatch, raises=subprocess.TimeoutExpired("grok", 1))
44 result = grok_x.search_x("topic", "2026-07-14", "2026-08-13")
45 assert result["items"] == []
46 assert "timed out" in result["error"]
47
48
49 def test_grok_nonzero_exit_yields_an_error_for_failover(monkeypatch):
50 _stub_grok(monkeypatch, stdout="boom", returncode=1)
51 result = grok_x.search_x("topic", "2026-07-14", "2026-08-13")
52 assert result["items"] == []
53 assert result["error"]
54
55
56 def test_grok_fabricated_results_end_up_empty_not_fabricated(monkeypatch):
57 """Provenance rejection must yield no items, so the chain moves to bird
58 rather than the run reporting invented posts."""
59 block = (
60 "id: 1956158892141441450\nhandle: steipete\n"
61 "created_at: Fri, 15 Aug 2025 00:59:58 GMT\nlikes: 100\n"
62 "text: recalled from training data\n"
63 )
64 _stub_grok(monkeypatch, stdout=block)
65 result = grok_x.search_x("steipete", "2026-07-14", "2026-08-13")
66 assert result["items"] == []
67
68
69 def test_clean_empty_result_carries_no_error(monkeypatch):
70 """A quiet window is not a broken backend; the chain still tries the next."""
71 _stub_grok(monkeypatch, stdout="The search returned no posts.")
72 result = grok_x.search_x("topic", "2026-07-14", "2026-08-13")
73 assert result["items"] == []
74 assert "error" not in result
75
76
77 # --- lane budget and selective retry ---------------------------------------
78
79 def test_lane_budget_stops_issuing_queries(monkeypatch):
80 """Three lanes over three handles is up to 14 sequential LLM subprocess
81 calls, bounded only by per-call timeouts without a shared budget."""
82 import time as _time
83 calls = {"n": 0}
84 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
85
86 def fake_run(cmd, **kwargs):
87 import subprocess
88 calls["n"] += 1
89 return subprocess.CompletedProcess(cmd, 0, "no posts", "")
90
91 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
92 past = _time.monotonic() - 1
93 items, revoked = grok_x.search_handles(
94 ["a", "b", "c"], "topic", "2026-07-14", "2026-08-13", deadline=past
95 )
96 assert items == []
97 assert revoked is False
98 assert calls["n"] == 0, "an expired budget must stop the lane before any call"
99
100
101 def test_lane_budget_constant_is_bounded():
102 assert 0 < grok_x.LANE_BUDGET_SECONDS <= 300
103
104
105 def test_clean_empty_is_not_retried(monkeypatch):
106 """Retrying a byte-identical prompt cannot turn an empty window into posts;
107 it only doubles latency and Grok-plan spend on the common case."""
108 calls = {"n": 0}
109 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
110
111 def fake_run(cmd, **kwargs):
112 import subprocess
113 calls["n"] += 1
114 return subprocess.CompletedProcess(cmd, 0, "The search returned no posts.", "")
115
116 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
117 items, error, auth_revoked = grok_x._run_query("topic", "2026-07-14", "2026-08-13")
118 assert items == [] and error == ""
119 assert calls["n"] == 1, "a clean empty result must not be retried"
120 assert not auth_revoked
121
122
123 def test_fabricated_response_is_still_retried(monkeypatch):
124 """The retry must survive for the case it exists to fix."""
125 calls = {"n": 0}
126 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
127 fabricated = (
128 "id: 1956158892141441450\nhandle: steipete\n"
129 "created_at: Fri, 15 Aug 2025 00:59:58 GMT\nlikes: 10\ntext: recalled\n"
130 )
131
132 def fake_run(cmd, **kwargs):
133 import subprocess
134 calls["n"] += 1
135 return subprocess.CompletedProcess(cmd, 0, fabricated, "")
136
137 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
138 grok_x._run_query("steipete", "2026-07-14", "2026-08-13")
139 assert calls["n"] == 2, "a provenance rejection is exactly what retrying can fix"
140
141
142 def test_lanes_use_a_single_attempt(monkeypatch):
143 """Lane queries pass attempts=1: an empty lane is a legitimate outcome and
144 the shared budget is better spent on breadth than on repeats."""
145 import inspect
146 for fn in (grok_x.search_handles, grok_x.search_mentions, grok_x.search_name):
147 assert "attempts=1" in inspect.getsource(fn), (
148 f"{fn.__name__} should not retry lane queries"
149 )
150
151
152 def test_every_empty_path_leaves_the_chain_free_to_continue(monkeypatch):
153 """The chain advances on an empty item list, so each way grok can come back
154 empty must actually return an empty list rather than raising or hanging.
155
156 Behavioral on purpose: an earlier version of this test asserted on the
157 loop's source text and broke when the loop moved, while proving nothing
158 about what grok returns.
159 """
160 import subprocess as sp
161 cases = {
162 "missing binary": (lambda: None, None),
163 "fabricated": (lambda: "/usr/bin/grok",
164 "id: 1956158892141441450\nhandle: steipete\n"
165 "created_at: Fri, 15 Aug 2025 00:59:58 GMT\nlikes: 1\ntext: x\n"),
166 "clean empty": (lambda: "/usr/bin/grok", "no posts found"),
167 "nonzero exit": (lambda: "/usr/bin/grok", None),
168 }
169 for label, (binary, stdout) in cases.items():
170 monkeypatch.setattr(grok_x, "binary_path", binary)
171 if stdout is not None:
172 monkeypatch.setattr(
173 grok_x.subproc, "run_with_timeout",
174 lambda cmd, **kw: sp.CompletedProcess(cmd, 0, stdout, ""),
175 )
176 elif binary() is not None:
177 monkeypatch.setattr(
178 grok_x.subproc, "run_with_timeout",
179 lambda cmd, **kw: sp.CompletedProcess(cmd, 1, "", "boom"),
180 )
181 result = grok_x.search_x("topic", "2026-07-14", "2026-08-13")
182 assert result["items"] == [], f"{label} must yield no items so the chain advances"
183
184
185 def test_a_call_is_not_started_when_it_cannot_finish_in_budget(monkeypatch):
186 """The lanes run synchronously with no outer timeout, so a per-call floor
187 would let the last call overrun the documented shared ceiling."""
188 import time as _time
189 calls = {"n": 0}
190 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
191
192 def fake_run(cmd, **kwargs):
193 import subprocess
194 calls["n"] += 1
195 return subprocess.CompletedProcess(cmd, 0, "no posts", "")
196
197 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
198 # 5s left: below the minimum useful call, so nothing should start.
199 near = _time.monotonic() + 5
200 items, error, auth_revoked = grok_x._run_query("topic", "2026-07-14", "2026-08-13", deadline=near)
201 assert calls["n"] == 0
202 assert "budget exhausted" in error
203 assert not auth_revoked
204
205
206 def test_timeout_never_exceeds_the_remaining_budget(monkeypatch):
207 import time as _time
208 seen = {}
209 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
210
211 def fake_run(cmd, **kwargs):
212 import subprocess
213 seen["timeout"] = kwargs.get("timeout")
214 return subprocess.CompletedProcess(cmd, 0, "no posts", "")
215
216 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
217 remaining = 40
218 grok_x._run_query(
219 "topic", "2026-07-14", "2026-08-13",
220 deadline=_time.monotonic() + remaining,
221 )
222 assert seen["timeout"] <= remaining
223
224
225 def test_no_x_backend_is_skipped_unconfigured(monkeypatch):
226 """CR-025: an empty X chain must read as SKIPPED_UNCONFIGURED, not failure."""
227 from unittest.mock import patch
228
229 from lib import env, schema
230
231 monkeypatch.setattr(env, "x_backend_chain", lambda config: [])
232 subquery = schema.SubQuery(
233 label="test",
234 search_query="test query",
235 ranking_query="test query",
236 sources=["x"],
237 )
238 runtime = schema.ProviderRuntime(
239 reasoning_provider="mock",
240 planner_model="mock",
241 rerank_model="mock",
242 )
243 try:
244 pipeline._retrieve_stream_impl(
245 topic="test",
246 subquery=subquery,
247 source="x",
248 config={},
249 depth="quick",
250 date_range=("2026-02-15", "2026-03-17"),
251 runtime=runtime,
252 mock=False,
253 )
254 except pipeline.SourceRunError as exc:
255 assert exc.outcome_state == schema.SKIPPED_UNCONFIGURED
256 else:
257 raise AssertionError("empty X chain should raise SourceRunError")
258
259
260 def test_no_x_backend_message_carries_skip_marker():
261 """The unconfigured-X error must match the _classify_source_failure skip marker."""
262 from lib import schema
263
264 state, attempted = pipeline._classify_source_failure(
265 pipeline.SourceRunError(
266 "No X backend is available (not configured).",
267 schema.SKIPPED_UNCONFIGURED,
268 )
269 )
270 assert state == schema.SKIPPED_UNCONFIGURED
271 assert attempted is False
272
272 lines PYTHON