| 1 | """LAST30DAYS_X_BUDGET_SECONDS: the X chain budget follows the resolved config. |
| 2 | |
| 3 | A grok call on a subscription account measured 150-170s, longer than the fixed |
| 4 | 90s chain deadline, so the lane exhausted its budget before the first call |
| 5 | returned and reported no X posts (issue #1626). |
| 6 | """ |
| 7 | |
| 8 | import contextlib |
| 9 | import sys |
| 10 | import threading |
| 11 | import unittest |
| 12 | from pathlib import Path |
| 13 | from unittest import mock |
| 14 | |
| 15 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "skills" / "last30days" / "scripts")) |
| 16 | |
| 17 | from lib import pipeline, schema # noqa: E402 |
| 18 | |
| 19 | |
| 20 | class XBudgetSettingTest(unittest.TestCase): |
| 21 | def test_default_budget_keeps_the_chain_constant(self): |
| 22 | self.assertEqual( |
| 23 | pipeline._x_chain_budget_seconds({}), pipeline.X_CHAIN_DEADLINE_SECONDS, |
| 24 | ) |
| 25 | |
| 26 | def test_configured_budget_is_used(self): |
| 27 | self.assertEqual( |
| 28 | pipeline._x_chain_budget_seconds({"LAST30DAYS_X_BUDGET_SECONDS": "200"}), 200.0, |
| 29 | ) |
| 30 | self.assertEqual( |
| 31 | pipeline._x_chain_budget_seconds({"LAST30DAYS_X_BUDGET_SECONDS": 150}), 150.0, |
| 32 | ) |
| 33 | |
| 34 | def test_unusable_budgets_fall_back_to_the_default(self): |
| 35 | for raw in (None, "", " ", "not-a-number", 0, -5, "0"): |
| 36 | with self.subTest(raw=raw): |
| 37 | self.assertEqual( |
| 38 | pipeline._x_chain_budget_seconds({"LAST30DAYS_X_BUDGET_SECONDS": raw}), |
| 39 | pipeline.X_CHAIN_DEADLINE_SECONDS, |
| 40 | ) |
| 41 | |
| 42 | def test_non_finite_budgets_fall_back_to_the_default(self): |
| 43 | # A NaN would otherwise pass the non-positive check, propagate through |
| 44 | # min(), and leave the chain deadline permanently unreached. |
| 45 | for raw in ("nan", float("nan"), "inf", float("inf"), "-inf"): |
| 46 | with self.subTest(raw=raw): |
| 47 | self.assertEqual( |
| 48 | pipeline._x_chain_budget_seconds({"LAST30DAYS_X_BUDGET_SECONDS": raw}), |
| 49 | pipeline.X_CHAIN_DEADLINE_SECONDS, |
| 50 | ) |
| 51 | |
| 52 | def test_only_x_plans_take_the_raised_stream_wait(self): |
| 53 | plan = mock.Mock() |
| 54 | plan.subqueries = [mock.Mock(sources=["reddit"])] |
| 55 | self.assertFalse(pipeline._plan_includes_x(plan, {"reddit"})) |
| 56 | plan.subqueries = [mock.Mock(sources=["reddit", "x"])] |
| 57 | self.assertTrue(pipeline._plan_includes_x(plan, {"reddit", "x"})) |
| 58 | self.assertFalse(pipeline._plan_includes_x(plan, {"reddit"})) |
| 59 | |
| 60 | def test_budget_above_the_per_call_ceiling_clamps(self): |
| 61 | self.assertEqual( |
| 62 | pipeline._x_chain_budget_seconds({"LAST30DAYS_X_BUDGET_SECONDS": "999"}), |
| 63 | pipeline.X_CHAIN_DEADLINE_MAX_SECONDS, |
| 64 | ) |
| 65 | |
| 66 | def test_stream_wait_covers_the_configured_budget(self): |
| 67 | self.assertEqual( |
| 68 | pipeline._x_stream_wait_seconds({}), pipeline.STREAM_FUTURE_TIMEOUT_SECONDS, |
| 69 | ) |
| 70 | self.assertEqual( |
| 71 | pipeline._x_stream_wait_seconds({"LAST30DAYS_X_BUDGET_SECONDS": "200"}), 210.0, |
| 72 | ) |
| 73 | |
| 74 | def test_unset_budget_keeps_the_standard_stream_wait(self): |
| 75 | # The raise is for an explicit setting only: a run with no budget keeps |
| 76 | # the module's standard wait even when another run lowered the constant. |
| 77 | with mock.patch.object(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 0.2): |
| 78 | self.assertEqual(pipeline._x_stream_wait_seconds({}), 0.2) |
| 79 | self.assertEqual( |
| 80 | pipeline._x_stream_wait_seconds({"LAST30DAYS_X_BUDGET_SECONDS": "200"}), |
| 81 | 200.0 + pipeline.X_STREAM_WAIT_MARGIN_SECONDS, |
| 82 | ) |
| 83 | |
| 84 | def test_run_keeps_the_standard_wait_without_a_budget(self): |
| 85 | """No explicit budget: a tight cutoff must not shorten the base wait.""" |
| 86 | seen = {} |
| 87 | |
| 88 | def fake_retrieve(**kwargs): |
| 89 | if kwargs.get("source") == "x": |
| 90 | seen["deadline"] = kwargs["config"]["_research_deadline"] |
| 91 | return [], {} |
| 92 | |
| 93 | plan = schema.QueryPlan( |
| 94 | raw_topic="sqlite", |
| 95 | intent="technical", |
| 96 | freshness_mode="balanced_recent", |
| 97 | cluster_mode="coverage", |
| 98 | source_weights={"x": 1.0}, |
| 99 | subqueries=[ |
| 100 | schema.SubQuery( |
| 101 | label="primary", search_query="sqlite", |
| 102 | ranking_query="sqlite", sources=["x"], |
| 103 | ) |
| 104 | ], |
| 105 | ) |
| 106 | real_completed_streams = pipeline._completed_streams |
| 107 | |
| 108 | def fake_batches(batches, bundle, retry_origins=None): |
| 109 | seen["batch_deadline"] = batches[0][2] |
| 110 | return real_completed_streams(batches, bundle, retry_origins=retry_origins) |
| 111 | |
| 112 | cutoff = pipeline.time.monotonic() + 120.0 |
| 113 | config = {"_finalization_deadline": cutoff} |
| 114 | with mock.patch.object(pipeline, "_retrieve_stream", fake_retrieve), \ |
| 115 | mock.patch.object(pipeline, "_completed_streams", fake_batches): |
| 116 | report = pipeline.run( |
| 117 | topic="sqlite", config=config, depth="quick", |
| 118 | requested_sources=["x"], mock=True, web_backend="none", |
| 119 | external_plan=schema.to_dict(plan), |
| 120 | ) |
| 121 | self.assertIsNotNone(report) |
| 122 | self.assertIn("deadline", seen, "run() never submitted the X stream") |
| 123 | self.assertGreater( |
| 124 | seen["deadline"], cutoff + 1.0, |
| 125 | "an unset budget shortened the standard 180s wait to the cutoff", |
| 126 | ) |
| 127 | self.assertGreater( |
| 128 | seen["batch_deadline"], cutoff + 1.0, |
| 129 | "an unset budget shortened the collector deadline to the cutoff", |
| 130 | ) |
| 131 | |
| 132 | def test_run_caps_the_x_wait_at_the_finalization_cutoff(self): |
| 133 | """run() must not hand X a wait that outlives the finalization window.""" |
| 134 | seen = {} |
| 135 | |
| 136 | def fake_retrieve(**kwargs): |
| 137 | if kwargs.get("source") == "x": |
| 138 | seen["deadline"] = kwargs["config"]["_research_deadline"] |
| 139 | return [], {} |
| 140 | |
| 141 | plan = schema.QueryPlan( |
| 142 | raw_topic="sqlite", |
| 143 | intent="technical", |
| 144 | freshness_mode="balanced_recent", |
| 145 | cluster_mode="coverage", |
| 146 | source_weights={"x": 1.0}, |
| 147 | subqueries=[ |
| 148 | schema.SubQuery( |
| 149 | label="primary", search_query="sqlite", |
| 150 | ranking_query="sqlite", sources=["x"], |
| 151 | ) |
| 152 | ], |
| 153 | ) |
| 154 | # 120s left before finalization: enough for the cut-off case to differ |
| 155 | # from the old 180s floor, and far longer than this mocked run takes. |
| 156 | real_completed_streams = pipeline._completed_streams |
| 157 | |
| 158 | def fake_batches(batches, bundle, retry_origins=None): |
| 159 | seen["batch_deadline"] = batches[0][2] |
| 160 | return real_completed_streams(batches, bundle, retry_origins=retry_origins) |
| 161 | |
| 162 | cutoff = pipeline.time.monotonic() + 120.0 |
| 163 | config = { |
| 164 | "LAST30DAYS_X_BUDGET_SECONDS": "200", |
| 165 | "_finalization_deadline": cutoff, |
| 166 | } |
| 167 | with mock.patch.object(pipeline, "_retrieve_stream", fake_retrieve), \ |
| 168 | mock.patch.object(pipeline, "_completed_streams", fake_batches): |
| 169 | report = pipeline.run( |
| 170 | topic="sqlite", config=config, depth="quick", |
| 171 | requested_sources=["x"], mock=True, web_backend="none", |
| 172 | external_plan=schema.to_dict(plan), |
| 173 | ) |
| 174 | self.assertIsNotNone(report) |
| 175 | self.assertIn("deadline", seen, "run() never submitted the X stream") |
| 176 | self.assertLessEqual( |
| 177 | seen["deadline"], cutoff + 0.001, |
| 178 | "the X stream wait outlived the run's finalization cutoff", |
| 179 | ) |
| 180 | self.assertGreater(seen["deadline"], cutoff - 120.0) |
| 181 | self.assertLessEqual( |
| 182 | seen["batch_deadline"], cutoff + 0.001, |
| 183 | "run() handed the collector a deadline past the finalization cutoff", |
| 184 | ) |
| 185 | self.assertGreaterEqual( |
| 186 | seen["batch_deadline"], cutoff - 0.5, |
| 187 | "run() collapsed the raised wait to zero instead of the cutoff", |
| 188 | ) |
| 189 | |
| 190 | def test_slow_submission_cannot_extend_the_collector_past_the_cutoff(self): |
| 191 | """A late collector start still stops at the original absolute cutoff.""" |
| 192 | seen = {} |
| 193 | release = threading.Event() |
| 194 | real_abandoning_executor = pipeline._abandoning_executor |
| 195 | |
| 196 | class _SlowSubmit: |
| 197 | """Delay each submission so the collector starts after fan-out began.""" |
| 198 | |
| 199 | def __init__(self, inner, delay, recorder): |
| 200 | self._inner = inner |
| 201 | self._delay = delay |
| 202 | self._recorder = recorder |
| 203 | |
| 204 | def submit(self, *args, **kwargs): |
| 205 | self._recorder["submits"] = self._recorder.get("submits", 0) + 1 |
| 206 | if self._recorder["submits"] <= 1: |
| 207 | pipeline.time.sleep(self._delay) |
| 208 | return self._inner.submit(*args, **kwargs) |
| 209 | |
| 210 | def __getattr__(self, name): |
| 211 | return getattr(self._inner, name) |
| 212 | |
| 213 | @contextlib.contextmanager |
| 214 | def slow_abandoning_executor(max_workers): |
| 215 | with real_abandoning_executor(max_workers=max_workers) as inner: |
| 216 | yield _SlowSubmit(inner, 0.8, seen) |
| 217 | |
| 218 | def fake_retrieve(**kwargs): |
| 219 | if kwargs.get("source") == "x": |
| 220 | seen["x_started"] = pipeline.time.monotonic() |
| 221 | release.wait(10.0) |
| 222 | return [], {} |
| 223 | |
| 224 | def fake_finalization_deadline(_config, _run_started): |
| 225 | # Deterministic cutoff relative to run()'s own clock: the fan-out |
| 226 | # starts milliseconds after this call. Later finalization calls |
| 227 | # must see the same cutoff. |
| 228 | if "cutoff" not in seen: |
| 229 | seen["cutoff"] = pipeline.time.monotonic() + 1.5 |
| 230 | return seen["cutoff"] |
| 231 | |
| 232 | plan = schema.QueryPlan( |
| 233 | raw_topic="sqlite", |
| 234 | intent="technical", |
| 235 | freshness_mode="balanced_recent", |
| 236 | cluster_mode="coverage", |
| 237 | source_weights={"x": 1.0}, |
| 238 | subqueries=[ |
| 239 | schema.SubQuery( |
| 240 | label="primary", search_query="sqlite", |
| 241 | ranking_query="sqlite", sources=["x"], |
| 242 | ) |
| 243 | ], |
| 244 | ) |
| 245 | real_completed_streams = pipeline._completed_streams |
| 246 | |
| 247 | def fake_batches(batches, bundle, retry_origins=None): |
| 248 | seen["collector_start"] = pipeline.time.monotonic() |
| 249 | seen["batch_deadline"] = batches[0][2] |
| 250 | seen["bundle"] = bundle |
| 251 | return real_completed_streams(batches, bundle, retry_origins=retry_origins) |
| 252 | |
| 253 | started = pipeline.time.monotonic() |
| 254 | try: |
| 255 | with mock.patch.object(pipeline, "_retrieve_stream", fake_retrieve), \ |
| 256 | mock.patch.object(pipeline, "_completed_streams", fake_batches), \ |
| 257 | mock.patch.object(pipeline, "_finalization_deadline", fake_finalization_deadline), \ |
| 258 | mock.patch.object(pipeline, "_abandoning_executor", slow_abandoning_executor): |
| 259 | report = pipeline.run( |
| 260 | topic="sqlite", config={"LAST30DAYS_X_BUDGET_SECONDS": "200"}, |
| 261 | depth="quick", requested_sources=["x"], mock=True, |
| 262 | web_backend="none", external_plan=schema.to_dict(plan), |
| 263 | ) |
| 264 | finally: |
| 265 | release.set() |
| 266 | elapsed = pipeline.time.monotonic() - started |
| 267 | self.assertIsNotNone(report) |
| 268 | self.assertIn("x_started", seen, "run() never submitted the X stream") |
| 269 | self.assertGreater( |
| 270 | seen["submits"], 0, "the test never delayed a stream submission", |
| 271 | ) |
| 272 | self.assertGreaterEqual( |
| 273 | seen["collector_start"] - started, 0.7, |
| 274 | "the collector started before the delayed submission finished", |
| 275 | ) |
| 276 | self.assertLess( |
| 277 | elapsed, seen["cutoff"] - started + 0.5, |
| 278 | "run() waited past the absolute cutoff after a slow submission", |
| 279 | ) |
| 280 | self.assertLessEqual( |
| 281 | seen["batch_deadline"], seen["cutoff"] + 0.001, |
| 282 | "the collector deadline passed the run's finalization cutoff", |
| 283 | ) |
| 284 | self.assertGreaterEqual( |
| 285 | seen["batch_deadline"], seen["cutoff"] - 0.5, |
| 286 | "the collector deadline was not the finalization cutoff", |
| 287 | ) |
| 288 | detail = seen["bundle"].errors_by_source.get("x", "") |
| 289 | self.assertIn("timed out after", detail) |
| 290 | reported = float(detail.split("timed out after ")[1].rstrip("s")) |
| 291 | self.assertLess( |
| 292 | reported, 1.3, |
| 293 | "the timeout detail reported the pre-fan-out budget, not the cutoff wait", |
| 294 | ) |
| 295 | self.assertGreaterEqual( |
| 296 | reported, 0.4, |
| 297 | "the timeout detail did not report the cutoff-limited wait", |
| 298 | ) |
| 299 | |
| 300 | def test_supplemental_lane_deadline_clamps_to_the_recorded_cutoff(self): |
| 301 | """A supplemental lane budget may not outlive the recorded cutoff.""" |
| 302 | cutoff = pipeline.time.monotonic() + 5.0 |
| 303 | config = { |
| 304 | "LAST30DAYS_X_BUDGET_SECONDS": "200", |
| 305 | "_finalization_deadline": cutoff, |
| 306 | "_research_deadline": cutoff + 600.0, |
| 307 | } |
| 308 | self.assertEqual(pipeline._x_lane_deadline(config, 150.0), cutoff) |
| 309 | self.assertEqual( |
| 310 | pipeline._x_lane_deadline( |
| 311 | {"_research_deadline": cutoff}, pipeline.grok_x.LANE_BUDGET_SECONDS, |
| 312 | ), |
| 313 | cutoff, |
| 314 | ) |
| 315 | # Without a recorded cutoff the lane keeps its own budget. |
| 316 | lane = pipeline._x_lane_deadline({}, 150.0) |
| 317 | self.assertGreater(lane, pipeline.time.monotonic() + 140.0) |
| 318 | |
| 319 | def test_supplemental_handle_lanes_receive_the_cutoff_deadline(self): |
| 320 | """The grok handle lanes must run on the clamped budget, not now+150s.""" |
| 321 | captured = {} |
| 322 | cutoff = pipeline.time.monotonic() + 5.0 |
| 323 | config = { |
| 324 | "LAST30DAYS_X_BUDGET_SECONDS": "200", |
| 325 | "_finalization_deadline": cutoff, |
| 326 | } |
| 327 | plan = schema.QueryPlan( |
| 328 | raw_topic="Peter Steinberger", |
| 329 | intent="person", |
| 330 | freshness_mode="balanced_recent", |
| 331 | cluster_mode="coverage", |
| 332 | source_weights={"x": 1.0}, |
| 333 | subqueries=[ |
| 334 | schema.SubQuery( |
| 335 | label="primary", search_query="Peter Steinberger", |
| 336 | ranking_query="Peter Steinberger", sources=["x"], |
| 337 | ) |
| 338 | ], |
| 339 | ) |
| 340 | |
| 341 | def fake_search(*_args, **kwargs): |
| 342 | captured.setdefault("deadlines", []).append(kwargs.get("deadline")) |
| 343 | return [], False |
| 344 | |
| 345 | with mock.patch.object(pipeline.env, "x_backend_chain", lambda _c: ["grok"]), \ |
| 346 | mock.patch.object( |
| 347 | pipeline.x_judge, "promotable_handles", |
| 348 | lambda *_a, **_k: (["steipete"], []), |
| 349 | ), \ |
| 350 | mock.patch.object(pipeline.grok_x, "search_handles", fake_search), \ |
| 351 | mock.patch.object(pipeline.grok_x, "search_mentions", fake_search), \ |
| 352 | mock.patch.object(pipeline.grok_x, "search_name", fake_search): |
| 353 | pipeline._run_supplemental_searches( |
| 354 | topic="Peter Steinberger", |
| 355 | bundle=schema.RetrievalBundle(), |
| 356 | plan=plan, |
| 357 | config=config, |
| 358 | depth="default", |
| 359 | date_range=("2026-10-27", "2026-11-26"), |
| 360 | runtime=mock.Mock(x_search_backend=None), |
| 361 | mock=False, |
| 362 | rate_limited_sources=set(), |
| 363 | rate_limit_lock=threading.Lock(), |
| 364 | x_handle="steipete", |
| 365 | ) |
| 366 | self.assertTrue(captured.get("deadlines"), "no grok handle lane ran") |
| 367 | for deadline in captured["deadlines"]: |
| 368 | self.assertLessEqual( |
| 369 | deadline, cutoff + 0.001, |
| 370 | "a supplemental handle lane outlived the finalization cutoff", |
| 371 | ) |
| 372 | self.assertGreaterEqual( |
| 373 | deadline, cutoff - 0.5, |
| 374 | "the handle lane did not receive the recorded cutoff", |
| 375 | ) |
| 376 | |
| 377 | |
| 378 | def test_resolved_config_layers_the_setting(self): |
| 379 | with mock.patch.dict("os.environ", {"LAST30DAYS_X_BUDGET_SECONDS": "200"}): |
| 380 | config = pipeline.env.get_config() |
| 381 | self.assertEqual(config.get("LAST30DAYS_X_BUDGET_SECONDS"), "200") |
| 382 | |
| 383 | def test_pinned_chain_deadline_uses_the_configured_budget(self): |
| 384 | """The chain handed to the backend must run past one 150-170s grok call.""" |
| 385 | captured = {} |
| 386 | |
| 387 | def fake_attempt( |
| 388 | backend, query, from_date, to_date, depth, config, |
| 389 | warnings=None, deadline=None, |
| 390 | ): |
| 391 | captured["deadline"] = deadline |
| 392 | return [], "boom", None |
| 393 | |
| 394 | plan = mock.Mock() |
| 395 | plan.domain = "topic" |
| 396 | with mock.patch.object(pipeline.env, "x_backend_chain", lambda c: ["grok"]), \ |
| 397 | mock.patch.object(pipeline, "_attempt_x_backend", fake_attempt), \ |
| 398 | mock.patch.object(pipeline.time, "monotonic", return_value=1000.0): |
| 399 | pipeline._fetch_discovery_source( |
| 400 | "x", plan, from_date="2026-08-01", to_date="2026-08-31", |
| 401 | depth="quick", mock=False, |
| 402 | config={"LAST30DAYS_X_BUDGET_SECONDS": "200"}, |
| 403 | keyword_gate=True, |
| 404 | ) |
| 405 | self.assertAlmostEqual(captured["deadline"], 1200.0) |
| 406 | |
| 407 | |
| 408 | if __name__ == "__main__": |
| 409 | unittest.main() |
| 410 |