| 1 | """grok's three supplement lanes, wired into the pipeline. |
| 2 | |
| 3 | The coverage requirement: for an entity topic the run must return what the |
| 4 | subject said, what others said *to* them, and what others said *about* them by |
| 5 | name. The third is not redundant with the second -- most discussion never |
| 6 | @-mentions the subject, so a mention-only lane structurally cannot reach it. |
| 7 | """ |
| 8 | |
| 9 | import inspect |
| 10 | import json |
| 11 | import subprocess |
| 12 | |
| 13 | import pytest |
| 14 | |
| 15 | import last30days as cli |
| 16 | from lib import pipeline, schema |
| 17 | |
| 18 | |
| 19 | def _supplements_source(): |
| 20 | return inspect.getsource(pipeline._run_supplemental_searches) |
| 21 | |
| 22 | |
| 23 | def test_grok_is_handle_lane_capable(): |
| 24 | src = _supplements_source() |
| 25 | assert '("grok", "bird", "xapi", "xquik")' in src, ( |
| 26 | "grok supports from:/@ natively; leaving it out of the capable set " |
| 27 | "silently drops all of Phase 2 for grok users, as it already does for " |
| 28 | "xai and xurl. xapi (X API v2 bearer) runs the same lanes, after " |
| 29 | "bird and before xquik (R7)." |
| 30 | ) |
| 31 | |
| 32 | |
| 33 | def test_xapi_lane_branch_sits_between_bird_and_xquik(): |
| 34 | src = _supplements_source() |
| 35 | grok = src.index('if primary == "grok":') |
| 36 | bird = src.index('elif primary == "bird":') |
| 37 | xapi = src.index('elif primary == "xapi":') |
| 38 | xquik = src.index('elif primary == "xquik":') |
| 39 | assert grok < bird < xapi < xquik |
| 40 | xapi_block = src[xapi:xquik] |
| 41 | assert "x_api.search_handles" in xapi_block |
| 42 | assert "x_api.search_mentions" in xapi_block |
| 43 | |
| 44 | |
| 45 | def test_all_three_lanes_are_defined_for_grok(): |
| 46 | src = _supplements_source() |
| 47 | grok_block = src[src.index('if primary == "grok":'):src.index('elif primary == "bird":')] |
| 48 | assert "_from_lane" in grok_block |
| 49 | assert "_about_lane" in grok_block |
| 50 | assert "_name_lane" in grok_block |
| 51 | |
| 52 | |
| 53 | def test_name_lane_is_gated_and_defaults_off(): |
| 54 | """Backends without phrase/negation support must not get a broken lane.""" |
| 55 | src = _supplements_source() |
| 56 | assert "_name_lane = None" in src |
| 57 | assert "if _name_lane is not None:" in src |
| 58 | |
| 59 | |
| 60 | def test_name_lane_items_reach_the_batch(): |
| 61 | src = _supplements_source() |
| 62 | assert "from_items + about_items + name_items" in src, ( |
| 63 | "name-lane results must join the batch, not be computed and dropped" |
| 64 | ) |
| 65 | |
| 66 | |
| 67 | def test_name_lane_excludes_the_subject_handles(): |
| 68 | src = _supplements_source() |
| 69 | grok_block = src[src.index('if primary == "grok":'):src.index('elif primary == "bird":')] |
| 70 | assert "exclude_handles=hs" in grok_block, ( |
| 71 | "the name lane must exclude the subject's own posts; those belong to " |
| 72 | "the by-lane and would otherwise double-count" |
| 73 | ) |
| 74 | |
| 75 | |
| 76 | def test_name_lane_failure_does_not_abort_the_run(): |
| 77 | src = _supplements_source() |
| 78 | block = src[src.index("if _name_lane is not None:"):] |
| 79 | assert "except Exception" in block |
| 80 | assert "NAME-lane" in block |
| 81 | |
| 82 | |
| 83 | def test_by_lane_does_not_and_the_topic_by_default(monkeypatch): |
| 84 | """A prior defect emptied the from-lane by ANDing the topic into it. |
| 85 | |
| 86 | The `and_topic` parameter now exists for extracted handles that need to |
| 87 | demonstrate on-topic content, but the default is False (no topic AND). |
| 88 | """ |
| 89 | from lib import grok_x |
| 90 | sig = inspect.signature(grok_x.search_handles) |
| 91 | assert "topic" in sig.parameters |
| 92 | assert "and_topic" in sig.parameters |
| 93 | assert sig.parameters["and_topic"].default is False |
| 94 | queries = [] |
| 95 | post_url = "https://x.com/steipete/status/2087568620465607078" |
| 96 | |
| 97 | def run(cmd, **kwargs): |
| 98 | if "--version" in cmd: |
| 99 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442) [stable]", "") |
| 100 | prompt = cmd[cmd.index("-p") + 1] |
| 101 | prefix = "Query (JSON string literal): " |
| 102 | query_lines = [line[len(prefix):] for line in prompt.splitlines() if line.startswith(prefix)] |
| 103 | assert len(query_lines) == 1 |
| 104 | queries.append(json.loads(query_lines[0])) |
| 105 | posts = [{"url": post_url, "text": "Released a new agent toolkit.", "likes": 10}] |
| 106 | return subprocess.CompletedProcess(cmd, 0, json.dumps(posts), "") |
| 107 | |
| 108 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok") |
| 109 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", run) |
| 110 | for options in ({}, {"and_topic": True}): |
| 111 | items, revoked = grok_x.search_handles( |
| 112 | ["steipete"], "Peter Steinberger", "2026-07-14", "2026-08-13", **options |
| 113 | ) |
| 114 | assert [item["url"] for item in items] == [post_url] |
| 115 | assert revoked is False |
| 116 | |
| 117 | assert queries == [ |
| 118 | "from:steipete since:2026-07-14 until:2026-08-14", |
| 119 | "from:steipete Peter Steinberger since:2026-07-14 until:2026-08-14", |
| 120 | ] |
| 121 | |
| 122 | |
| 123 | |
| 124 | # --- behavioral: the source-text assertions above cannot catch a crash ------- |
| 125 | |
| 126 | @pytest.mark.parametrize("has_posts", [True, False]) |
| 127 | def test_partial_coverage_does_not_raise_on_an_empty_x_source(monkeypatch, has_posts): |
| 128 | """Regression: partial coverage was recorded via bundle.record_failure with |
| 129 | the state string "degraded", which is not in SourceOutcome's valid_states. |
| 130 | With zero Phase-1 X items record_failure passes the caller's state straight |
| 131 | through, so it raised ValueError and killed the whole run -- on exactly the |
| 132 | entity topics this feature targets. No source-text assertion could catch |
| 133 | this; only executing the path does.""" |
| 134 | runtime = schema.ProviderRuntime( |
| 135 | reasoning_provider="local", planner_model="", rerank_model="", |
| 136 | x_search_backend="grok", |
| 137 | ) |
| 138 | monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *_args: (runtime, None)) |
| 139 | monkeypatch.setattr(pipeline, "available_sources", lambda *_args, **_kwargs: ["x"]) |
| 140 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _config: ["grok"]) |
| 141 | monkeypatch.setattr(pipeline, "_retrieve_stream_impl", lambda **_kwargs: ([], {})) |
| 142 | lanes = [] |
| 143 | |
| 144 | def from_lane(handles, topic, from_date, to_date, **kwargs): |
| 145 | lanes.append("by") |
| 146 | assert handles == ["steipete"] |
| 147 | assert kwargs["and_topic"] is False |
| 148 | if not has_posts: |
| 149 | return [], False |
| 150 | return [{ |
| 151 | "id": "2087568620465607078", |
| 152 | "url": "https://x.com/steipete/status/2087568620465607078", |
| 153 | "author_handle": "steipete", |
| 154 | "text": "Peter Steinberger released a new agent toolkit.", |
| 155 | "date": "2026-08-12", |
| 156 | "relevance": 0.9, |
| 157 | "engagement": {"likes": 1462, "reposts": 48, "replies": 95}, |
| 158 | }], False |
| 159 | |
| 160 | def empty_lane(name): |
| 161 | def search(*_args, **_kwargs): |
| 162 | lanes.append(name) |
| 163 | return [], False |
| 164 | return search |
| 165 | |
| 166 | monkeypatch.setattr(pipeline.grok_x, "search_handles", from_lane) |
| 167 | monkeypatch.setattr(pipeline.grok_x, "search_mentions", empty_lane("mention")) |
| 168 | monkeypatch.setattr(pipeline.grok_x, "search_name", empty_lane("name")) |
| 169 | report = pipeline.run( |
| 170 | topic="Peter Steinberger", config={}, depth="default", |
| 171 | requested_sources=["x"], x_handle="steipete", web_backend="none", |
| 172 | as_of_date="2026-08-13", |
| 173 | external_plan={ |
| 174 | "intent": "general", "freshness_mode": "balanced_recent", |
| 175 | "cluster_mode": "story", "raw_topic": "Peter Steinberger", |
| 176 | "source_weights": {"x": 1.0}, |
| 177 | "subqueries": [{"label": "primary", "search_query": "Peter Steinberger", |
| 178 | "ranking_query": "Peter Steinberger", "sources": ["x"]}], |
| 179 | }, |
| 180 | ) |
| 181 | |
| 182 | warning = ( |
| 183 | "X partial coverage: mention, name lane(s) returned nothing; " |
| 184 | "the report may show only one side of this entity." |
| 185 | ) |
| 186 | assert lanes == ["by", "mention", "name"] |
| 187 | expected_urls = [ |
| 188 | "https://x.com/steipete/status/2087568620465607078", |
| 189 | ] if has_posts else [] |
| 190 | assert [item.url for item in report.items_by_source["x"]] == expected_urls |
| 191 | expected_warnings = [warning] if has_posts else [] |
| 192 | assert report.artifacts.get("x_partial_coverage", []) == expected_warnings |
| 193 | assert [note for note in report.warnings if note.startswith("X partial coverage:")] == expected_warnings |
| 194 | assert report.errors_by_source == {} |
| 195 | assert report.source_status["x"].state == ("ok" if has_posts else "no-results") |
| 196 | assert report.source_status["x"].items_returned == int(has_posts) |
| 197 | assert cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "1"}) == 0 |
| 198 | |
| 199 | |
| 200 | def test_degraded_is_not_a_valid_source_outcome_state(): |
| 201 | """Pins why partial coverage must not go through record_failure.""" |
| 202 | with pytest.raises(ValueError): |
| 203 | schema.SourceOutcome( |
| 204 | source="x", state="degraded", items_returned=0, attempted=True, |
| 205 | ) |
| 206 |