返回 last30days-skill
test_eval_harness.py
根目录 / tests / eval / test_eval_harness.py
1 from __future__ import annotations
2
3 import json
4 from copy import deepcopy
5 from unittest import mock
6
7 from . import harness
8
9
10 def test_fixture_matrix_covers_required_topic_archetypes():
11 fixtures = harness.load_fixtures()
12 archetypes = {fixture.manifest["archetype"] for fixture in fixtures}
13
14 assert 6 <= len(fixtures) <= 10
15 assert {
16 "tech-product",
17 "person",
18 "comparison",
19 "breaking-event",
20 "niche",
21 "non-english-cjk",
22 } <= archetypes
23
24
25 def test_research_quality_scores_meet_committed_baselines():
26 results = harness.evaluate_all()
27 print(harness.format_score_table(results))
28
29 failures = harness.baseline_failures(harness.aggregate_scores(results))
30 failures += harness.per_fixture_failures(results)
31 assert not failures, "\n".join(failures)
32
33
34 def test_per_fixture_floor_catches_single_broken_archetype():
35 results = harness.evaluate_all()
36 # Simulate a total clustering failure on one clustered fixture: the
37 # average stays above the aggregate floor but the per-fixture floor fires.
38 broken = None
39 for result in results:
40 if result.fixture.manifest.get("expects_clusters"):
41 result.scores["cluster_coherence"] = 0.0
42 broken = result.fixture.name
43 break
44 assert broken is not None
45 aggregate_ok = not harness.baseline_failures(harness.aggregate_scores(results))
46 per_fixture = harness.per_fixture_failures(results)
47 assert any(f.startswith(f"{broken}/cluster_coherence") for f in per_fixture)
48 # Document why the per-fixture layer exists: with 7 fixtures the aggregate
49 # can absorb one zero.
50 if aggregate_ok:
51 assert per_fixture
52
53
54 def test_entity_overlap_predicate_pinned():
55 # The coherence metric shares extract_text_entities/entity_overlap with
56 # production clustering. Pin the predicate on fixed inputs so a
57 # too-permissive drift is caught independently of the (circular) metric.
58 from lib import entity_extract
59
60 same = entity_extract.entity_overlap(
61 entity_extract.extract_text_entities("OpenAI ships GPT-6 to enterprise customers"),
62 entity_extract.extract_text_entities("Enterprise customers get GPT-6 from OpenAI"),
63 )
64 unrelated = entity_extract.entity_overlap(
65 entity_extract.extract_text_entities("OpenAI ships GPT-6 to enterprise customers"),
66 entity_extract.extract_text_entities("Best sourdough starter recipes for beginners"),
67 )
68 assert same >= harness.ENTITY_OVERLAP_FLOOR, f"related pair fell below floor: {same}"
69 assert unrelated < harness.ENTITY_OVERLAP_FLOOR, (
70 f"unrelated pair passed the overlap floor ({unrelated}); the shared "
71 "predicate got too permissive and the coherence metric is now blind"
72 )
73
74
75 def test_replay_uses_manifest_source_availability(tmp_path):
76 fixture_path = tmp_path / "cli-sources"
77 fixture_path.mkdir()
78 (fixture_path / "http.json").write_text(
79 json.dumps(
80 {
81 "format": "last30days-http-fixture/v1",
82 "exchanges": [],
83 "source_exchanges": [],
84 }
85 ),
86 encoding="utf-8",
87 )
88 fixture = harness.EvalFixture(
89 name="cli-sources",
90 path=fixture_path,
91 manifest={
92 "topic": "fixture topic",
93 "as_of_date": "2026-07-10",
94 "fixture_sources": ["digg", "arxiv", "techmeme", "trustpilot"],
95 "plan": {},
96 },
97 input_urls=frozenset(),
98 )
99
100 def observe_availability(**_kwargs):
101 return harness.pipeline.available_sources({}, fixture.manifest["fixture_sources"])
102
103 with mock.patch.object(harness.pipeline, "run", side_effect=observe_availability), \
104 mock.patch.object(harness.pipeline, "which", return_value=None):
105 available = harness._run_once(fixture)
106
107 assert available == fixture.manifest["fixture_sources"]
108
109
110 def test_intentional_out_of_window_regression_fails_recency_floor():
111 fixture = harness.load_fixtures()[0]
112 result = harness.evaluate_fixture(fixture)
113 regressed = deepcopy(result.report)
114 primary = regressed.ranked_candidates[0].source_items[0]
115 primary.published_at = "2025-01-01"
116
117 scores = harness.score_report(regressed, fixture, deterministic=True)
118 failures = harness.baseline_failures(scores)
119
120 assert scores["recency_compliance"] < 1.0
121 assert any(failure.startswith("recency_compliance:") for failure in failures)
122
123
124 def test_coherence_fails_when_expected_clusters_vanish():
125 fixtures = {f.name: f for f in harness.load_fixtures()}
126 clustered = fixtures["breaking-event"]
127 assert clustered.manifest["expects_clusters"] is True
128 report = harness._run_once(clustered)
129 # Simulate cluster formation regressing to singletons.
130 report.clusters = []
131 assert harness._cluster_coherence(report, clustered) == 0.0
132
133
134 def test_coherence_allows_singletons_for_sparse_fixtures():
135 fixtures = {f.name: f for f in harness.load_fixtures()}
136 sparse = fixtures["niche"]
137 assert sparse.manifest.get("expects_clusters") is False
138 report = harness._run_once(sparse)
139 report.clusters = []
140 assert harness._cluster_coherence(report, sparse) == 1.0
141
142
143 def test_enrichment_replay_merges_metadata_without_replacing_items():
144 import sys
145 sys.path.insert(0, "skills/last30days/scripts")
146 from lib import pipeline, schema
147
148 fresh = schema.SourceItem(
149 item_id="yt-1",
150 source="youtube",
151 title="Fresh title from current normalization",
152 body="fresh body",
153 url="https://youtube.com/watch?v=1",
154 published_at="2026-07-01",
155 snippet="fresh snippet",
156 engagement={"views": 10},
157 metadata={"channel": "fresh-channel"},
158 )
159 replayed = [{
160 "item_id": "yt-1",
161 "title": "STALE fixture title",
162 "snippet": "STALE snippet",
163 "metadata": {"transcript_snippet": "recorded transcript"},
164 }]
165 merged = pipeline._merge_replayed_enrichment([fresh], replayed)
166 assert merged[0].title == "Fresh title from current normalization"
167 assert merged[0].snippet == "fresh snippet"
168 assert merged[0].metadata["transcript_snippet"] == "recorded transcript"
169 assert merged[0].metadata["channel"] == "fresh-channel"
170
171
172 def test_star_enrichment_apply_map_offline():
173 import sys
174 sys.path.insert(0, "skills/last30days/scripts")
175 from lib import github, schema
176
177 candidate = schema.Candidate(
178 candidate_id="c-gh",
179 item_id="gh-1",
180 source="github",
181 title="repo mvanhorn/last30days-skill discussion",
182 url="https://github.com/mvanhorn/last30days-skill",
183 snippet="s",
184 subquery_labels=["primary"],
185 native_ranks={"primary:github": 1},
186 local_relevance=0.9,
187 freshness=90,
188 engagement=10,
189 source_quality=0.5,
190 rrf_score=0.1,
191 final_score=90,
192 cluster_id="cl",
193 source_items=[],
194 metadata={},
195 )
196 enriched = github.apply_star_map(
197 [candidate], {"mvanhorn/last30days-skill": 51436}
198 )
199 assert enriched == 1
200 assert candidate.metadata["github_stars"]["mvanhorn/last30days-skill"] == 51436
201
202
203 def test_hn_comment_replay_follows_firebase_kids_order(tmp_path):
204 source = next(f for f in harness.load_fixtures() if f.name == "breaking-event")
205 payload = json.loads((source.path / "http.json").read_text(encoding="utf-8"))
206 story_id = "breaking-event-hn-1"
207 algolia_children = [
208 {"id": 41000101, "author": "posted_first", "text": "<p>First reply.</p>", "points": None},
209 {"id": 41000102, "author": "posted_second", "text": "<p>Second reply.</p>", "points": None},
210 {"id": 41000103, "author": "posted_third", "text": "<p>Third reply.</p>", "points": None},
211 ]
212 kids = [41000103, 41000101, 41000102]
213 patched = {"algolia": False, "firebase": False}
214 for exchange in payload["exchanges"]:
215 url = exchange["request"]["url"]
216 if url == f"https://hn.algolia.com/api/v1/items/{story_id}":
217 exchange["response"]["value"]["children"] = algolia_children
218 patched["algolia"] = True
219 elif url == f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json":
220 exchange["response"]["value"]["kids"] = kids
221 patched["firebase"] = True
222 assert patched == {"algolia": True, "firebase": True}
223 fixture_path = tmp_path / source.name
224 fixture_path.mkdir()
225 (fixture_path / "http.json").write_text(json.dumps(payload), encoding="utf-8")
226 fixture = harness.EvalFixture(
227 name=source.name,
228 path=fixture_path,
229 manifest=deepcopy(source.manifest),
230 input_urls=source.input_urls,
231 )
232
233 report = harness._run_once(fixture)
234
235 story = next(
236 item for item in report.items_by_source["hackernews"]
237 if item.item_id == story_id
238 )
239 assert [c["author"] for c in story.metadata["top_comments"]] == [
240 "posted_third",
241 "posted_first",
242 "posted_second",
243 ]
244
245
246 def test_digg_story_sources_confirm_matching_x_and_hacker_news_items():
247 [fixture] = [f for f in harness.load_fixtures() if f.name == "digg-confirmation"]
248 report = harness.evaluate_fixture(fixture).report
249 by_url = {candidate.url: candidate for candidate in report.ranked_candidates}
250
251 def story_of(url):
252 return (by_url[url].metadata.get("digg_story") or {}).get("url")
253
254 # Sources of a fetched story, in URL forms that differ from Digg's.
255 assert story_of("https://x.com/i/status/1940000000000000101") == "https://digg.com/ai/ljvbajl5"
256 assert story_of(
257 "https://x.com/Fixture_PHPDev/status/1940000000000000202?s=20"
258 ) == "https://digg.com/ai/1i79b1xh"
259 assert story_of(
260 "https://www.news.example.test/digg-confirmation/openai-lean-proofs/?utm_source=hn"
261 ) == "https://digg.com/ai/ljvbajl5"
262 # Same author topic, same site, or same subject, but not a story source.
263 for url in (
264 "https://x.com/fixture_onlooker/status/1940000000000000901",
265 "https://x.com/fixture_pricing/status/1940000000000000902",
266 "https://news.example.test/digg-confirmation/openai-lean-explainer",
267 "https://benchmarks.example.test/digg-confirmation/openai-terra",
268 ):
269 assert story_of(url) is None, url
270 # Each confirmed post outranks its unconfirmed twin, which has the same
271 # engagement and date.
272 assert (
273 by_url["https://x.com/i/status/1940000000000000101"].final_score
274 > by_url["https://x.com/fixture_onlooker/status/1940000000000000901"].final_score
275 )
276 proofs_story = next(
277 item for item in report.items_by_source["digg"] if item.item_id == "ljvbajl5"
278 )
279 assert len(proofs_story.metadata["posts"]) == 5
280
281
282 def test_digg_bar_drops_off_topic_and_leads_with_biggest_on_topic_story():
283 [fixture] = [f for f in harness.load_fixtures() if f.name == "digg-confirmation"]
284 report = harness.evaluate_fixture(fixture).report
285 digg_ids = {item.item_id for item in report.items_by_source["digg"]}
286 by_url = {candidate.url: candidate for candidate in report.ranked_candidates}
287
288 # A 652-score sports story that never mentions OpenAI.
289 assert "q4rk8tzn" not in digg_ids
290 assert "https://digg.com/sports/q4rk8tzn" not in by_url
291
292 # The report's Digg items are re-sorted at the end of the run, so the
293 # order Digg's stream went into ranking is read from each story's rank
294 # in that stream. The story recorded last is also the oldest, so local
295 # ranking alone would put it last. It has the highest Digg Score of the
296 # stories whose title names OpenAI, and the other big ones follow by score.
297 stream = sorted(
298 (candidate for candidate in report.ranked_candidates if candidate.source == "digg"),
299 key=lambda candidate: candidate.native_ranks["primary:digg"],
300 )
301 assert [candidate.item_id for candidate in stream[:6]] == [
302 "b9ds3fua", # 1502
303 "ljvbajl5", # 1286
304 "1i79b1xh", # 473
305 "x7hzsqzf", # 239
306 "en0dbdyl", # 226
307 "wo3n9meb", # 180
308 ]
309 assert stream[0].native_ranks["primary:digg"] == 1
310 # Kept, but behind them: it names OpenAI in the title with a Digg Score
311 # of 38 and 3 sources.
312 assert [candidate.item_id for candidate in stream[6:]] == ["mtdi1c95"]
313
314 # A 310-score story that names OpenAI only in its summary. A summary-only
315 # mention is dropped, however big the story is.
316 assert "h2vy6wpc" not in digg_ids
317 assert "https://digg.com/ai/h2vy6wpc" not in by_url
318 # Its recorded sources include a Hacker News link and an X post that are
319 # in this report. Its sources are not read, so those two results carry
320 # no Digg story.
321 for url in (
322 "https://benchmarks.example.test/digg-confirmation/openai-terra",
323 "https://x.com/fixture_pricing/status/1940000000000000902",
324 ):
325 assert by_url[url].metadata.get("digg_story") is None, url
326
327
328 def test_entity_markets_lead_with_the_teams_title_odds():
329 [fixture] = [f for f in harness.load_fixtures() if f.name == "entity-markets"]
330 report = harness.evaluate_fixture(fixture).report
331 markets = sorted(
332 report.items_by_source["polymarket"],
333 key=lambda item: item.metadata["selection_score"],
334 reverse=True,
335 )
336
337 # "Pro Football: 2027 Champion" never names the 49ers in its title; the
338 # 49ers are one of its 32 outcomes, and the favorite.
339 champion = markets[0]
340 assert champion.title == "Pro Football: 2027 Champion"
341 matched = champion.metadata["matched_market"]
342 assert matched["label"] == "San Francisco 49ers"
343 assert (matched["rank"], matched["race_size"]) == (1, 32)
344 assert champion.metadata["headline"]["question"] == (
345 "Will the San Francisco 49ers win the 2027 NFL league championship?"
346 )
347 # Every market shown names the 49ers in its own question or label.
348 for item in markets:
349 text = f"{item.metadata['matched_market']['question']} {item.metadata['matched_market']['label']}"
350 assert "49ers" in text, item.title
351
351 lines PYTHON