| 1 | import json |
| 2 | import re |
| 3 | import sys |
| 4 | import threading |
| 5 | from pathlib import Path |
| 6 | from unittest import mock |
| 7 | |
| 8 | import pytest |
| 9 | |
| 10 | import last30days as cli |
| 11 | from lib import http, pipeline, rerank, schema, subproc, youtube_yt |
| 12 | |
| 13 | |
| 14 | @pytest.mark.parametrize("slow", [False, True]) |
| 15 | def test_transcript_backfill_keeps_videos_within_the_remaining_budget(monkeypatch, slow): |
| 16 | now = [1000.0] |
| 17 | calls = [] |
| 18 | cancel = threading.Event() |
| 19 | transcript = "SQLite explains how write-ahead logging keeps concurrent readers working." |
| 20 | existing = schema.SourceItem( |
| 21 | item_id="recorded", source="youtube", title="SQLite introduction", |
| 22 | body="SQLite introduction", url="https://www.youtube.com/watch?v=recorded", |
| 23 | metadata={"transcript_snippet": "Existing transcript"}, |
| 24 | ) |
| 25 | survivor = schema.SourceItem( |
| 26 | item_id="survivor", source="youtube", title="SQLite write-ahead logging", |
| 27 | body="SQLite write-ahead logging", url="https://www.youtube.com/watch?v=survivor", |
| 28 | ) |
| 29 | |
| 30 | def run_ytdlp(command, *, timeout, deadline_monotonic=None, cancel=None): |
| 31 | calls.append((timeout, deadline_monotonic, cancel)) |
| 32 | if slow: |
| 33 | now[0] += timeout |
| 34 | raise subproc.SubprocTimeout("timed out") |
| 35 | target = Path(command[command.index("-o") + 1]).parent / "survivor.en.vtt" |
| 36 | target.write_text(f"WEBVTT\n\n00:00:00.000 --> 00:00:04.000\n{transcript}\n") |
| 37 | return subproc.SubprocResult(returncode=0, stdout="", stderr="") |
| 38 | |
| 39 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 40 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True) |
| 41 | monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None) |
| 42 | monkeypatch.setattr(subproc, "run_with_timeout", run_ytdlp) |
| 43 | |
| 44 | finalized = pipeline._finalize_items_by_source( |
| 45 | {"youtube": [existing, survivor]}, topic="SQLite", elapsed=275.0, |
| 46 | config={"_enrich_cancel": cancel}, |
| 47 | ) |
| 48 | |
| 49 | assert finalized["youtube"] == [existing, survivor] |
| 50 | assert existing.metadata["transcript_snippet"] == "Existing transcript" |
| 51 | assert calls == [(5.0, 1005.0, cancel)] |
| 52 | if slow: |
| 53 | assert "transcript_snippet" not in survivor.metadata |
| 54 | else: |
| 55 | assert survivor.metadata["transcript_snippet"] == transcript |
| 56 | |
| 57 | |
| 58 | @pytest.mark.parametrize("scenario", ["fast", "slow", "inherited", "command"]) |
| 59 | def test_report_keeps_evidence_when_reranking_runs_out_of_time(monkeypatch, capsys, scenario): |
| 60 | now = [1000.0] |
| 61 | timeouts = [] |
| 62 | topic = "SQLite write-ahead logging" |
| 63 | story = { |
| 64 | "id": "HN1", "title": topic, "url": "https://example.com/sqlite-wal", |
| 65 | "author": "sqlite-author", "date": "2026-10-25", |
| 66 | "engagement": {"points": 84, "comments": 12}, |
| 67 | } |
| 68 | plan = schema.QueryPlan( |
| 69 | raw_topic=topic, intent="technical", freshness_mode="balanced_recent", |
| 70 | cluster_mode="coverage", source_weights={"hackernews": 1.0}, |
| 71 | subqueries=[schema.SubQuery( |
| 72 | label="primary", search_query=topic, ranking_query=topic, |
| 73 | sources=["hackernews"], |
| 74 | )], |
| 75 | ) |
| 76 | finalize = pipeline._finalize_items_by_source |
| 77 | |
| 78 | def finalize_after_retrieval(*args, **kwargs): |
| 79 | now[0] += 273.0 |
| 80 | return finalize(*args, **kwargs) |
| 81 | |
| 82 | def open_request(request, timeout): |
| 83 | timeouts.append(timeout) |
| 84 | if scenario != "fast": |
| 85 | now[0] += timeout |
| 86 | raise TimeoutError("simulated socket timeout") |
| 87 | prompt = json.loads(request.data)["input"][0]["content"] |
| 88 | candidate_id = re.search(r"candidate_id: (\S+)", prompt).group(1) |
| 89 | body = {"scores": [{"candidate_id": candidate_id, "relevance": 94, "fun": 37}]} |
| 90 | response = mock.MagicMock(status=200) |
| 91 | response.__enter__.return_value = response |
| 92 | response.read.return_value = json.dumps({"output_text": json.dumps(body)}).encode() |
| 93 | return response |
| 94 | |
| 95 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 96 | monkeypatch.setattr(http.time, "sleep", lambda seconds: now.__setitem__(0, now[0] + seconds)) |
| 97 | monkeypatch.setattr(pipeline, "available_sources", lambda *args, **kwargs: ["hackernews"]) |
| 98 | monkeypatch.setattr(pipeline, "_retrieve_stream", lambda **kwargs: ([story], {})) |
| 99 | monkeypatch.setattr(http, "_open_request", open_request) |
| 100 | |
| 101 | config = {"XAI_API_KEY": "dummy-key"} |
| 102 | if scenario == "command": |
| 103 | def diagnose(*args, **kwargs): |
| 104 | now[0] += 273.0 |
| 105 | return {"available_sources": ["hackernews"]} |
| 106 | |
| 107 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: config) |
| 108 | monkeypatch.setattr(cli.pipeline, "diagnose", diagnose) |
| 109 | monkeypatch.setattr(sys, "argv", [ |
| 110 | "last30days.py", topic, "--quick", "--search=hackernews", |
| 111 | "--as-of=2026-10-26", "--web-backend=none", "--emit=json", |
| 112 | "--json-profile=raw", "--save-dir=", "--no-browser-cookies", |
| 113 | "--plan", json.dumps(schema.to_dict(plan)), |
| 114 | ]) |
| 115 | assert cli.main() == 0 |
| 116 | report = schema.report_from_dict(json.loads(capsys.readouterr().out)) |
| 117 | else: |
| 118 | if scenario == "inherited": |
| 119 | config["_research_deadline"] = 1280.0 |
| 120 | monkeypatch.setattr(pipeline, "_finalize_items_by_source", finalize_after_retrieval) |
| 121 | report = pipeline.run( |
| 122 | topic=topic, config=config, depth="quick", |
| 123 | requested_sources=["hackernews"], external_plan=schema.to_dict(plan), |
| 124 | as_of_date="2026-10-26", web_backend="none", |
| 125 | ) |
| 126 | |
| 127 | assert [item.url for item in report.items_by_source["hackernews"]] == [story["url"]] |
| 128 | candidate, = report.ranked_candidates |
| 129 | if scenario != "fast": |
| 130 | assert timeouts == ([] if scenario == "inherited" else [7.0]) |
| 131 | assert candidate.metadata[rerank.RERANK_PROVENANCE_KEY] == rerank.RERANK_PROVENANCE_FALLBACK |
| 132 | assert candidate.fun_explanation == "heuristic-fallback" |
| 133 | else: |
| 134 | assert timeouts == [7.0, 7.0] |
| 135 | assert candidate.rerank_score == 94 |
| 136 | assert candidate.fun_score == 37 |
| 137 |