返回 last30days-skill
test_external_plan_source_contract.py
根目录 / tests / test_external_plan_source_contract.py
1 """Unavailable external-plan sources must never broaden retrieval."""
2
3 import json
4 import sys
5 from unittest.mock import patch
6
7 import pytest
8
9 import last30days as cli
10 from lib import pipeline, planner
11
12
13 def plan_with(*source_lists):
14 return {
15 "intent": "opinion",
16 "freshness_mode": "balanced_recent",
17 "cluster_mode": "debate",
18 "subqueries": [
19 {"label": f"part-{i}", "search_query": "test topic", "ranking_query": "test topic",
20 "sources": sources, "weight": 1.0}
21 for i, sources in enumerate(source_lists)
22 ],
23 }
24
25
26 @pytest.mark.parametrize("depth", ["quick", "default", "deep"])
27 def test_all_unavailable_fails_before_retrieval(depth, capsys):
28 with patch.object(pipeline, "_retrieve_stream") as retrieve:
29 with pytest.raises(ValueError, match="No available planned sources"):
30 pipeline.run(
31 topic="test topic", config={}, mock=True, web_backend="none",
32 requested_sources=["reddit", "hackernews"], depth=depth,
33 external_plan=plan_with(["instagram"]),
34 )
35 retrieve.assert_not_called()
36 assert "part-0" in capsys.readouterr().err
37
38
39 @pytest.mark.parametrize("depth", ["quick", "default", "deep"])
40 def test_mixed_plan_skips_empty_subquery_without_expansion(depth, capsys):
41 with patch.object(pipeline, "_retrieve_stream", return_value=([], {})) as retrieve:
42 report = pipeline.run(
43 topic="test topic", config={}, mock=True, web_backend="none",
44 requested_sources=["reddit", "hackernews"], depth=depth,
45 external_plan=plan_with(["instagram"], ["reddit", "instagram"]),
46 )
47 assert report.query_plan.subqueries[0].label == "part-1"
48 assert report.query_plan.subqueries[0].sources == ["reddit"]
49 assert retrieve.call_args_list
50 assert {call.kwargs["source"] for call in retrieve.call_args_list} == {"reddit"}
51 assert "part-0" in capsys.readouterr().err
52
53
54 def test_internal_empty_intersection_retains_fallback():
55 plan = planner._sanitize_plan(
56 plan_with(["instagram"]), "test topic", ["reddit", "hackernews"], None, "default",
57 )
58 assert plan.subqueries[0].sources == ["reddit", "hackernews"]
59
60
61 def _planned(report):
62 """Subquery sources minus the installed/opted-in lanes the engine backfills."""
63 return [
64 [s for s in sq.sources if s not in planner.HOST_PLAN_BACKFILL_SOURCES]
65 for sq in report.query_plan.subqueries
66 ]
67
68
69 def _run_with_plan(topic, plan, depth="default", **kwargs):
70 with patch.object(pipeline, "_retrieve_stream", return_value=([], {})) as retrieve:
71 report = pipeline.run(
72 topic=topic, config={}, mock=True, web_backend="none",
73 depth=depth, external_plan=plan, **kwargs,
74 )
75 return report, {call.kwargs["source"] for call in retrieve.call_args_list}
76
77
78 def test_host_plan_on_company_topic_does_not_gain_jobs():
79 report, fetched = _run_with_plan(
80 "Listen Labs", plan_with(["reddit", "youtube"], ["hackernews"]),
81 )
82 assert _planned(report) == [["reddit", "youtube"], ["hackernews"]]
83 assert "jobs" not in fetched
84 assert "jobs" not in report.source_status
85
86
87 def test_host_plan_naming_jobs_keeps_it_on_non_company_topic():
88 report, fetched = _run_with_plan(
89 "test topic", plan_with(["reddit", "jobs"], ["hackernews"]),
90 )
91 assert _planned(report) == [["reddit", "jobs"], ["hackernews"]]
92 assert "jobs" in fetched
93
94
95 def test_host_plan_naming_jobs_does_not_override_excluded_jobs():
96 with patch.object(pipeline, "_retrieve_stream", return_value=([], {})) as retrieve:
97 report = pipeline.run(
98 topic="test topic", config={"EXCLUDE_SOURCES": "jobs"}, mock=True,
99 web_backend="none", depth="default",
100 external_plan=plan_with(["reddit", "jobs"], ["hackernews"]),
101 )
102 fetched = {call.kwargs["source"] for call in retrieve.call_args_list}
103 assert _planned(report) == [["reddit"], ["hackernews"]]
104 assert "jobs" not in fetched
105
106
107 def test_hiring_mode_adds_jobs_to_host_plan_without_it():
108 report, fetched = _run_with_plan(
109 "Listen Labs", plan_with(["reddit"], ["hackernews"]),
110 hiring_signals_mode=True,
111 )
112 assert len(report.query_plan.subqueries) == 2
113 assert all("jobs" in sq.sources for sq in report.query_plan.subqueries)
114 assert "jobs" in fetched
115
116
117 def test_hiring_mode_does_not_duplicate_jobs_already_in_host_plan():
118 report, _ = _run_with_plan(
119 "Listen Labs", plan_with(["reddit", "jobs"], ["jobs"]),
120 hiring_signals_mode=True,
121 )
122 assert len(report.query_plan.subqueries) == 2
123 assert all(sq.sources.count("jobs") == 1 for sq in report.query_plan.subqueries)
124
125
126 def test_host_plan_gains_installed_lanes_it_never_named(capsys):
127 report, fetched = _run_with_plan(
128 "test topic", plan_with(["reddit", "youtube"], ["hackernews"]),
129 requested_sources=["reddit", "youtube", "hackernews", "digg", "arxiv"],
130 )
131 assert [sq.sources for sq in report.query_plan.subqueries] == [
132 ["reddit", "youtube", "digg", "arxiv"], ["hackernews"],
133 ]
134 assert {"digg", "arxiv"} <= fetched
135 assert "digg, arxiv" in capsys.readouterr().err
136
137
138 @pytest.mark.parametrize("depth", ["default", "deep"])
139 def test_host_plan_can_omit_specific_installed_lanes(depth, capsys):
140 plan = dict(plan_with(["reddit"], ["hackernews"]), omit_sources=["arxiv", "devto"])
141 report, fetched = _run_with_plan(
142 "test topic", plan, depth=depth,
143 requested_sources=["reddit", "hackernews", "digg", "arxiv", "devto"],
144 )
145 assert [sq.sources for sq in report.query_plan.subqueries] == [
146 ["reddit", "digg"], ["hackernews"],
147 ]
148 assert fetched == {"reddit", "hackernews", "digg"}
149 assert {"arxiv", "devto"}.isdisjoint(report.query_plan.source_weights)
150 assert "part-0: digg" in capsys.readouterr().err
151
152
153 def test_omitted_trustpilot_is_not_probed_or_backfilled():
154 plan = dict(plan_with(["reddit"]), omit_sources=["trustpilot"])
155 with patch.object(pipeline.trustpilot, "can_run_now") as can_run:
156 report, fetched = _run_with_plan("test topic", plan)
157 can_run.assert_not_called()
158 assert "trustpilot" not in report.query_plan.subqueries[0].sources
159 assert "trustpilot" not in fetched
160
161
162 @pytest.mark.parametrize("mode", ["--mock", "--diagnose", "--preflight"])
163 def test_cli_omission_skips_trustpilot_readiness_check(mode, tmp_path, capsys):
164 plan = dict(plan_with(["reddit"]), omit_sources=["trustpilot"])
165 config = {"EXCLUDE_SOURCES": "digg"}
166 with (
167 patch.object(sys, "argv", [
168 "last30days.py", "test topic", mode, "--no-browser-cookies",
169 "--plan", json.dumps(plan), "--search", "reddit,trustpilot",
170 "--emit", "json", "--save-dir", str(tmp_path),
171 ]),
172 patch.object(cli.env, "get_config", return_value=config),
173 patch.object(pipeline, "which", side_effect=lambda command: command),
174 patch.object(pipeline.trustpilot, "can_run_now", return_value={"can_run": True}) as can_run,
175 ):
176 assert cli.main() == 0
177 payload = json.loads(capsys.readouterr().out)
178 can_run.assert_not_called()
179 assert config["EXCLUDE_SOURCES"] == "digg"
180 if mode == "--diagnose":
181 assert not payload["trustpilot_can_run"]
182 assert {"digg", "trustpilot"}.isdisjoint(payload["available_sources"])
183 elif mode == "--preflight":
184 assert {"digg", "trustpilot"}.isdisjoint(payload["network"]["available_sources"])
185
186
187 @pytest.mark.parametrize(
188 "omissions", ["arxiv", None, [True], [["arxiv"]], ["arxive"], ["amazon"]],
189 )
190 def test_host_plan_rejects_invalid_omissions(omissions):
191 with pytest.raises(ValueError, match="omit_sources"):
192 planner.validate_external_plan(dict(plan_with(["reddit"]), omit_sources=omissions))
193
194
195 def test_host_plan_rejects_omitting_a_source_named_by_a_subquery():
196 plan = dict(plan_with(["reddit"], ["arxiv"]), omit_sources=["arxiv"])
197 with pytest.raises(ValueError, match="omit_sources.*arxiv"):
198 planner.validate_external_plan(plan)
199
200
201 def test_host_plan_lane_named_in_secondary_subquery_is_not_duplicated():
202 report, _ = _run_with_plan(
203 "test topic", plan_with(["reddit"], ["digg"]),
204 requested_sources=["reddit", "digg"],
205 )
206 assert [sq.sources for sq in report.query_plan.subqueries] == [["reddit"], ["digg"]]
207
208
209 def test_host_plan_backfill_only_adds_available_lanes():
210 # EXCLUDE_SOURCES and --search filter ``available`` before the backfill runs.
211 plan = planner._sanitize_plan(
212 plan_with(["reddit"]), "test topic", ["reddit"], None, "default",
213 honor_plan_sources=True,
214 )
215 pipeline._ensure_unplanned_lanes_in_host_plan(plan, ["reddit"])
216 assert plan.subqueries[0].sources == ["reddit"]
217
218
219 def test_host_plan_backfill_skips_paid_decision_lanes():
220 plan = planner._sanitize_plan(
221 plan_with(["reddit"]), "test topic", ["reddit", "amazon", "meta_ads"], None, "default",
222 honor_plan_sources=True,
223 )
224 pipeline._ensure_unplanned_lanes_in_host_plan(plan, ["reddit", "amazon", "meta_ads"])
225 assert plan.subqueries[0].sources == ["reddit"]
226
227
228 def test_host_plan_backfill_says_when_a_paid_lane_is_available_but_not_run(capsys):
229 plan = planner._sanitize_plan(
230 plan_with(["reddit"]), "test topic", ["reddit", "amazon", "meta_ads"], None, "default",
231 honor_plan_sources=True,
232 )
233 pipeline._ensure_unplanned_lanes_in_host_plan(plan, ["reddit", "amazon", "meta_ads"])
234 err = capsys.readouterr().err
235 assert "[Amazon] available but not requested for this run" in err
236 assert "[Meta Ads] available but not requested for this run" in err
237
238
239 @pytest.mark.parametrize("lane", ["amazon", "meta_ads"])
240 @pytest.mark.parametrize("depth", ["quick", "default"])
241 def test_host_plan_gains_a_paid_lane_named_in_search(lane, depth, capsys):
242 # The runbook has the host request these through --search, not the plan.
243 report, fetched = _run_with_plan(
244 "test topic", plan_with(["hackernews"]),
245 requested_sources=["hackernews", lane], depth=depth,
246 )
247 assert report.query_plan.subqueries[0].sources == ["hackernews", lane]
248 assert lane in fetched
249 err = capsys.readouterr().err
250 assert f"[Planner] Added" in err and lane in err
251 assert "not requested for this run" not in err
252
253
254 @pytest.mark.parametrize(
255 "lane,flag", [("amazon", "_amazon_query"), ("meta_ads", "_meta_ads_page")],
256 )
257 def test_host_plan_gains_a_paid_lane_whose_targeting_flag_is_set(lane, flag):
258 # INCLUDE_SOURCES makes the lane available; the flag is this run's request.
259 available = ["reddit", "amazon", "meta_ads"]
260 plan = planner._sanitize_plan(
261 plan_with(["reddit"]), "test topic", available, None, "default",
262 honor_plan_sources=True,
263 )
264 asked = pipeline._paid_lanes_asked_for(None, {flag: "value"})
265 assert asked == [lane]
266 pipeline._ensure_unplanned_lanes_in_host_plan(plan, available, asked=asked)
267 assert plan.subqueries[0].sources == ["reddit", lane]
268
269
270 def test_paid_lane_only_in_include_sources_is_not_asked_for():
271 assert pipeline._paid_lanes_asked_for(
272 ["reddit"], {"INCLUDE_SOURCES": "amazon,meta_ads"},
273 ) == []
274 assert pipeline._paid_lanes_asked_for(None, {}) == []
275
276
277 def test_host_plan_naming_a_paid_lane_is_left_alone(capsys):
278 report, _ = _run_with_plan(
279 "test topic", plan_with(["hackernews"], ["amazon"]),
280 requested_sources=["hackernews", "amazon"],
281 )
282 assert [sq.sources for sq in report.query_plan.subqueries] == [["hackernews"], ["amazon"]]
283 assert "[Planner] Added" not in capsys.readouterr().err
284
285
286 def test_amazon_footer_is_silent_when_the_lane_was_available_but_never_ran():
287 # It used to print `no products matched "<keyword>"` for a search never made.
288 from lib import render
289
290 with patch.object(pipeline, "_paid_lanes_asked_for", return_value=[]):
291 report, fetched = _run_with_plan(
292 "test topic", plan_with(["hackernews"]),
293 requested_sources=["hackernews", "amazon"],
294 )
295 assert "amazon" not in fetched
296 assert "amazon_query" not in report.artifacts
297 assert render._amazon_footer_line(report) is None
298
299
300 def test_exclude_sources_keeps_an_installed_lane_out_of_the_backfill():
301 def which(name):
302 return "/fake/bin/digg-pp-cli" if name == "digg-pp-cli" else None
303
304 with patch.object(pipeline, "which", side_effect=which):
305 assert "digg" in pipeline.available_sources({})
306 assert "digg" not in pipeline.available_sources({"EXCLUDE_SOURCES": "digg"})
307
308
309 def test_quick_host_plan_keeps_its_source_budget():
310 report, fetched = _run_with_plan(
311 "test topic", plan_with(["reddit", "youtube"]),
312 requested_sources=["reddit", "youtube", "digg", "arxiv"], depth="quick",
313 )
314 assert [sq.sources for sq in report.query_plan.subqueries] == [["reddit", "youtube"]]
315 assert not {"digg", "arxiv"} & fetched
316
317
318 def test_runbook_tells_the_host_to_name_jobs_for_company_topics():
319 from tests.skill_contract import reference_text
320
321 runbook = reference_text("research-runbook")
322 omit = runbook[runbook.index("Leave out only"):]
323 omit = omit[:omit.index(".") + 1]
324 assert "`jobs`" not in omit
325 assert "`perplexity`" in omit
326 assert "For a company or the person who leads it, name `jobs`" in runbook
327
328
329 def test_host_plan_naming_jobs_on_a_person_topic_fetches_jobs():
330 report, fetched = _run_with_plan(
331 "Jensen Huang", plan_with(["reddit", "jobs"], ["hackernews"]),
332 )
333 assert _planned(report) == [["reddit", "jobs"], ["hackernews"]]
334 assert "jobs" in fetched
335
336
337 # ---- #1449: backfill only lanes that can run this session ----
338
339 def _backfill(available, monkeypatch, can_run, **kwargs):
340 from lib import trustpilot
341
342 calls = []
343
344 def fake_can_run(config=None):
345 calls.append(config)
346 return {"can_run": can_run}
347
348 monkeypatch.setattr(trustpilot, "can_run_now", fake_can_run)
349 plan = planner._sanitize_plan(
350 plan_with(["reddit"]), "test topic", available, None, "default",
351 honor_plan_sources=True,
352 )
353 pipeline._ensure_unplanned_lanes_in_host_plan(plan, available, **kwargs)
354 return plan.subqueries[0].sources, calls
355
356
357 def test_trustpilot_without_a_session_is_not_backfilled(monkeypatch, capsys):
358 sources, calls = _backfill(["reddit", "trustpilot", "digg"], monkeypatch, can_run=False)
359 assert sources == ["reddit", "digg"]
360 assert calls
361 err = capsys.readouterr().err
362 assert "Not adding trustpilot" in err
363 assert "Added installed/opted-in/requested sources" in err
364 assert "digg" in err and "trustpilot" not in err.split("Added")[1]
365
366
367 def test_trustpilot_that_can_run_is_still_backfilled(monkeypatch):
368 sources, _ = _backfill(["reddit", "trustpilot"], monkeypatch, can_run=True)
369 assert sources == ["reddit", "trustpilot"]
370
371
372 @pytest.mark.parametrize("kwargs", [
373 {"requested_sources": ["reddit", "trustpilot"]},
374 {"trustpilot_domain": "example.com"},
375 ])
376 def test_explicitly_requested_trustpilot_is_backfilled_without_a_session(monkeypatch, kwargs):
377 sources, calls = _backfill(["reddit", "trustpilot"], monkeypatch, can_run=False, **kwargs)
378 assert sources == ["reddit", "trustpilot"]
379 assert calls == []
380
381
382 def test_arxiv_backfill_is_unchanged_and_never_probes_trustpilot(monkeypatch):
383 sources, calls = _backfill(["reddit", "arxiv"], monkeypatch, can_run=False)
384 assert sources == ["reddit", "arxiv"]
385 assert calls == []
386
387
388 def test_runbook_describes_host_plan_backfill_honestly():
389 from tests.skill_contract import reference_text
390
391 runbook = reference_text("research-runbook")
392 assert "never expands a narrow list" not in runbook
393 assert "is added to the primary subquery" in runbook
394 assert "`EXCLUDE_SOURCES` or `--search` keeps one out" not in runbook
395 assert "exclusions win." in runbook
396 assert "plus top-level `jobs_queries`: 2-4 product or team terms" in runbook
397 assert "Trustpilot when `trustpilot_can_run` is false" in runbook
398
399
400 def test_search_list_dropping_a_plan_source_warns_once_naming_it(capsys):
401 report, fetched = _run_with_plan(
402 "test topic", plan_with(["reddit", "tiktok"], ["tiktok"]),
403 requested_sources=["reddit", "x"],
404 )
405 assert [sq.label for sq in report.query_plan.subqueries] == ["part-0"]
406 assert "tiktok" not in fetched
407 err = capsys.readouterr().err
408 warnings = [line for line in err.splitlines() if "--search dropped" in line]
409 assert len(warnings) == 1
410 assert "tiktok" in warnings[0]
411 # The subquery whose only source was tiktok is skipped, and the warning
412 # still names tiktok rather than leaving it to the skip line.
413 assert "Skipping external-plan subquery part-1" in err
414
415
416 @pytest.mark.parametrize("plan_sources, config", [
417 # Not installed: the mock run cannot serve stocktwits.
418 (["reddit", "stocktwits"], {}),
419 # Engine-attached lanes.
420 (["reddit", "amazon"], {}),
421 (["reddit", "corpus"], {}),
422 (["reddit", "meta_ads"], {}),
423 # Excluded by the user, not by --search.
424 (["reddit", "tiktok"], {"EXCLUDE_SOURCES": "tiktok"}),
425 ])
426 def test_sources_search_did_not_drop_never_warn(plan_sources, config, capsys):
427 with patch.object(pipeline, "_retrieve_stream", return_value=([], {})):
428 pipeline.run(
429 topic="test topic", config=config, mock=True, web_backend="none",
430 depth="default", requested_sources=["reddit"],
431 external_plan=plan_with(plan_sources),
432 )
433 assert "--search dropped" not in capsys.readouterr().err
434
435
436 def test_unavailable_lanes_do_not_consume_external_plan_slots():
437 raw = plan_with(["instagram"], ["pinterest"], ["reddit"], ["hackernews"])
438 raw["intent"] = "concept"
439 plan = planner._sanitize_plan(
440 raw,
441 "test topic", ["reddit", "hackernews"], None, "default",
442 honor_plan_sources=True,
443 )
444 assert [(query.label, query.sources) for query in plan.subqueries] == [
445 ("part-2", ["reddit"]),
446 ("part-3", ["hackernews"]),
447 ]
448
448 lines PYTHON