| 1 | """Regression tests for PR 28: pipeline weighting/X-floor/SSH-ytdlp, fetch_memo lifecycle, schema & dates. |
| 2 | |
| 3 | Covers HIGH-014, HIGH-019, HIGH-022, HIGH-023, HIGH-031, HIGH-033, HIGH-034, HIGH-035. |
| 4 | """ |
| 5 | |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | from concurrent.futures import ThreadPoolExecutor |
| 9 | from datetime import datetime, timezone |
| 10 | import os |
| 11 | import threading |
| 12 | from unittest import mock |
| 13 | |
| 14 | import pytest |
| 15 | |
| 16 | from lib import ( |
| 17 | dates, |
| 18 | fanout, |
| 19 | fetch_memo, |
| 20 | grounding, |
| 21 | health, |
| 22 | pipeline, |
| 23 | schema, |
| 24 | youtube_yt, |
| 25 | ) |
| 26 | |
| 27 | |
| 28 | def _make_runtime() -> schema.ProviderRuntime: |
| 29 | return schema.ProviderRuntime( |
| 30 | reasoning_provider="local", |
| 31 | planner_model="local", |
| 32 | rerank_model="local", |
| 33 | ) |
| 34 | |
| 35 | |
| 36 | def _make_plan( |
| 37 | sources: list[str], |
| 38 | *, |
| 39 | num_subqueries: int = 1, |
| 40 | normalized: bool = True, |
| 41 | ) -> schema.QueryPlan: |
| 42 | sq_weight = (1.0 / num_subqueries) if normalized else 1.0 |
| 43 | subqueries = [ |
| 44 | schema.SubQuery( |
| 45 | label=f"sq{i + 1}", |
| 46 | search_query=f"topic angle {i + 1}", |
| 47 | ranking_query=f"topic angle {i + 1}", |
| 48 | sources=list(sources), |
| 49 | weight=sq_weight, |
| 50 | ) |
| 51 | for i in range(num_subqueries) |
| 52 | ] |
| 53 | src_weight = (1.0 / len(sources)) if (normalized and sources) else 1.0 |
| 54 | return schema.QueryPlan( |
| 55 | intent="general", |
| 56 | freshness_mode="balanced_recent", |
| 57 | cluster_mode="story", |
| 58 | raw_topic="Acme Corp", |
| 59 | subqueries=subqueries, |
| 60 | source_weights={source: src_weight for source in sources}, |
| 61 | ) |
| 62 | |
| 63 | |
| 64 | def _make_report( |
| 65 | *, |
| 66 | subqueries: list[schema.SubQuery], |
| 67 | source_weights: dict[str, float], |
| 68 | ranked_candidates: list[schema.Candidate], |
| 69 | clusters: list[schema.Cluster], |
| 70 | items_by_source: dict[str, list[schema.SourceItem]], |
| 71 | artifacts: dict | None = None, |
| 72 | source_status: dict[str, schema.SourceOutcome] | None = None, |
| 73 | ) -> schema.Report: |
| 74 | return schema.Report( |
| 75 | topic="Acme rollout", |
| 76 | range_from="2026-03-01", |
| 77 | range_to="2026-03-31", |
| 78 | generated_at="2026-03-31T12:00:00Z", |
| 79 | provider_runtime=_make_runtime(), |
| 80 | query_plan=schema.QueryPlan( |
| 81 | intent="general", |
| 82 | freshness_mode="balanced_recent", |
| 83 | cluster_mode="story", |
| 84 | raw_topic="Acme rollout", |
| 85 | subqueries=subqueries, |
| 86 | source_weights=source_weights, |
| 87 | ), |
| 88 | clusters=clusters, |
| 89 | ranked_candidates=ranked_candidates, |
| 90 | items_by_source=items_by_source, |
| 91 | errors_by_source={}, |
| 92 | source_status=source_status or {}, |
| 93 | artifacts=artifacts or {}, |
| 94 | ) |
| 95 | |
| 96 | |
| 97 | # --------------------------------------------------------------------------- |
| 98 | # HIGH-014: fetch_memo lifecycle resets & bounded LRU eviction |
| 99 | # --------------------------------------------------------------------------- |
| 100 | |
| 101 | |
| 102 | class TestHigh014FetchMemoLifecycleAndEviction: |
| 103 | def test_pipeline_run_isolates_fetch_memo_standalone_and_shares_internal_subrun(self): |
| 104 | # Populate the ambient default store before any run starts. |
| 105 | fetch_memo.fetch_once(("x", "stale-key"), lambda: {"gen": "ambient"}, timeout=1) |
| 106 | assert ("x", "stale-key") in fetch_memo._CACHE |
| 107 | |
| 108 | plan = { |
| 109 | "intent": "general", |
| 110 | "freshness_mode": "balanced_recent", |
| 111 | "cluster_mode": "story", |
| 112 | "subqueries": [ |
| 113 | { |
| 114 | "label": "primary", |
| 115 | "search_query": "test topic", |
| 116 | "ranking_query": "test topic", |
| 117 | "sources": ["reddit"], |
| 118 | } |
| 119 | ], |
| 120 | "source_weights": {"reddit": 1.0}, |
| 121 | } |
| 122 | seen_standalone: list[dict] = [] |
| 123 | |
| 124 | def _retrieve_standalone(**_kwargs): |
| 125 | seen_standalone.append( |
| 126 | fetch_memo.fetch_once(("x", "stale-key"), lambda: {"gen": "fresh"}, timeout=1) |
| 127 | ) |
| 128 | return [], {} |
| 129 | |
| 130 | # Standalone run enters an isolated run_scope: it fetches fresh instead |
| 131 | # of seeing the ambient entry AND does not wipe the ambient store. |
| 132 | with mock.patch.object(pipeline, "_retrieve_stream", side_effect=_retrieve_standalone): |
| 133 | pipeline.run( |
| 134 | topic="test topic", |
| 135 | config={}, |
| 136 | depth="quick", |
| 137 | requested_sources=["reddit"], |
| 138 | mock=True, |
| 139 | external_plan=plan, |
| 140 | web_backend="none", |
| 141 | internal_subrun=False, |
| 142 | ) |
| 143 | assert seen_standalone == [{"gen": "fresh"}] |
| 144 | assert fetch_memo._CACHE[("x", "stale-key")] == {"gen": "ambient"} |
| 145 | |
| 146 | # Internal subrun shares the caller's active run_scope. |
| 147 | seen_subrun: list[dict] = [] |
| 148 | |
| 149 | def _retrieve_subrun(**_kwargs): |
| 150 | seen_subrun.append( |
| 151 | fetch_memo.fetch_once( |
| 152 | ("x", "shared-in-run"), lambda: {"gen": "should-not-run"}, timeout=1 |
| 153 | ) |
| 154 | ) |
| 155 | return [], {} |
| 156 | |
| 157 | with fetch_memo.run_scope(): |
| 158 | fetch_memo.fetch_once(("x", "shared-in-run"), lambda: {"gen": "shared"}, timeout=1) |
| 159 | with mock.patch.object(pipeline, "_retrieve_stream", side_effect=_retrieve_subrun): |
| 160 | pipeline.run( |
| 161 | topic="test topic", |
| 162 | config={}, |
| 163 | depth="quick", |
| 164 | requested_sources=["reddit"], |
| 165 | mock=True, |
| 166 | external_plan=plan, |
| 167 | web_backend="none", |
| 168 | internal_subrun=True, |
| 169 | ) |
| 170 | assert seen_subrun == [{"gen": "shared"}] |
| 171 | |
| 172 | def test_concurrent_overlapping_pipeline_runs_isolate_fetch_memo_and_sequential_start_fresh(self): |
| 173 | plan = { |
| 174 | "intent": "general", |
| 175 | "freshness_mode": "balanced_recent", |
| 176 | "cluster_mode": "story", |
| 177 | "subqueries": [ |
| 178 | { |
| 179 | "label": "sq1", |
| 180 | "search_query": "topic", |
| 181 | "ranking_query": "topic", |
| 182 | "sources": ["reddit"], |
| 183 | } |
| 184 | ], |
| 185 | "source_weights": {"reddit": 1.0}, |
| 186 | } |
| 187 | both_started = threading.Barrier(2, timeout=5) |
| 188 | b_finished = threading.Event() |
| 189 | fetch_counts = {"A": 0, "B": 0, "C": 0} |
| 190 | lock = threading.Lock() |
| 191 | observed: dict[str, list[dict]] = {"A": [], "B": [], "C": []} |
| 192 | |
| 193 | def _retrieve(**kwargs): |
| 194 | run_id = kwargs["topic"] |
| 195 | |
| 196 | def _fetch(): |
| 197 | with lock: |
| 198 | fetch_counts[run_id] += 1 |
| 199 | return {"run": run_id, "n": fetch_counts[run_id]} |
| 200 | |
| 201 | first = fetch_memo.fetch_once(("shared", "key"), _fetch, timeout=5) |
| 202 | observed[run_id].append(first) |
| 203 | if run_id in ("A", "B"): |
| 204 | both_started.wait() |
| 205 | if run_id == "A": |
| 206 | # Wait until concurrent run B has populated its own scope and exited. |
| 207 | assert b_finished.wait(timeout=5) |
| 208 | # Second lookup inside the same run must still hit this run's own entry |
| 209 | # (neither cleared nor overwritten by the overlapping run). |
| 210 | second = fetch_memo.fetch_once(("shared", "key"), _fetch, timeout=5) |
| 211 | observed[run_id].append(second) |
| 212 | return [], {} |
| 213 | |
| 214 | def _invoke(run_id: str) -> None: |
| 215 | pipeline.run( |
| 216 | topic=run_id, |
| 217 | config={}, |
| 218 | depth="quick", |
| 219 | requested_sources=["reddit"], |
| 220 | mock=True, |
| 221 | external_plan=plan, |
| 222 | web_backend="none", |
| 223 | internal_subrun=False, |
| 224 | ) |
| 225 | if run_id == "B": |
| 226 | b_finished.set() |
| 227 | |
| 228 | with mock.patch.object(pipeline, "_retrieve_stream", side_effect=_retrieve): |
| 229 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 230 | fa = pool.submit(_invoke, "A") |
| 231 | fb = pool.submit(_invoke, "B") |
| 232 | fa.result(timeout=10) |
| 233 | fb.result(timeout=10) |
| 234 | # Sequential run C starts fresh without seeing A or B's entries. |
| 235 | _invoke("C") |
| 236 | |
| 237 | assert fetch_counts == {"A": 1, "B": 1, "C": 1} |
| 238 | assert observed["A"] == [{"run": "A", "n": 1}, {"run": "A", "n": 1}] |
| 239 | assert observed["B"] == [{"run": "B", "n": 1}, {"run": "B", "n": 1}] |
| 240 | assert observed["C"] == [{"run": "C", "n": 1}] |
| 241 | |
| 242 | def test_competitor_fanout_scopes_fetch_memo_for_parallel_subruns_without_wiping_ambient(self): |
| 243 | stale_calls = 0 |
| 244 | |
| 245 | def _stale(): |
| 246 | nonlocal stale_calls |
| 247 | stale_calls += 1 |
| 248 | return {"gen": "stale"} |
| 249 | |
| 250 | fetch_memo.fetch_once(("digg", "shared"), _stale, timeout=1) |
| 251 | assert stale_calls == 1 |
| 252 | |
| 253 | fresh_calls = 0 |
| 254 | barrier = threading.Barrier(2, timeout=5) |
| 255 | dummy_report = _make_report( |
| 256 | subqueries=[ |
| 257 | schema.SubQuery( |
| 258 | label="p", search_query="q", ranking_query="q", sources=["reddit"], |
| 259 | ) |
| 260 | ], |
| 261 | source_weights={"reddit": 1.0}, |
| 262 | ranked_candidates=[], |
| 263 | clusters=[], |
| 264 | items_by_source={}, |
| 265 | ) |
| 266 | |
| 267 | def _fresh(): |
| 268 | nonlocal fresh_calls |
| 269 | fresh_calls += 1 |
| 270 | return {"gen": "fresh"} |
| 271 | |
| 272 | def _subrun(_entity=None): |
| 273 | barrier.wait() |
| 274 | val = fetch_memo.fetch_once(("digg", "shared"), _fresh, timeout=5) |
| 275 | assert val == {"gen": "fresh"} |
| 276 | return dummy_report |
| 277 | |
| 278 | results = fanout.run_competitor_fanout( |
| 279 | main_topic="Alpha", |
| 280 | main_runner=_subrun, |
| 281 | competitors=["Beta"], |
| 282 | competitor_runner=_subrun, |
| 283 | ) |
| 284 | assert len(results) == 2 |
| 285 | # Parallel subruns ignored stale ambient entry and coalesced onto one fresh fetch. |
| 286 | assert fresh_calls == 1 |
| 287 | # Ambient store outside fanout was never wiped. |
| 288 | assert fetch_memo._CACHE[("digg", "shared")] == {"gen": "stale"} |
| 289 | |
| 290 | def test_enrich_nominations_scopes_fetch_memo_across_subruns(self): |
| 291 | fetch_memo.fetch_once(("polymarket", "stale"), lambda: {"old": 1}, timeout=1) |
| 292 | assert ("polymarket", "stale") in fetch_memo._CACHE |
| 293 | |
| 294 | fresh_calls = 0 |
| 295 | seen: list[dict] = [] |
| 296 | |
| 297 | def _fresh(): |
| 298 | nonlocal fresh_calls |
| 299 | fresh_calls += 1 |
| 300 | return {"fresh": fresh_calls} |
| 301 | |
| 302 | def _fake_run(**_kwargs): |
| 303 | seen.append(fetch_memo.fetch_once(("polymarket", "stale"), _fresh, timeout=5)) |
| 304 | return _make_report( |
| 305 | subqueries=[ |
| 306 | schema.SubQuery( |
| 307 | label="p", search_query="q", ranking_query="q", sources=["reddit"], |
| 308 | ) |
| 309 | ], |
| 310 | source_weights={"reddit": 1.0}, |
| 311 | ranked_candidates=[], |
| 312 | clusters=[], |
| 313 | items_by_source={}, |
| 314 | ) |
| 315 | |
| 316 | nominations = [ |
| 317 | pipeline.Nomination(name="Nom 1", seed_score=50.0, items=[], summary="s1"), |
| 318 | pipeline.Nomination(name="Nom 2", seed_score=40.0, items=[], summary="s2"), |
| 319 | ] |
| 320 | with mock.patch.object(pipeline, "run", side_effect=_fake_run): |
| 321 | enriched = pipeline.enrich_nominations( |
| 322 | nominations, config={}, mock=True, max_workers=1, |
| 323 | ) |
| 324 | assert len(enriched) == 2 |
| 325 | # Both nominations shared one fresh fetch in the batch scope (ignoring ambient stale). |
| 326 | assert fresh_calls == 1 |
| 327 | assert seen == [{"fresh": 1}, {"fresh": 1}] |
| 328 | assert fetch_memo._CACHE[("polymarket", "stale")] == {"old": 1} |
| 329 | |
| 330 | def test_discovery_sweep_isolates_fetch_memo(self): |
| 331 | fetch_memo.fetch_once(("x", "old-sweep"), lambda: {"old": True}, timeout=1) |
| 332 | assert ("x", "old-sweep") in fetch_memo._CACHE |
| 333 | |
| 334 | seen: list[dict] = [] |
| 335 | |
| 336 | def _fake_fetch(*_args, **_kwargs): |
| 337 | seen.append( |
| 338 | fetch_memo.fetch_once(("x", "old-sweep"), lambda: {"old": False}, timeout=1) |
| 339 | ) |
| 340 | return [], None |
| 341 | |
| 342 | with mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=_fake_fetch): |
| 343 | pipeline.run_discover_nominate( |
| 344 | domain="ai", |
| 345 | config={}, |
| 346 | requested_sources=["reddit"], |
| 347 | mock=True, |
| 348 | ) |
| 349 | assert seen == [{"old": False}] |
| 350 | assert fetch_memo._CACHE[("x", "old-sweep")] == {"old": True} |
| 351 | |
| 352 | def test_lru_eviction_bounds_cache_and_keeps_recently_used_entries(self, monkeypatch): |
| 353 | monkeypatch.setattr(fetch_memo, "MAX_ENTRIES", 3) |
| 354 | calls: dict[str, int] = {} |
| 355 | |
| 356 | def _fetch(name: str): |
| 357 | def _inner(): |
| 358 | calls[name] = calls.get(name, 0) + 1 |
| 359 | return {"k": name, "n": calls[name]} |
| 360 | return _inner |
| 361 | |
| 362 | fetch_memo.fetch_once("k1", _fetch("k1"), timeout=1) |
| 363 | fetch_memo.fetch_once("k2", _fetch("k2"), timeout=1) |
| 364 | fetch_memo.fetch_once("k3", _fetch("k3"), timeout=1) |
| 365 | # Touch k1 so k2 becomes the least-recently-used entry. |
| 366 | assert fetch_memo.fetch_once("k1", _fetch("k1"), timeout=1) == {"k": "k1", "n": 1} |
| 367 | fetch_memo.fetch_once("k4", _fetch("k4"), timeout=1) |
| 368 | |
| 369 | assert len(fetch_memo._CACHE) == 3 |
| 370 | assert "k2" not in fetch_memo._CACHE |
| 371 | assert list(fetch_memo._CACHE.keys()) == ["k3", "k1", "k4"] |
| 372 | # Evicted k2 refetches; retained k1 serves from cache. |
| 373 | assert fetch_memo.fetch_once("k1", _fetch("k1"), timeout=1) == {"k": "k1", "n": 1} |
| 374 | assert fetch_memo.fetch_once("k2", _fetch("k2"), timeout=1) == {"k": "k2", "n": 2} |
| 375 | assert len(fetch_memo._CACHE) == 3 |
| 376 | |
| 377 | def test_reset_and_eviction_preserve_inflight_singleflight_safety(self, monkeypatch): |
| 378 | monkeypatch.setattr(fetch_memo, "MAX_ENTRIES", 2) |
| 379 | owner_entered = threading.Event() |
| 380 | release_owner = threading.Event() |
| 381 | |
| 382 | def _slow_owner(): |
| 383 | owner_entered.set() |
| 384 | release_owner.wait(timeout=5) |
| 385 | return {"version": "old-inflight"} |
| 386 | |
| 387 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 388 | f_owner = pool.submit(fetch_memo.fetch_once, "shared", _slow_owner, timeout=5) |
| 389 | assert owner_entered.wait(timeout=5) |
| 390 | waiter_waiting = threading.Event() |
| 391 | with fetch_memo._LOCK: |
| 392 | live_slot = fetch_memo._INFLIGHT["shared"] |
| 393 | real_wait = live_slot.event.wait |
| 394 | |
| 395 | def _observed_wait(timeout=None): |
| 396 | waiter_waiting.set() |
| 397 | return real_wait(timeout) |
| 398 | |
| 399 | live_slot.event.wait = _observed_wait |
| 400 | f_waiter = pool.submit( |
| 401 | fetch_memo.fetch_once, "shared", lambda: {"version": "unused"}, timeout=5, |
| 402 | ) |
| 403 | assert waiter_waiting.wait(timeout=5) |
| 404 | |
| 405 | fetch_memo.reset() |
| 406 | # Fill cache past MAX_ENTRIES after reset while old owner is still running. |
| 407 | fetch_memo.fetch_once("a", lambda: 1, timeout=1) |
| 408 | fetch_memo.fetch_once("b", lambda: 2, timeout=1) |
| 409 | fetch_memo.fetch_once("c", lambda: 3, timeout=1) |
| 410 | assert len(fetch_memo._CACHE) == 2 |
| 411 | |
| 412 | release_owner.set() |
| 413 | assert f_owner.result(timeout=5) == {"version": "old-inflight"} |
| 414 | assert f_waiter.result(timeout=5) == {"version": "old-inflight"} |
| 415 | |
| 416 | # Stale owner must not have polluted the post-reset cache. |
| 417 | assert "shared" not in fetch_memo._CACHE |
| 418 | assert fetch_memo.fetch_once("shared", lambda: {"version": "fresh"}, timeout=1) == { |
| 419 | "version": "fresh", |
| 420 | } |
| 421 | |
| 422 | |
| 423 | # --------------------------------------------------------------------------- |
| 424 | # HIGH-019: Deferred X relevance floor consistency across streams & merged view |
| 425 | # --------------------------------------------------------------------------- |
| 426 | |
| 427 | |
| 428 | class TestHigh019DeferredXRelevanceFloorConsistency: |
| 429 | def _run_x_floor_pipeline( |
| 430 | self, |
| 431 | stream_by_label: dict[str, list[dict]], |
| 432 | *, |
| 433 | topic: str = "Acme launch @acmedev", |
| 434 | x_handle: str = "acmedev", |
| 435 | ) -> tuple[schema.Report, dict[tuple[str, str], list[schema.SourceItem]]]: |
| 436 | plan = { |
| 437 | "intent": "general", |
| 438 | "freshness_mode": "balanced_recent", |
| 439 | "cluster_mode": "story", |
| 440 | "subqueries": [ |
| 441 | { |
| 442 | "label": label, |
| 443 | "search_query": f"acme {label}", |
| 444 | "ranking_query": f"acme {label} benchmark release", |
| 445 | "sources": ["x"], |
| 446 | } |
| 447 | for label in stream_by_label |
| 448 | ], |
| 449 | "source_weights": {"x": 1.0}, |
| 450 | } |
| 451 | |
| 452 | def _fake_retrieve(**kwargs): |
| 453 | label = kwargs["subquery"].label |
| 454 | return list(stream_by_label.get(label, [])), {} |
| 455 | |
| 456 | with mock.patch.object(pipeline, "_retrieve_stream", side_effect=_fake_retrieve), \ |
| 457 | mock.patch.object(pipeline, "_retry_thin_sources"), \ |
| 458 | mock.patch.object(pipeline, "_run_supplemental_searches"), \ |
| 459 | mock.patch.object(pipeline, "weighted_rrf", wraps=pipeline.weighted_rrf) as fuse: |
| 460 | report = pipeline.run( |
| 461 | topic=topic, |
| 462 | config={}, |
| 463 | depth="default", |
| 464 | requested_sources=["x"], |
| 465 | mock=True, |
| 466 | x_handle=x_handle, |
| 467 | external_plan=plan, |
| 468 | web_backend="none", |
| 469 | as_of_date="2026-03-31", |
| 470 | ) |
| 471 | return report, fuse.call_args.args[0] |
| 472 | |
| 473 | def test_weak_subquery_does_not_leak_dropped_posts_into_fusion(self): |
| 474 | # sq1 has only an off-topic zero-engagement post that fails the X floor. |
| 475 | # sq2 has an on-topic post by the resolved subject handle that passes. |
| 476 | weak_post = { |
| 477 | "id": "X-weak", |
| 478 | "text": "random unrelated sandwich lunch photo", |
| 479 | "author_handle": "bystander", |
| 480 | "url": "https://x.com/bystander/status/1001", |
| 481 | "date": "2026-03-30", |
| 482 | "engagement": {"likes": 0, "reposts": 0, "replies": 0}, |
| 483 | } |
| 484 | strong_post = { |
| 485 | "id": "X-strong", |
| 486 | "text": "Acme benchmark release shipped today with 2x speedup", |
| 487 | "author_handle": "acmedev", |
| 488 | "url": "https://x.com/acmedev/status/2002", |
| 489 | "date": "2026-03-30", |
| 490 | "engagement": {"likes": 250, "reposts": 40, "replies": 15}, |
| 491 | } |
| 492 | |
| 493 | report, fused_streams = self._run_x_floor_pipeline( |
| 494 | {"sq1": [weak_post], "sq2": [strong_post]}, |
| 495 | ) |
| 496 | |
| 497 | assert fused_streams.get(("sq1", "x")) == [] |
| 498 | assert [i.url for i in fused_streams.get(("sq2", "x"), [])] == [ |
| 499 | "https://x.com/acmedev/status/2002" |
| 500 | ] |
| 501 | report_urls = {item.url for item in report.items_by_source.get("x", [])} |
| 502 | candidate_urls = {cand.url for cand in report.ranked_candidates} |
| 503 | assert report_urls == {"https://x.com/acmedev/status/2002"} |
| 504 | assert candidate_urls == report_urls |
| 505 | assert report.source_status["x"].items_returned == 1 |
| 506 | |
| 507 | def test_all_fail_rescue_stays_consistent_across_both_views(self): |
| 508 | # Both posts fail the deferred X relevance/engagement floor (zero |
| 509 | # engagement + low overlap with the ranking query), triggering the |
| 510 | # all-fail rescue consistently across merged and per-query views. |
| 511 | weak_1 = { |
| 512 | "id": "X-w1", |
| 513 | "text": "acme coffee mug sitting quietly beside breakfast sandwich photo", |
| 514 | "author_handle": "user1", |
| 515 | "url": "https://x.com/user1/status/3001", |
| 516 | "date": "2026-03-30", |
| 517 | "engagement": {"likes": 0, "reposts": 0, "replies": 0}, |
| 518 | } |
| 519 | weak_2 = { |
| 520 | "id": "X-w2", |
| 521 | "text": "acme umbrella weather forecast drizzle walking downtown afternoon", |
| 522 | "author_handle": "user2", |
| 523 | "url": "https://x.com/user2/status/3002", |
| 524 | "date": "2026-03-30", |
| 525 | "engagement": {"likes": 0, "reposts": 0, "replies": 0}, |
| 526 | } |
| 527 | |
| 528 | report, fused_streams = self._run_x_floor_pipeline({"sq1": [weak_1], "sq2": [weak_2]}) |
| 529 | |
| 530 | # Confirm the posts genuinely failed the floor (rescued, not passed). |
| 531 | from lib import signals |
| 532 | assert signals.prune_low_relevance( |
| 533 | report.items_by_source["x"], |
| 534 | first_party_handles={"acmedev"}, |
| 535 | passing_only=True, |
| 536 | ) == [] |
| 537 | |
| 538 | fused_urls = { |
| 539 | item.url for stream in fused_streams.values() for item in stream |
| 540 | } |
| 541 | report_urls = {item.url for item in report.items_by_source.get("x", [])} |
| 542 | candidate_urls = {cand.url for cand in report.ranked_candidates} |
| 543 | expected = { |
| 544 | "https://x.com/user1/status/3001", |
| 545 | "https://x.com/user2/status/3002", |
| 546 | } |
| 547 | assert fused_urls == expected |
| 548 | assert report_urls == expected |
| 549 | assert candidate_urls == expected |
| 550 | assert report.source_status["x"].items_returned == 2 |
| 551 | |
| 552 | def test_duplicate_empty_url_item_id_does_not_collide_during_stream_sync(self): |
| 553 | # Two distinct posts with empty URL and identical item_id across streams: |
| 554 | # sq1's fails the floor, sq2's passes (authored by resolved handle). |
| 555 | weak_no_url = { |
| 556 | "id": "dup-id", |
| 557 | "text": "unrelated noise text", |
| 558 | "author_handle": "stranger", |
| 559 | "url": "", |
| 560 | "date": "2026-03-30", |
| 561 | "engagement": {"likes": 0}, |
| 562 | } |
| 563 | strong_no_url = { |
| 564 | "id": "dup-id", |
| 565 | "text": "Acme release announcement benchmark notes", |
| 566 | "author_handle": "acmedev", |
| 567 | "url": "", |
| 568 | "date": "2026-03-30", |
| 569 | "engagement": {"likes": 120}, |
| 570 | } |
| 571 | |
| 572 | report, fused_streams = self._run_x_floor_pipeline( |
| 573 | {"sq1": [weak_no_url], "sq2": [strong_no_url]}, |
| 574 | ) |
| 575 | |
| 576 | assert fused_streams.get(("sq1", "x")) == [] |
| 577 | assert len(fused_streams.get(("sq2", "x"), [])) == 1 |
| 578 | x_items = report.items_by_source.get("x", []) |
| 579 | assert len(x_items) == 1 |
| 580 | assert x_items[0].author == "acmedev" |
| 581 | assert len(report.ranked_candidates) == 1 |
| 582 | assert report.ranked_candidates[0].subquery_labels == ["sq2"] |
| 583 | assert report.source_status["x"].items_returned == 1 |
| 584 | |
| 585 | def test_duplicate_url_failing_in_one_subquery_does_not_survive_in_that_stream(self): |
| 586 | # Same URL retrieved in sq1 (off-topic text/low relevance) and sq2 (authored by |
| 587 | # resolved subject handle so it passes). Only sq2's surviving copy enters fusion. |
| 588 | shared_url = "https://x.com/shared/status/4004" |
| 589 | failing_copy = { |
| 590 | "id": "X-4004", |
| 591 | "text": "completely unrelated lunch photo", |
| 592 | "author_handle": "bystander", |
| 593 | "url": shared_url, |
| 594 | "date": "2026-03-30", |
| 595 | "engagement": {"likes": 0}, |
| 596 | } |
| 597 | passing_copy = { |
| 598 | "id": "X-4004", |
| 599 | "text": "Acme benchmark release shipped today", |
| 600 | "author_handle": "acmedev", |
| 601 | "url": shared_url, |
| 602 | "date": "2026-03-30", |
| 603 | "engagement": {"likes": 90}, |
| 604 | } |
| 605 | |
| 606 | report, fused_streams = self._run_x_floor_pipeline( |
| 607 | {"sq1": [failing_copy], "sq2": [passing_copy]}, |
| 608 | ) |
| 609 | |
| 610 | assert fused_streams.get(("sq1", "x")) == [] |
| 611 | assert len(fused_streams.get(("sq2", "x"), [])) == 1 |
| 612 | assert len(report.items_by_source.get("x", [])) == 1 |
| 613 | assert report.source_status["x"].items_returned == 1 |
| 614 | assert report.ranked_candidates[0].subquery_labels == ["sq2"] |
| 615 | |
| 616 | |
| 617 | # --------------------------------------------------------------------------- |
| 618 | # HIGH-022: Post-plan source & subquery weight normalization |
| 619 | # --------------------------------------------------------------------------- |
| 620 | |
| 621 | |
| 622 | class TestHigh022PostPlanWeightNormalization: |
| 623 | TEN_SOURCES = [ |
| 624 | "reddit", "x", "youtube", "hackernews", "polymarket", |
| 625 | "github", "grounding", "tiktok", "instagram", "bluesky", |
| 626 | ] |
| 627 | |
| 628 | def test_ensure_devto_in_plan_uses_mean_weight(self): |
| 629 | plan = _make_plan(self.TEN_SOURCES) |
| 630 | pipeline._ensure_opt_in_source_in_plan(plan, [*self.TEN_SOURCES, "devto"], "devto") |
| 631 | |
| 632 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 633 | assert plan.source_weights["devto"] == pytest.approx(1.0 / 11) |
| 634 | assert plan.source_weights["reddit"] == pytest.approx(1.0 / 11) |
| 635 | |
| 636 | def test_ensure_unplanned_lanes_in_host_plan_uses_mean_weight(self): |
| 637 | plan = _make_plan(self.TEN_SOURCES) |
| 638 | pipeline._ensure_unplanned_lanes_in_host_plan( |
| 639 | plan, |
| 640 | [*self.TEN_SOURCES, "digg", "arxiv"], |
| 641 | installed=True, |
| 642 | ) |
| 643 | |
| 644 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 645 | for source in (*self.TEN_SOURCES, "digg", "arxiv"): |
| 646 | assert plan.source_weights[source] == pytest.approx(1.0 / 12) |
| 647 | |
| 648 | def test_ensure_company_jobs_in_host_plan_uses_mean_weight(self): |
| 649 | plan = _make_plan(self.TEN_SOURCES) |
| 650 | pipeline._ensure_company_jobs_in_host_plan( |
| 651 | plan, [*self.TEN_SOURCES, "jobs"], "official site acme.com", |
| 652 | ) |
| 653 | |
| 654 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 655 | assert plan.source_weights["jobs"] == pytest.approx(1.0 / 11) |
| 656 | assert plan.source_weights["reddit"] == pytest.approx(1.0 / 11) |
| 657 | |
| 658 | def test_ensure_jobs_in_plan_uses_mean_weight_and_renormalizes(self): |
| 659 | plan = _make_plan(self.TEN_SOURCES) |
| 660 | pipeline._ensure_jobs_in_plan( |
| 661 | plan, [*self.TEN_SOURCES, "jobs"], explicit=True, topic="Acme Corp", |
| 662 | ) |
| 663 | |
| 664 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 665 | assert plan.source_weights["jobs"] == pytest.approx(1.0 / 11) |
| 666 | assert plan.source_weights["reddit"] == pytest.approx(1.0 / 11) |
| 667 | |
| 668 | def test_ensure_perplexity_in_plan_normalizes_both_subquery_and_source_weights(self): |
| 669 | plan = _make_plan(self.TEN_SOURCES, num_subqueries=3) |
| 670 | pipeline._ensure_perplexity_in_plan( |
| 671 | plan, "Acme Corp", [*self.TEN_SOURCES, "perplexity"], force=True, |
| 672 | ) |
| 673 | |
| 674 | assert sum(sq.weight for sq in plan.subqueries) == pytest.approx(1.0) |
| 675 | assert len(plan.subqueries) == 4 |
| 676 | for sq in plan.subqueries: |
| 677 | assert sq.weight == pytest.approx(0.25) |
| 678 | |
| 679 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 680 | assert plan.source_weights["perplexity"] == pytest.approx(1.0 / 11) |
| 681 | assert plan.source_weights["reddit"] == pytest.approx(1.0 / 11) |
| 682 | |
| 683 | def test_sequential_injections_do_not_exponentially_halve_primary_sources(self): |
| 684 | plan = _make_plan(self.TEN_SOURCES, num_subqueries=3) |
| 685 | available = [*self.TEN_SOURCES, "digg", "jobs", "devto", "perplexity"] |
| 686 | |
| 687 | pipeline._ensure_unplanned_lanes_in_host_plan(plan, available, installed=True) |
| 688 | pipeline._ensure_company_jobs_in_host_plan(plan, available, "ticker ACME") |
| 689 | pipeline._ensure_opt_in_source_in_plan(plan, available, "devto") |
| 690 | pipeline._ensure_perplexity_in_plan(plan, "Acme Corp", available, force=True) |
| 691 | |
| 692 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 693 | for source in available: |
| 694 | assert plan.source_weights[source] == pytest.approx(1.0 / len(available)) |
| 695 | assert all(sq.weight == pytest.approx(0.25) for sq in plan.subqueries) |
| 696 | |
| 697 | def test_empty_and_zero_weight_maps_fall_back_safely_to_one(self): |
| 698 | assert pipeline._mean_source_weight({}) == 1.0 |
| 699 | assert pipeline._mean_source_weight({"a": 0.0, "b": 0.0}) == 1.0 |
| 700 | |
| 701 | plan = _make_plan(["perplexity"], num_subqueries=1) |
| 702 | plan.source_weights = {} |
| 703 | pipeline._ensure_perplexity_in_plan(plan, "Acme", ["perplexity"], force=True) |
| 704 | assert len(plan.subqueries) == 1 |
| 705 | assert plan.subqueries[0].weight == pytest.approx(1.0) |
| 706 | assert plan.source_weights["perplexity"] == pytest.approx(1.0) |
| 707 | |
| 708 | def test_sanitize_plan_and_backfill_use_planned_mean_and_preserve_explicit_weights(self): |
| 709 | from lib import planner |
| 710 | |
| 711 | raw = { |
| 712 | "intent": "general", |
| 713 | "freshness_mode": "balanced_recent", |
| 714 | "cluster_mode": "story", |
| 715 | "source_weights": {source: 0.1 for source in self.TEN_SOURCES}, |
| 716 | "subqueries": [ |
| 717 | { |
| 718 | "label": "primary", |
| 719 | "search_query": "Acme Corp", |
| 720 | "ranking_query": "What is new with Acme Corp?", |
| 721 | "sources": list(self.TEN_SOURCES), |
| 722 | "weight": 1.0, |
| 723 | } |
| 724 | ], |
| 725 | } |
| 726 | available = [*self.TEN_SOURCES, "digg"] |
| 727 | plan = planner._sanitize_plan( |
| 728 | raw, "Acme Corp", available, None, "default", honor_plan_sources=True, |
| 729 | ) |
| 730 | pipeline._ensure_unplanned_lanes_in_host_plan(plan, available, installed=True) |
| 731 | |
| 732 | assert "digg" in plan.subqueries[0].sources |
| 733 | assert sum(plan.source_weights.values()) == pytest.approx(1.0) |
| 734 | assert plan.source_weights["digg"] == pytest.approx(1.0 / 11) |
| 735 | assert plan.source_weights["reddit"] == pytest.approx(1.0 / 11) |
| 736 | |
| 737 | # Explicit unequal weights are preserved while omitted eligible source gets their mean. |
| 738 | weighted_raw = { |
| 739 | **raw, |
| 740 | "source_weights": {"reddit": 0.6, "x": 0.4}, |
| 741 | "subqueries": [ |
| 742 | { |
| 743 | "label": "primary", |
| 744 | "search_query": "Acme Corp", |
| 745 | "ranking_query": "What is new with Acme Corp?", |
| 746 | "sources": ["reddit", "x"], |
| 747 | "weight": 1.0, |
| 748 | } |
| 749 | ], |
| 750 | } |
| 751 | weighted_plan = planner._sanitize_plan( |
| 752 | weighted_raw, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 753 | honor_plan_sources=True, |
| 754 | ) |
| 755 | # mean(0.6, 0.4) = 0.5 -> normalized [0.6/1.5, 0.4/1.5, 0.5/1.5] |
| 756 | assert weighted_plan.source_weights["reddit"] == pytest.approx(0.6 / 1.5) |
| 757 | assert weighted_plan.source_weights["x"] == pytest.approx(0.4 / 1.5) |
| 758 | assert weighted_plan.source_weights["digg"] == pytest.approx(0.5 / 1.5) |
| 759 | |
| 760 | # Explicit weight for a backfilled source in raw plan is respected. |
| 761 | explicit_raw = { |
| 762 | **weighted_raw, |
| 763 | "source_weights": {"reddit": 0.6, "x": 0.2, "digg": 0.2}, |
| 764 | } |
| 765 | explicit_plan = planner._sanitize_plan( |
| 766 | explicit_raw, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 767 | honor_plan_sources=True, |
| 768 | ) |
| 769 | assert explicit_plan.source_weights["reddit"] == pytest.approx(0.6) |
| 770 | assert explicit_plan.source_weights["digg"] == pytest.approx(0.2) |
| 771 | |
| 772 | def test_sanitize_plan_preserves_raw_unnormalized_source_boosts_and_demotions(self): |
| 773 | from lib import planner |
| 774 | |
| 775 | # Raw boost map (reddit=3.0, x unweighted): x defaults to 1.0 so reddit keeps 3:1 boost. |
| 776 | boosted_raw = { |
| 777 | "intent": "general", |
| 778 | "freshness_mode": "balanced_recent", |
| 779 | "cluster_mode": "story", |
| 780 | "source_weights": {"reddit": 3.0}, |
| 781 | "subqueries": [ |
| 782 | { |
| 783 | "label": "primary", |
| 784 | "search_query": "Acme Corp", |
| 785 | "ranking_query": "What is new with Acme Corp?", |
| 786 | "sources": ["reddit", "x"], |
| 787 | "weight": 1.0, |
| 788 | } |
| 789 | ], |
| 790 | } |
| 791 | boosted_plan = planner._sanitize_plan( |
| 792 | boosted_raw, "Acme Corp", ["reddit", "x"], None, "default", |
| 793 | honor_plan_sources=True, |
| 794 | ) |
| 795 | assert boosted_plan.source_weights["reddit"] == pytest.approx(0.75) |
| 796 | assert boosted_plan.source_weights["x"] == pytest.approx(0.25) |
| 797 | |
| 798 | # Raw demotion map (reddit=0.5, x unweighted): x defaults to 1.0 so reddit stays 1:2. |
| 799 | demoted_raw = {**boosted_raw, "source_weights": {"reddit": 0.5}} |
| 800 | demoted_plan = planner._sanitize_plan( |
| 801 | demoted_raw, "Acme Corp", ["reddit", "x"], None, "default", |
| 802 | honor_plan_sources=True, |
| 803 | ) |
| 804 | assert demoted_plan.source_weights["reddit"] == pytest.approx(1.0 / 3) |
| 805 | assert demoted_plan.source_weights["x"] == pytest.approx(2.0 / 3) |
| 806 | |
| 807 | # Multi-source raw boost map (reddit=3.0, youtube=2.0, x unweighted -> x=1.0). |
| 808 | multi_raw = {**boosted_raw, "source_weights": {"reddit": 3.0, "youtube": 2.0}} |
| 809 | multi_plan = planner._sanitize_plan( |
| 810 | multi_raw, "Acme Corp", ["reddit", "youtube", "x"], None, "default", |
| 811 | honor_plan_sources=True, |
| 812 | ) |
| 813 | assert multi_plan.source_weights["reddit"] == pytest.approx(3.0 / 6.0) |
| 814 | assert multi_plan.source_weights["youtube"] == pytest.approx(2.0 / 6.0) |
| 815 | assert multi_plan.source_weights["x"] == pytest.approx(1.0 / 6.0) |
| 816 | |
| 817 | def test_sanitize_plan_ignores_filtered_out_and_overflow_weights_for_default(self): |
| 818 | from lib import planner, signals |
| 819 | |
| 820 | base_raw = { |
| 821 | "intent": "product", |
| 822 | "freshness_mode": "last30days", |
| 823 | "cluster_mode": "story", |
| 824 | "subqueries": [ |
| 825 | { |
| 826 | "label": "primary", |
| 827 | "search_query": "Acme Corp", |
| 828 | "ranking_query": "Acme Corp reviews", |
| 829 | "sources": ["reddit", "x"], |
| 830 | } |
| 831 | ], |
| 832 | "source_weights": {"reddit": 0.6, "x": 0.4}, |
| 833 | } |
| 834 | baseline = planner._sanitize_plan( |
| 835 | base_raw, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 836 | honor_plan_sources=True, |
| 837 | ) |
| 838 | # Filtered weights sum to 1.0 (0.6 + 0.4), so unweighted digg gets 0.5 -> 0.5 / 1.5 = 1/3. |
| 839 | assert baseline.source_weights["reddit"] == pytest.approx(0.6 / 1.5) |
| 840 | assert baseline.source_weights["x"] == pytest.approx(0.4 / 1.5) |
| 841 | assert baseline.source_weights["digg"] == pytest.approx(0.5 / 1.5) |
| 842 | |
| 843 | # Adding a weight for an unavailable source must not skew the default weight. |
| 844 | with_unavailable = { |
| 845 | **base_raw, |
| 846 | "source_weights": {"reddit": 0.6, "x": 0.4, "youtube": 0.2}, |
| 847 | } |
| 848 | plan_unavailable = planner._sanitize_plan( |
| 849 | with_unavailable, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 850 | honor_plan_sources=True, |
| 851 | ) |
| 852 | assert plan_unavailable.source_weights == pytest.approx(baseline.source_weights) |
| 853 | |
| 854 | # Adding a weight for a source excluded via requested_sources must not skew it either. |
| 855 | plan_excluded = planner._sanitize_plan( |
| 856 | with_unavailable, |
| 857 | "Acme Corp", |
| 858 | ["reddit", "x", "digg", "youtube"], |
| 859 | ["reddit", "x", "digg"], |
| 860 | "default", |
| 861 | honor_plan_sources=True, |
| 862 | ) |
| 863 | assert plan_excluded.source_weights == pytest.approx(baseline.source_weights) |
| 864 | |
| 865 | # Huge / non-finite / bool weights on excluded or eligible sources must not crash planning. |
| 866 | with_huge_excluded = { |
| 867 | **base_raw, |
| 868 | "source_weights": {"reddit": 0.6, "x": 0.4, "youtube": 10**400}, |
| 869 | } |
| 870 | plan_huge_excluded = planner._sanitize_plan( |
| 871 | with_huge_excluded, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 872 | honor_plan_sources=True, |
| 873 | ) |
| 874 | assert plan_huge_excluded.source_weights == pytest.approx(baseline.source_weights) |
| 875 | |
| 876 | for bad_weight in (10**400, -10**400, float("inf"), float("nan"), True, "not-a-number"): |
| 877 | with_bad_eligible = { |
| 878 | **base_raw, |
| 879 | "source_weights": {"reddit": 0.6, "x": 0.4, "digg": bad_weight}, |
| 880 | } |
| 881 | plan_bad_eligible = planner._sanitize_plan( |
| 882 | with_bad_eligible, "Acme Corp", ["reddit", "x", "digg"], None, "default", |
| 883 | honor_plan_sources=True, |
| 884 | ) |
| 885 | assert plan_bad_eligible.source_weights == pytest.approx(baseline.source_weights) |
| 886 | |
| 887 | # Normalized plan where one planned source is disabled/unavailable |
| 888 | # (reddit=0.5, x=0.3, youtube=0.2 -> raw sum 1.0, filtered sum 0.8): |
| 889 | # unweighted digg must receive the filtered mean 0.4 (0.4 / 1.2 = 1/3), |
| 890 | # not 1.0. |
| 891 | normalized_with_disabled = { |
| 892 | **base_raw, |
| 893 | "source_weights": {"reddit": 0.5, "x": 0.3, "youtube": 0.2}, |
| 894 | } |
| 895 | plan_disabled_unavailable = planner._sanitize_plan( |
| 896 | normalized_with_disabled, |
| 897 | "Acme Corp", |
| 898 | ["reddit", "x", "digg"], |
| 899 | None, |
| 900 | "default", |
| 901 | honor_plan_sources=True, |
| 902 | ) |
| 903 | assert plan_disabled_unavailable.source_weights["reddit"] == pytest.approx(0.5 / 1.2) |
| 904 | assert plan_disabled_unavailable.source_weights["x"] == pytest.approx(0.3 / 1.2) |
| 905 | assert plan_disabled_unavailable.source_weights["digg"] == pytest.approx(0.4 / 1.2) |
| 906 | |
| 907 | plan_disabled_excluded = planner._sanitize_plan( |
| 908 | normalized_with_disabled, |
| 909 | "Acme Corp", |
| 910 | ["reddit", "x", "digg", "youtube"], |
| 911 | ["reddit", "x", "digg"], |
| 912 | "default", |
| 913 | honor_plan_sources=True, |
| 914 | ) |
| 915 | assert plan_disabled_excluded.source_weights == pytest.approx( |
| 916 | plan_disabled_unavailable.source_weights |
| 917 | ) |
| 918 | |
| 919 | # Unrecognized source names / typos (e.g. "youtub": 0.5 alongside "reddit": 0.5) |
| 920 | # must NOT be counted as normalized planned sources; X keeps default 1.0 |
| 921 | # so Reddit keeps its 1:2 demotion. |
| 922 | typo_raw = { |
| 923 | **base_raw, |
| 924 | "source_weights": {"reddit": 0.5, "youtub": 0.5}, |
| 925 | } |
| 926 | plan_with_typo = planner._sanitize_plan( |
| 927 | typo_raw, "Acme Corp", ["reddit", "x"], None, "default", |
| 928 | honor_plan_sources=True, |
| 929 | ) |
| 930 | assert plan_with_typo.source_weights["reddit"] == pytest.approx(1.0 / 3) |
| 931 | assert plan_with_typo.source_weights["x"] == pytest.approx(2.0 / 3) |
| 932 | assert "youtub" not in plan_with_typo.source_weights |
| 933 | assert pipeline.KNOWN_SEARCH_SOURCES <= planner.KNOWN_SOURCES |
| 934 | assert set(signals._ENGAGEMENT_LOG_REFERENCE) <= planner.KNOWN_SOURCES |
| 935 | assert signals._NO_ENGAGEMENT_SCORE_SOURCES <= planner.KNOWN_SOURCES |
| 936 | |
| 937 | |
| 938 | # --------------------------------------------------------------------------- |
| 939 | # HIGH-023: YouTube SSH host routing without local yt-dlp binary |
| 940 | # --------------------------------------------------------------------------- |
| 941 | |
| 942 | |
| 943 | class TestHigh023YoutubeSshHostAvailabilityAndStream: |
| 944 | def test_available_sources_includes_youtube_with_ssh_host_in_env_without_local_ytdlp( |
| 945 | self, monkeypatch, |
| 946 | ): |
| 947 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: None) |
| 948 | monkeypatch.setenv("LAST30DAYS_YOUTUBE_SSH_HOST", "macmini") |
| 949 | |
| 950 | assert "youtube" in pipeline.available_sources({}) |
| 951 | |
| 952 | def test_available_sources_includes_youtube_with_ssh_host_in_config_without_env( |
| 953 | self, monkeypatch, |
| 954 | ): |
| 955 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: None) |
| 956 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 957 | |
| 958 | without_ssh = pipeline.available_sources({}) |
| 959 | assert "youtube" not in without_ssh |
| 960 | assert "tiktok" not in without_ssh |
| 961 | assert "instagram" not in without_ssh |
| 962 | |
| 963 | with_ssh = pipeline.available_sources({"LAST30DAYS_YOUTUBE_SSH_HOST": "macmini"}) |
| 964 | assert "youtube" in with_ssh |
| 965 | assert "tiktok" in with_ssh |
| 966 | assert "instagram" in with_ssh |
| 967 | # Config-scoped check must not pollute process-wide os.environ. |
| 968 | assert "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ |
| 969 | |
| 970 | def test_retrieve_stream_uses_ssh_ytdlp_without_local_binary_from_config( |
| 971 | self, monkeypatch, |
| 972 | ): |
| 973 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: None) |
| 974 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 975 | |
| 976 | observed: dict[str, object] = {} |
| 977 | |
| 978 | def _fake_search_and_transcribe(*_args, **_kwargs): |
| 979 | observed["ssh_host"] = youtube_yt._ytdlp_ssh_host() |
| 980 | observed["is_installed"] = youtube_yt.is_ytdlp_installed() |
| 981 | return { |
| 982 | "items": [ |
| 983 | { |
| 984 | "video_id": f"v{i}", |
| 985 | "title": f"Acme video {i}", |
| 986 | "url": f"https://www.youtube.com/watch?v=v{i}", |
| 987 | "date": "2026-03-20", |
| 988 | "transcript_snippet": "substantive transcript", |
| 989 | } |
| 990 | for i in range(4) |
| 991 | ] |
| 992 | } |
| 993 | |
| 994 | with mock.patch.object( |
| 995 | youtube_yt, "search_and_transcribe", side_effect=_fake_search_and_transcribe, |
| 996 | ) as ytdlp_search, mock.patch.object( |
| 997 | youtube_yt, "search_youtube_sc", |
| 998 | ) as sc_search, mock.patch.object( |
| 999 | youtube_yt, "enrich_with_comments", side_effect=lambda items, **_k: items, |
| 1000 | ): |
| 1001 | items, artifact = pipeline._retrieve_stream_impl( |
| 1002 | topic="Acme", |
| 1003 | subquery=schema.SubQuery( |
| 1004 | label="primary", |
| 1005 | search_query="Acme", |
| 1006 | ranking_query="Acme", |
| 1007 | sources=["youtube"], |
| 1008 | ), |
| 1009 | source="youtube", |
| 1010 | config={ |
| 1011 | "LAST30DAYS_YOUTUBE_SSH_HOST": "macmini", |
| 1012 | "SCRAPECREATORS_API_KEY": "dummy-sc-key", |
| 1013 | }, |
| 1014 | depth="default", |
| 1015 | date_range=("2026-03-01", "2026-03-31"), |
| 1016 | runtime=_make_runtime(), |
| 1017 | mock=False, |
| 1018 | ) |
| 1019 | |
| 1020 | assert ytdlp_search.call_count == 1 |
| 1021 | sc_search.assert_not_called() |
| 1022 | assert observed == {"ssh_host": "macmini", "is_installed": True} |
| 1023 | assert len(items) == 4 |
| 1024 | assert "_source_outcome" not in artifact |
| 1025 | assert "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ |
| 1026 | |
| 1027 | @pytest.mark.parametrize( |
| 1028 | ("source", "urls"), |
| 1029 | [ |
| 1030 | ( |
| 1031 | "tiktok", |
| 1032 | [ |
| 1033 | "https://www.tiktok.com/@acmedev/video/7621000000000000001", |
| 1034 | "https://www.tiktok.com/@acmedev/video/7621000000000000002", |
| 1035 | ], |
| 1036 | ), |
| 1037 | ( |
| 1038 | "instagram", |
| 1039 | [ |
| 1040 | "https://www.instagram.com/reel/DWabcd12341/", |
| 1041 | "https://www.instagram.com/reel/DWabcd12342/", |
| 1042 | ], |
| 1043 | ), |
| 1044 | ], |
| 1045 | ) |
| 1046 | def test_shortform_streams_and_multibatch_workers_inherit_config_ssh_host_scope( |
| 1047 | self, monkeypatch, source, urls, |
| 1048 | ): |
| 1049 | import json |
| 1050 | from lib import shortform_oss, subproc |
| 1051 | |
| 1052 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: None) |
| 1053 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 1054 | |
| 1055 | config = { |
| 1056 | "LAST30DAYS_YOUTUBE_SSH_HOST": "macmini", |
| 1057 | "EXCLUDE_SOURCES": "tiktok_comments,instagram_comments", |
| 1058 | } |
| 1059 | assert source in pipeline.available_sources(config) |
| 1060 | |
| 1061 | seen_cmds: list[list[str]] = [] |
| 1062 | seen_enrich_worker_hosts: list[str | None] = [] |
| 1063 | lock = threading.Lock() |
| 1064 | |
| 1065 | def _fake_run(cmd, *, input_text="", **_kwargs): |
| 1066 | with lock: |
| 1067 | seen_cmds.append(list(cmd)) |
| 1068 | if "--flat-playlist" in " ".join(cmd): |
| 1069 | return subproc.SubprocResult(returncode=0, stdout="", stderr="") |
| 1070 | url = input_text.strip() |
| 1071 | vid = url.rstrip("/").split("/")[-1] |
| 1072 | with lock: |
| 1073 | seen_enrich_worker_hosts.append(youtube_yt._ytdlp_ssh_host()) |
| 1074 | payload = json.dumps( |
| 1075 | { |
| 1076 | "id": vid, |
| 1077 | "uploader": "acmedev", |
| 1078 | "timestamp": 1774000000, # 2026-03-20 UTC |
| 1079 | "view_count": 500, |
| 1080 | "like_count": 40, |
| 1081 | "comment_count": 5, |
| 1082 | "description": "Acme launch benchmark review", |
| 1083 | "webpage_url": url, |
| 1084 | } |
| 1085 | ) |
| 1086 | return subproc.SubprocResult(returncode=0, stdout=payload + "\n", stderr="") |
| 1087 | |
| 1088 | with mock.patch.object( |
| 1089 | shortform_oss, "discover_urls", return_value=(urls, "keyless"), |
| 1090 | ), mock.patch.object( |
| 1091 | shortform_oss, "_outside_window", return_value=False, |
| 1092 | ), mock.patch.object( |
| 1093 | shortform_oss.subproc, "run_with_timeout", side_effect=_fake_run, |
| 1094 | ), mock.patch.object( |
| 1095 | pipeline.tiktok, "enrich_with_comments", side_effect=lambda items, **_k: items, |
| 1096 | ), mock.patch.object( |
| 1097 | pipeline.instagram, "enrich_with_comments", side_effect=lambda items, **_k: items, |
| 1098 | ): |
| 1099 | items, artifact = pipeline._retrieve_stream_impl( |
| 1100 | topic="Acme launch", |
| 1101 | subquery=schema.SubQuery( |
| 1102 | label="primary", |
| 1103 | search_query="Acme launch", |
| 1104 | ranking_query="Acme launch", |
| 1105 | sources=[source], |
| 1106 | ), |
| 1107 | source=source, |
| 1108 | config=config, |
| 1109 | depth="default", |
| 1110 | date_range=("2026-03-01", "2026-03-31"), |
| 1111 | runtime=_make_runtime(), |
| 1112 | mock=False, |
| 1113 | ) |
| 1114 | |
| 1115 | assert "_source_outcome" not in artifact |
| 1116 | assert len(items) == 2 |
| 1117 | assert len(seen_cmds) >= 2 |
| 1118 | assert all(cmd[0] == "ssh" and "macmini" in cmd for cmd in seen_cmds) |
| 1119 | assert seen_enrich_worker_hosts == ["macmini", "macmini"] |
| 1120 | assert "LAST30DAYS_YOUTUBE_SSH_HOST" not in os.environ |
| 1121 | |
| 1122 | def test_invalid_ssh_host_does_not_enable_ytdlp(self, monkeypatch, capsys): |
| 1123 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: None) |
| 1124 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 1125 | |
| 1126 | bad_config = {"LAST30DAYS_YOUTUBE_SSH_HOST": "-oProxyCommand=evil"} |
| 1127 | assert "youtube" not in pipeline.available_sources(bad_config) |
| 1128 | avail_err = capsys.readouterr().err |
| 1129 | assert avail_err.count("does not look like a plain hostname/alias") == 1 |
| 1130 | |
| 1131 | with mock.patch.object(youtube_yt, "search_and_transcribe") as ytdlp_search: |
| 1132 | items, _artifact = pipeline._retrieve_stream_impl( |
| 1133 | topic="Acme", |
| 1134 | subquery=schema.SubQuery( |
| 1135 | label="primary", |
| 1136 | search_query="Acme", |
| 1137 | ranking_query="Acme", |
| 1138 | sources=["youtube"], |
| 1139 | ), |
| 1140 | source="youtube", |
| 1141 | config=bad_config, |
| 1142 | depth="default", |
| 1143 | date_range=("2026-03-01", "2026-03-31"), |
| 1144 | runtime=_make_runtime(), |
| 1145 | mock=False, |
| 1146 | ) |
| 1147 | stream_err = capsys.readouterr().err |
| 1148 | assert stream_err.count("does not look like a plain hostname/alias") == 1 |
| 1149 | ytdlp_search.assert_not_called() |
| 1150 | assert items == [] |
| 1151 | |
| 1152 | def test_youtube_search_cache_isolates_different_ssh_hosts_and_inflight_slots( |
| 1153 | self, monkeypatch, |
| 1154 | ): |
| 1155 | import json |
| 1156 | from lib import subproc |
| 1157 | |
| 1158 | youtube_yt.reset_search_cache() |
| 1159 | monkeypatch.setattr(youtube_yt.shutil, "which", lambda _cmd: "/usr/bin/yt-dlp") |
| 1160 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 1161 | |
| 1162 | calls: list[str | None] = [] |
| 1163 | both_inflight = threading.Barrier(2, timeout=5) |
| 1164 | lock = threading.Lock() |
| 1165 | |
| 1166 | def _fake_run(cmd, **_kwargs): |
| 1167 | host = youtube_yt._ytdlp_ssh_host() |
| 1168 | with lock: |
| 1169 | calls.append(host) |
| 1170 | if host in ("host-a", "host-b"): |
| 1171 | both_inflight.wait() |
| 1172 | label = host or "local" |
| 1173 | payload = json.dumps( |
| 1174 | { |
| 1175 | "id": f"vid_{label}", |
| 1176 | "title": f"Acme from {label}", |
| 1177 | "upload_date": "20260320", |
| 1178 | "view_count": 100, |
| 1179 | "like_count": 10, |
| 1180 | "comment_count": 1, |
| 1181 | } |
| 1182 | ) |
| 1183 | return subproc.SubprocResult(returncode=0, stdout=payload + "\n", stderr="") |
| 1184 | |
| 1185 | def _run_search(host: str | None): |
| 1186 | with youtube_yt.ssh_host_scope(host): |
| 1187 | return youtube_yt.search_youtube( |
| 1188 | "Acme", "2026-03-01", "2026-03-31", depth="quick", |
| 1189 | ) |
| 1190 | |
| 1191 | try: |
| 1192 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=_fake_run): |
| 1193 | # Concurrent in-flight calls on host-a vs host-b must not coalesce onto each other. |
| 1194 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 1195 | fa = pool.submit(_run_search, "host-a") |
| 1196 | fb = pool.submit(_run_search, "host-b") |
| 1197 | res_a = fa.result(timeout=5) |
| 1198 | res_b = fb.result(timeout=5) |
| 1199 | # Local call must also miss both SSH cache entries. |
| 1200 | res_local = _run_search(None) |
| 1201 | # Repeating host-a hits host-a's cached result without another subprocess call. |
| 1202 | res_a_cached = _run_search("host-a") |
| 1203 | |
| 1204 | assert [i["video_id"] for i in res_a["items"]] == ["vid_host-a"] |
| 1205 | assert [i["video_id"] for i in res_b["items"]] == ["vid_host-b"] |
| 1206 | assert [i["video_id"] for i in res_local["items"]] == ["vid_local"] |
| 1207 | assert [i["video_id"] for i in res_a_cached["items"]] == ["vid_host-a"] |
| 1208 | assert sorted(c or "local" for c in calls) == ["host-a", "host-b", "local"] |
| 1209 | finally: |
| 1210 | youtube_yt.reset_search_cache() |
| 1211 | |
| 1212 | |
| 1213 | # --------------------------------------------------------------------------- |
| 1214 | # HIGH-031: RetrievalBundle.record_detail substring preservation & specificity |
| 1215 | # --------------------------------------------------------------------------- |
| 1216 | |
| 1217 | |
| 1218 | class TestHigh031RecordDetailPreservationAndSpecificity: |
| 1219 | def test_shorter_substring_detail_does_not_clobber_existing_detail(self): |
| 1220 | bundle = schema.RetrievalBundle() |
| 1221 | bundle.mark_attempted("reddit") |
| 1222 | full = "3 sub-requests rate-limited (HTTP 429); 1 sub-request blocked (HTTP 403)" |
| 1223 | shorter = "1 sub-request blocked (HTTP 403)" |
| 1224 | |
| 1225 | bundle.record_detail("reddit", full, state=schema.RATE_LIMITED) |
| 1226 | bundle.record_detail("reddit", shorter, state=schema.RATE_LIMITED) |
| 1227 | |
| 1228 | assert bundle.detail_by_source["reddit"] == full |
| 1229 | assert bundle.source_status["reddit"].detail == full |
| 1230 | |
| 1231 | def test_longer_superset_detail_replaces_shorter_without_duplication(self): |
| 1232 | bundle = schema.RetrievalBundle() |
| 1233 | bundle.mark_attempted("reddit") |
| 1234 | shorter = "1 sub-request blocked (HTTP 403)" |
| 1235 | full = "3 sub-requests rate-limited (HTTP 429); 1 sub-request blocked (HTTP 403)" |
| 1236 | |
| 1237 | bundle.record_detail("reddit", shorter, state=schema.RATE_LIMITED) |
| 1238 | bundle.record_detail("reddit", full, state=schema.RATE_LIMITED) |
| 1239 | |
| 1240 | assert bundle.detail_by_source["reddit"] == full |
| 1241 | assert bundle.source_status["reddit"].detail == full |
| 1242 | |
| 1243 | def test_distinct_failure_counts_with_shared_suffix_are_both_preserved(self): |
| 1244 | bundle = schema.RetrievalBundle() |
| 1245 | bundle.mark_attempted("reddit") |
| 1246 | twelve = "12 sub-requests rate-limited (HTTP 429)" |
| 1247 | two = "2 sub-requests rate-limited (HTTP 429)" |
| 1248 | |
| 1249 | bundle.record_detail("reddit", twelve, state=schema.RATE_LIMITED) |
| 1250 | bundle.record_detail("reddit", two, state=schema.RATE_LIMITED) |
| 1251 | assert bundle.detail_by_source["reddit"] == f"{twelve}; {two}" |
| 1252 | assert bundle.source_status["reddit"].detail == f"{twelve}; {two}" |
| 1253 | |
| 1254 | # Reverse order preserves both clauses too, with the longer clause leading. |
| 1255 | bundle_rev = schema.RetrievalBundle() |
| 1256 | bundle_rev.mark_attempted("reddit") |
| 1257 | bundle_rev.record_detail("reddit", two, state=schema.RATE_LIMITED) |
| 1258 | bundle_rev.record_detail("reddit", twelve, state=schema.RATE_LIMITED) |
| 1259 | assert bundle_rev.detail_by_source["reddit"] == f"{twelve}; {two}" |
| 1260 | |
| 1261 | # Overlapping multi-clause details deduplicate exact clauses without losing distinct ones. |
| 1262 | bundle_overlap = schema.RetrievalBundle() |
| 1263 | bundle_overlap.mark_attempted("reddit") |
| 1264 | bundle_overlap.record_detail("reddit", "clause A; clause B") |
| 1265 | bundle_overlap.record_detail("reddit", "clause B; clause C") |
| 1266 | assert bundle_overlap.detail_by_source["reddit"] == "clause A; clause B; clause C" |
| 1267 | |
| 1268 | def test_merged_detail_orders_longest_clause_first_regardless_of_arrival_order(self): |
| 1269 | short_clause = "host kept 2 of 2" |
| 1270 | long_clause = "host+arctic served 1" |
| 1271 | expected = f"{long_clause}; {short_clause}" |
| 1272 | |
| 1273 | for first, second in ((short_clause, long_clause), (long_clause, short_clause)): |
| 1274 | bundle = schema.RetrievalBundle() |
| 1275 | bundle.mark_attempted("reddit") |
| 1276 | bundle.record_detail("reddit", first) |
| 1277 | bundle.record_detail("reddit", second) |
| 1278 | assert bundle.detail_by_source["reddit"] == expected |
| 1279 | assert bundle.source_status["reddit"].detail == expected |
| 1280 | |
| 1281 | def test_distinct_detail_appends_and_exact_repeat_does_not_duplicate(self): |
| 1282 | bundle = schema.RetrievalBundle() |
| 1283 | bundle.mark_attempted("reddit") |
| 1284 | bundle.record_detail("reddit", "first note") |
| 1285 | bundle.record_detail("reddit", "other note") |
| 1286 | bundle.record_detail("reddit", "first note") |
| 1287 | bundle.record_detail("reddit", "other note") |
| 1288 | |
| 1289 | assert bundle.detail_by_source["reddit"] == "first note; other note" |
| 1290 | assert bundle.source_status["reddit"].detail == "first note; other note" |
| 1291 | |
| 1292 | def test_lane_failure_state_respects_failure_specificity(self): |
| 1293 | bundle = schema.RetrievalBundle() |
| 1294 | bundle.mark_attempted("x") |
| 1295 | bundle.record_detail("x", "auth expired", state=schema.AUTH_FAILED) |
| 1296 | bundle.record_detail("x", "generic error", state=health.ERROR) |
| 1297 | bundle.record_detail("x", "rate limited", state=schema.RATE_LIMITED) |
| 1298 | |
| 1299 | assert bundle.lane_state_by_source["x"] == schema.AUTH_FAILED |
| 1300 | assert bundle.source_status["x"].lane_failure_state == schema.AUTH_FAILED |
| 1301 | |
| 1302 | bundle_upgrade = schema.RetrievalBundle() |
| 1303 | bundle_upgrade.mark_attempted("x") |
| 1304 | bundle_upgrade.record_detail("x", "generic error", state=health.ERROR) |
| 1305 | bundle_upgrade.record_detail("x", "payment required", state=schema.PAYMENT_REQUIRED) |
| 1306 | assert bundle_upgrade.lane_state_by_source["x"] == schema.PAYMENT_REQUIRED |
| 1307 | |
| 1308 | |
| 1309 | # --------------------------------------------------------------------------- |
| 1310 | # HIGH-033: schema.without_sources invariants, artifacts, and candidate re-homing |
| 1311 | # --------------------------------------------------------------------------- |
| 1312 | |
| 1313 | |
| 1314 | class TestHigh033WithoutSourcesInvariants: |
| 1315 | def test_rebuilds_frozen_subqueries_drops_empty_and_roundtrips(self): |
| 1316 | sq_corpus_only = schema.SubQuery( |
| 1317 | label="local", |
| 1318 | search_query="internal docs", |
| 1319 | ranking_query="internal docs", |
| 1320 | sources=["corpus"], |
| 1321 | weight=0.4, |
| 1322 | ) |
| 1323 | sq_mixed = schema.SubQuery( |
| 1324 | label="mixed", |
| 1325 | search_query="acme rollout", |
| 1326 | ranking_query="acme rollout", |
| 1327 | sources=["corpus", "reddit"], |
| 1328 | weight=0.6, |
| 1329 | ) |
| 1330 | report = _make_report( |
| 1331 | subqueries=[sq_corpus_only, sq_mixed], |
| 1332 | source_weights={"corpus": 0.5, "reddit": 0.5}, |
| 1333 | ranked_candidates=[], |
| 1334 | clusters=[], |
| 1335 | items_by_source={}, |
| 1336 | ) |
| 1337 | |
| 1338 | clean = schema.without_sources(report, {"corpus"}) |
| 1339 | |
| 1340 | # Original report subqueries remain untouched. |
| 1341 | assert report.query_plan.subqueries[0].sources == ["corpus"] |
| 1342 | assert report.query_plan.subqueries[1].sources == ["corpus", "reddit"] |
| 1343 | |
| 1344 | # Clean report drops the empty subquery and rebuilds the mixed one cleanly. |
| 1345 | assert len(clean.query_plan.subqueries) == 1 |
| 1346 | assert clean.query_plan.subqueries[0].label == "mixed" |
| 1347 | assert clean.query_plan.subqueries[0].sources == ["reddit"] |
| 1348 | assert clean.query_plan.subqueries[0] is not sq_mixed |
| 1349 | |
| 1350 | # Must survive serialization + deserialization without raising ValueError. |
| 1351 | restored = schema.report_from_dict(schema.to_dict(clean)) |
| 1352 | assert [sq.sources for sq in restored.query_plan.subqueries] == [["reddit"]] |
| 1353 | |
| 1354 | def test_artifact_scrubbing_uses_token_boundaries_not_raw_substrings(self): |
| 1355 | report = _make_report( |
| 1356 | subqueries=[ |
| 1357 | schema.SubQuery( |
| 1358 | label="p", search_query="q", ranking_query="q", sources=["reddit"], |
| 1359 | ) |
| 1360 | ], |
| 1361 | source_weights={"reddit": 1.0}, |
| 1362 | ranked_candidates=[], |
| 1363 | clusters=[], |
| 1364 | items_by_source={}, |
| 1365 | artifacts={ |
| 1366 | "drill_context": {"topic": "keep me"}, |
| 1367 | "corpus_in_export": False, |
| 1368 | "extra_notes": "keep me too", |
| 1369 | "patents": {"count": 2}, |
| 1370 | "x": {"raw": 1}, |
| 1371 | "x_provenance": {"lane": "connector"}, |
| 1372 | "x_partial_coverage": ["note"], |
| 1373 | "extra_x": {"drop": True}, |
| 1374 | "prefix_x_suffix": {"drop": True}, |
| 1375 | "x-cache": {"drop": True}, |
| 1376 | "meta_ads_page": {"name": "Acme"}, |
| 1377 | "meta_ads_tally": {"total": 5}, |
| 1378 | }, |
| 1379 | ) |
| 1380 | |
| 1381 | clean_x = schema.without_sources(report, {"x"}) |
| 1382 | assert "drill_context" in clean_x.artifacts |
| 1383 | assert "corpus_in_export" in clean_x.artifacts |
| 1384 | assert "extra_notes" in clean_x.artifacts |
| 1385 | assert "patents" in clean_x.artifacts |
| 1386 | assert "meta_ads_page" in clean_x.artifacts |
| 1387 | for removed in ("x", "x_provenance", "x_partial_coverage", "extra_x", "prefix_x_suffix", "x-cache"): |
| 1388 | assert removed not in clean_x.artifacts |
| 1389 | |
| 1390 | clean_meta = schema.without_sources(report, {"meta_ads"}) |
| 1391 | assert "meta_ads_page" not in clean_meta.artifacts |
| 1392 | assert "meta_ads_tally" not in clean_meta.artifacts |
| 1393 | assert "drill_context" in clean_meta.artifacts |
| 1394 | |
| 1395 | def test_rehomes_multi_source_candidate_and_rebuilds_cluster_title(self): |
| 1396 | private_item = schema.SourceItem( |
| 1397 | item_id="C-secret", |
| 1398 | source="corpus", |
| 1399 | title="PRIVATE-CORPUS-TITLE", |
| 1400 | body="PRIVATE-CORPUS-BODY", |
| 1401 | url="corpus://notes/secret.md", |
| 1402 | snippet="PRIVATE-CORPUS-SNIPPET", |
| 1403 | published_at="2026-03-20", |
| 1404 | ) |
| 1405 | public_item = schema.SourceItem( |
| 1406 | item_id="R-public", |
| 1407 | source="reddit", |
| 1408 | title="Public Reddit rollout thread", |
| 1409 | body="Public Reddit body text", |
| 1410 | url="https://www.reddit.com/r/devops/comments/abc123/rollout/", |
| 1411 | snippet="Public Reddit rollout snippet", |
| 1412 | published_at="2026-03-21", |
| 1413 | ) |
| 1414 | fused = schema.Candidate( |
| 1415 | candidate_id="cand-fused", |
| 1416 | item_id="C-secret", |
| 1417 | source="corpus", |
| 1418 | title="PRIVATE-CORPUS-TITLE", |
| 1419 | url="corpus://notes/secret.md", |
| 1420 | snippet="PRIVATE-CORPUS-SNIPPET", |
| 1421 | subquery_labels=["primary"], |
| 1422 | native_ranks={"primary:corpus": 1, "primary:reddit": 2}, |
| 1423 | local_relevance=0.9, |
| 1424 | freshness=90, |
| 1425 | engagement=50, |
| 1426 | source_quality=1.0, |
| 1427 | rrf_score=0.05, |
| 1428 | sources=["corpus", "reddit"], |
| 1429 | source_items=[private_item, public_item], |
| 1430 | final_score=88.0, |
| 1431 | explanation="Matched PRIVATE-CORPUS-TITLE note", |
| 1432 | metadata={ |
| 1433 | "provenance": [ |
| 1434 | {"source": "corpus", "subquery_label": "primary", "native_rank": 1, "item_id": "C-secret"}, |
| 1435 | {"source": "reddit", "subquery_label": "primary", "native_rank": 2, "item_id": "R-public"}, |
| 1436 | ], |
| 1437 | }, |
| 1438 | ) |
| 1439 | cluster = schema.Cluster( |
| 1440 | cluster_id="cluster-1", |
| 1441 | title="PRIVATE-CORPUS-TITLE", |
| 1442 | candidate_ids=["cand-fused"], |
| 1443 | representative_ids=["cand-fused"], |
| 1444 | sources=["corpus", "reddit"], |
| 1445 | score=88.0, |
| 1446 | ) |
| 1447 | report = _make_report( |
| 1448 | subqueries=[ |
| 1449 | schema.SubQuery( |
| 1450 | label="primary", search_query="acme", ranking_query="acme", |
| 1451 | sources=["corpus", "reddit"], |
| 1452 | ) |
| 1453 | ], |
| 1454 | source_weights={"corpus": 0.5, "reddit": 0.5}, |
| 1455 | ranked_candidates=[fused], |
| 1456 | clusters=[cluster], |
| 1457 | items_by_source={"corpus": [private_item], "reddit": [public_item]}, |
| 1458 | ) |
| 1459 | |
| 1460 | clean = schema.without_sources(report, {"corpus"}) |
| 1461 | assert len(clean.ranked_candidates) == 1 |
| 1462 | rehomed = clean.ranked_candidates[0] |
| 1463 | assert rehomed.source == "reddit" |
| 1464 | assert rehomed.item_id == "R-public" |
| 1465 | assert rehomed.title == "Public Reddit rollout thread" |
| 1466 | assert rehomed.url == public_item.url |
| 1467 | assert rehomed.snippet == "Public Reddit rollout snippet" |
| 1468 | assert rehomed.sources == ["reddit"] |
| 1469 | assert rehomed.explanation is None |
| 1470 | assert list(rehomed.native_ranks.keys()) == ["primary:reddit"] |
| 1471 | assert [p["source"] for p in rehomed.metadata["provenance"]] == ["reddit"] |
| 1472 | assert clean.clusters[0].title == "Public Reddit rollout thread" |
| 1473 | assert clean.clusters[0].sources == ["reddit"] |
| 1474 | |
| 1475 | serialized = str(schema.to_dict(clean)) |
| 1476 | assert "PRIVATE-CORPUS" not in serialized |
| 1477 | assert "corpus://" not in serialized |
| 1478 | restored = schema.report_from_dict(schema.to_dict(clean)) |
| 1479 | assert restored.ranked_candidates[0].source == "reddit" |
| 1480 | |
| 1481 | def test_drops_orphan_candidate_when_all_source_items_are_excluded(self): |
| 1482 | private_only_item = schema.SourceItem( |
| 1483 | item_id="C1", |
| 1484 | source="corpus", |
| 1485 | title="Private note", |
| 1486 | body="secret", |
| 1487 | url="corpus://note.md", |
| 1488 | snippet="secret", |
| 1489 | ) |
| 1490 | # Candidate's top-level source says reddit, but every backing source_item is corpus. |
| 1491 | orphan = schema.Candidate( |
| 1492 | candidate_id="cand-orphan", |
| 1493 | item_id="C1", |
| 1494 | source="reddit", |
| 1495 | title="Orphan", |
| 1496 | url="corpus://note.md", |
| 1497 | snippet="secret", |
| 1498 | subquery_labels=["primary"], |
| 1499 | native_ranks={"primary:corpus": 1}, |
| 1500 | local_relevance=0.8, |
| 1501 | freshness=80, |
| 1502 | engagement=10, |
| 1503 | source_quality=1.0, |
| 1504 | rrf_score=0.02, |
| 1505 | sources=["corpus"], |
| 1506 | source_items=[private_only_item], |
| 1507 | final_score=75.0, |
| 1508 | ) |
| 1509 | public_item = schema.SourceItem( |
| 1510 | item_id="R2", |
| 1511 | source="reddit", |
| 1512 | title="Public survivor", |
| 1513 | body="public", |
| 1514 | url="https://www.reddit.com/r/test/comments/r2/p/", |
| 1515 | snippet="public snippet", |
| 1516 | ) |
| 1517 | survivor = schema.Candidate( |
| 1518 | candidate_id="cand-survivor", |
| 1519 | item_id="R2", |
| 1520 | source="reddit", |
| 1521 | title="Public survivor", |
| 1522 | url=public_item.url, |
| 1523 | snippet="public snippet", |
| 1524 | subquery_labels=["primary"], |
| 1525 | native_ranks={"primary:reddit": 1}, |
| 1526 | local_relevance=0.8, |
| 1527 | freshness=80, |
| 1528 | engagement=10, |
| 1529 | source_quality=1.0, |
| 1530 | rrf_score=0.02, |
| 1531 | sources=["reddit"], |
| 1532 | source_items=[public_item], |
| 1533 | final_score=70.0, |
| 1534 | ) |
| 1535 | report = _make_report( |
| 1536 | subqueries=[ |
| 1537 | schema.SubQuery( |
| 1538 | label="primary", search_query="acme", ranking_query="acme", |
| 1539 | sources=["reddit", "corpus"], |
| 1540 | ) |
| 1541 | ], |
| 1542 | source_weights={"reddit": 0.5, "corpus": 0.5}, |
| 1543 | ranked_candidates=[orphan, survivor], |
| 1544 | clusters=[ |
| 1545 | schema.Cluster( |
| 1546 | cluster_id="c-only-orphan", |
| 1547 | title="Orphan", |
| 1548 | candidate_ids=["cand-orphan"], |
| 1549 | representative_ids=["cand-orphan"], |
| 1550 | sources=["corpus"], |
| 1551 | score=75.0, |
| 1552 | ), |
| 1553 | schema.Cluster( |
| 1554 | cluster_id="c-mixed", |
| 1555 | title="Orphan", |
| 1556 | candidate_ids=["cand-orphan", "cand-survivor"], |
| 1557 | representative_ids=["cand-orphan"], |
| 1558 | sources=["corpus", "reddit"], |
| 1559 | score=75.0, |
| 1560 | ), |
| 1561 | ], |
| 1562 | items_by_source={"corpus": [private_only_item], "reddit": [public_item]}, |
| 1563 | ) |
| 1564 | |
| 1565 | clean = schema.without_sources(report, {"corpus"}) |
| 1566 | assert [c.candidate_id for c in clean.ranked_candidates] == ["cand-survivor"] |
| 1567 | assert [cl.cluster_id for cl in clean.clusters] == ["c-mixed"] |
| 1568 | assert clean.clusters[0].candidate_ids == ["cand-survivor"] |
| 1569 | assert clean.clusters[0].representative_ids == ["cand-survivor"] |
| 1570 | assert clean.clusters[0].title == "Public survivor" |
| 1571 | restored = schema.report_from_dict(schema.to_dict(clean)) |
| 1572 | assert len(restored.clusters) == 1 |
| 1573 | |
| 1574 | def test_strips_leaked_excluded_snippet_on_surviving_candidate(self): |
| 1575 | public_item = schema.SourceItem( |
| 1576 | item_id="R1", |
| 1577 | source="reddit", |
| 1578 | title="Public thread", |
| 1579 | body="public body", |
| 1580 | url="https://www.reddit.com/r/test/comments/r1/x/", |
| 1581 | snippet="Public thread snippet", |
| 1582 | ) |
| 1583 | private_item = schema.SourceItem( |
| 1584 | item_id="C1", |
| 1585 | source="corpus", |
| 1586 | title="Private note", |
| 1587 | body="private body", |
| 1588 | url="corpus://private.md", |
| 1589 | snippet="LONGER PRIVATE CORPUS SNIPPET THAT WON DURING FUSION", |
| 1590 | ) |
| 1591 | candidate = schema.Candidate( |
| 1592 | candidate_id="cand-1", |
| 1593 | item_id="R1", |
| 1594 | source="reddit", |
| 1595 | title="Public thread", |
| 1596 | url=public_item.url, |
| 1597 | snippet=private_item.snippet, |
| 1598 | subquery_labels=["primary"], |
| 1599 | native_ranks={"primary:reddit": 1, "primary:corpus": 2}, |
| 1600 | local_relevance=0.9, |
| 1601 | freshness=90, |
| 1602 | engagement=10, |
| 1603 | source_quality=1.0, |
| 1604 | rrf_score=0.03, |
| 1605 | sources=["reddit", "corpus"], |
| 1606 | source_items=[public_item, private_item], |
| 1607 | ) |
| 1608 | report = _make_report( |
| 1609 | subqueries=[ |
| 1610 | schema.SubQuery( |
| 1611 | label="primary", search_query="acme", ranking_query="acme", |
| 1612 | sources=["reddit", "corpus"], |
| 1613 | ) |
| 1614 | ], |
| 1615 | source_weights={"reddit": 0.5, "corpus": 0.5}, |
| 1616 | ranked_candidates=[candidate], |
| 1617 | clusters=[], |
| 1618 | items_by_source={"reddit": [public_item], "corpus": [private_item]}, |
| 1619 | ) |
| 1620 | |
| 1621 | clean = schema.without_sources(report, {"corpus"}) |
| 1622 | assert clean.ranked_candidates[0].snippet == "Public thread snippet" |
| 1623 | |
| 1624 | |
| 1625 | # --------------------------------------------------------------------------- |
| 1626 | # HIGH-034 & HIGH-035: dates.parse_date & dates.timestamp_to_date |
| 1627 | # --------------------------------------------------------------------------- |
| 1628 | |
| 1629 | |
| 1630 | class TestHigh034And035DatesParsing: |
| 1631 | @pytest.mark.parametrize( |
| 1632 | "bad_value", |
| 1633 | [ |
| 1634 | "1e20", |
| 1635 | "-1e20", |
| 1636 | "inf", |
| 1637 | "-inf", |
| 1638 | "nan", |
| 1639 | "99999999999999999999", |
| 1640 | True, |
| 1641 | False, |
| 1642 | float("inf"), |
| 1643 | float("-inf"), |
| 1644 | float("nan"), |
| 1645 | 1e20, |
| 1646 | -1e20, |
| 1647 | 10**400, |
| 1648 | -(10**400), |
| 1649 | "9999-12-31 23:59:59-01:00", |
| 1650 | "9999-12-31T23:59:59-01:00", |
| 1651 | "0001-01-01 00:00:00+01:00", |
| 1652 | "0001-01-01T00:00:00+01:00", |
| 1653 | None, |
| 1654 | "", |
| 1655 | " ", |
| 1656 | ], |
| 1657 | ) |
| 1658 | def test_parse_date_returns_none_on_overflow_nonfinite_and_bool(self, bad_value): |
| 1659 | assert dates.parse_date(bad_value) is None |
| 1660 | |
| 1661 | def test_reader_end_date_and_is_today_survive_astimezone_overflow(self): |
| 1662 | from datetime import date, timedelta |
| 1663 | |
| 1664 | boundary_now = datetime(9999, 12, 31, 23, 30, tzinfo=timezone(timedelta(hours=-2))) |
| 1665 | assert dates.reader_end_date("2026-04-01", now=boundary_now) == date(2026, 4, 1) |
| 1666 | assert dates.is_today("2026-04-01", now=boundary_now) is False |
| 1667 | assert dates.is_today("9999-12-31", now=boundary_now) is True |
| 1668 | |
| 1669 | @pytest.mark.parametrize( |
| 1670 | "bad_ts", |
| 1671 | [ |
| 1672 | None, |
| 1673 | True, |
| 1674 | False, |
| 1675 | float("inf"), |
| 1676 | float("-inf"), |
| 1677 | float("nan"), |
| 1678 | 1e20, |
| 1679 | -1e20, |
| 1680 | 10**25, |
| 1681 | 10**400, |
| 1682 | -(10**400), |
| 1683 | "bad", |
| 1684 | "1768435200", |
| 1685 | ], |
| 1686 | ) |
| 1687 | def test_timestamp_to_date_returns_none_on_overflow_nonfinite_and_bool(self, bad_ts): |
| 1688 | assert dates.timestamp_to_date(bad_ts) is None |
| 1689 | |
| 1690 | def test_windows_oserror_in_fromtimestamp_returns_none(self, monkeypatch): |
| 1691 | class _RaisingDateTime(datetime): |
| 1692 | @classmethod |
| 1693 | def fromtimestamp(cls, *_args, **_kwargs): |
| 1694 | raise OSError("Windows errno 22") |
| 1695 | |
| 1696 | monkeypatch.setattr(dates, "datetime", _RaisingDateTime) |
| 1697 | assert dates.parse_date("1768435200") is None |
| 1698 | assert dates.timestamp_to_date(1768435200) is None |
| 1699 | |
| 1700 | def test_compact_yyyymmdd_bare_year_and_zero_not_misparsed_as_1970(self): |
| 1701 | compact = dates.parse_date("20260401") |
| 1702 | assert compact == datetime(2026, 4, 1, 0, 0, tzinfo=timezone.utc) |
| 1703 | |
| 1704 | assert dates.parse_date("2026") is None |
| 1705 | assert dates.parse_date("0") is None |
| 1706 | assert dates.parse_date("-1") is None |
| 1707 | assert dates.parse_date("12345") is None |
| 1708 | assert dates.parse_date("20261345") is None |
| 1709 | |
| 1710 | @pytest.mark.parametrize( |
| 1711 | ("raw", "expected"), |
| 1712 | [ |
| 1713 | ("2026-04-01", datetime(2026, 4, 1, 0, 0, tzinfo=timezone.utc)), |
| 1714 | ("20260401", datetime(2026, 4, 1, 0, 0, tzinfo=timezone.utc)), |
| 1715 | ("2026-04-01T12:34:56", datetime(2026, 4, 1, 12, 34, 56, tzinfo=timezone.utc)), |
| 1716 | ( |
| 1717 | "2026-04-01T12:34:56.123456", |
| 1718 | datetime(2026, 4, 1, 12, 34, 56, 123456, tzinfo=timezone.utc), |
| 1719 | ), |
| 1720 | ( |
| 1721 | "2026-04-01T12:34:56.123456Z", |
| 1722 | datetime(2026, 4, 1, 12, 34, 56, 123456, tzinfo=timezone.utc), |
| 1723 | ), |
| 1724 | ( |
| 1725 | "2026-04-01 12:34:56", |
| 1726 | datetime(2026, 4, 1, 12, 34, 56, tzinfo=timezone.utc), |
| 1727 | ), |
| 1728 | ( |
| 1729 | "2026-04-01 12:34:56.500000+02:00", |
| 1730 | datetime(2026, 4, 1, 10, 34, 56, 500000, tzinfo=timezone.utc), |
| 1731 | ), |
| 1732 | ( |
| 1733 | "2026-04-01T12:34:56+0000", |
| 1734 | datetime(2026, 4, 1, 12, 34, 56, tzinfo=timezone.utc), |
| 1735 | ), |
| 1736 | ( |
| 1737 | " 2026-04-01T12:34:56Z ", |
| 1738 | datetime(2026, 4, 1, 12, 34, 56, tzinfo=timezone.utc), |
| 1739 | ), |
| 1740 | ], |
| 1741 | ) |
| 1742 | def test_parse_date_iso_8601_variants_normalize_to_utc(self, raw, expected): |
| 1743 | parsed = dates.parse_date(raw) |
| 1744 | assert parsed == expected |
| 1745 | assert parsed.tzinfo == timezone.utc |
| 1746 | |
| 1747 | @pytest.mark.parametrize( |
| 1748 | ("raw", "expected"), |
| 1749 | [ |
| 1750 | ("1768435200", datetime(2026, 1, 15, 0, 0, tzinfo=timezone.utc)), |
| 1751 | ("1710460800.5", datetime(2024, 3, 15, 0, 0, 0, 500000, tzinfo=timezone.utc)), |
| 1752 | ("946684800", datetime(2000, 1, 1, 0, 0, tzinfo=timezone.utc)), |
| 1753 | (1768435200, datetime(2026, 1, 15, 0, 0, tzinfo=timezone.utc)), |
| 1754 | ], |
| 1755 | ) |
| 1756 | def test_parse_date_preserves_valid_unix_epoch_seconds(self, raw, expected): |
| 1757 | parsed = dates.parse_date(raw) |
| 1758 | assert parsed == expected |
| 1759 | assert parsed.tzinfo == timezone.utc |
| 1760 | |
| 1761 | def test_grounding_normalize_date_does_not_drop_compact_yyyymmdd_or_bare_year(self): |
| 1762 | assert grounding._normalize_date("20260401") == "2026-04-01" |
| 1763 | assert not grounding._known_date_out_of_range( |
| 1764 | grounding._normalize_date("20260401"), ("2026-03-15", "2026-04-15"), |
| 1765 | ) |
| 1766 | assert grounding._normalize_date("2026") is None |
| 1767 | assert not grounding._known_date_out_of_range( |
| 1768 | grounding._normalize_date("2026"), ("2026-03-15", "2026-04-15"), |
| 1769 | ) |
| 1770 |