| 1 | """Exercise provider accounting through real child processes and SQLite.""" |
| 2 | |
| 3 | import json |
| 4 | import subprocess |
| 5 | from pathlib import Path |
| 6 | from types import SimpleNamespace |
| 7 | |
| 8 | import pytest |
| 9 | |
| 10 | import store |
| 11 | import watchlist |
| 12 | from lib import usage |
| 13 | |
| 14 | |
| 15 | @pytest.fixture |
| 16 | def isolated_store(tmp_path, monkeypatch): |
| 17 | monkeypatch.setattr(store, "_db_override", tmp_path / "research.db") |
| 18 | store.init_db() |
| 19 | store.set_setting("daily_budget", "1.00") |
| 20 | for name in ("First", "Second", "Third"): |
| 21 | store.add_topic(name) |
| 22 | |
| 23 | |
| 24 | def install_child(tmp_path, monkeypatch, *, cost=0.6, fail=False, free=False, after=""): |
| 25 | script_dir = Path(watchlist.__file__).resolve().parent |
| 26 | child = tmp_path / "last30days.py" |
| 27 | child.write_text( |
| 28 | "import io, json, sys\n" |
| 29 | f"sys.path.insert(0, {str(script_dir)!r})\n" |
| 30 | "from lib import http, providers\n" |
| 31 | f"payload = {{'choices': [{{'message': {{'content': 'ok'}}}}], 'usage': {{'cost': {cost!r}}}}}\n" |
| 32 | "class Response(io.BytesIO):\n" |
| 33 | " status = 200\n" |
| 34 | "def respond(req, timeout):\n" |
| 35 | " return Response(json.dumps(payload).encode())\n" |
| 36 | "http._open_request = respond\n" |
| 37 | + ( |
| 38 | "http.get('https://www.reddit.com/r/example.json')\n" |
| 39 | if free else |
| 40 | "providers.OpenRouterClient('dummy-key').generate_text('example/model', 'prompt')\n" |
| 41 | ) |
| 42 | + ("raise SystemExit(1)\n" if fail else "") |
| 43 | + after |
| 44 | + "\ntopic = sys.argv[sys.argv.index('--') + 1]\n" |
| 45 | "print(json.dumps({'topic': topic, 'range_from': '2026-01-01', 'range_to': '2026-04-01', " |
| 46 | "'generated_at': '2026-04-01T00:00:00Z', 'provider_runtime': {'reasoning_provider': 'local', " |
| 47 | "'planner_model': 'local', 'rerank_model': 'local'}, 'query_plan': {'intent': 'test', " |
| 48 | "'freshness_mode': 'recent', 'cluster_mode': 'standard', 'raw_topic': topic}}))\n" |
| 49 | ) |
| 50 | monkeypatch.setattr(watchlist, "SCRIPT_DIR", tmp_path) |
| 51 | |
| 52 | |
| 53 | def test_paid_topics_continue_below_budget_and_stop_at_limit(isolated_store, tmp_path, monkeypatch, capsys): |
| 54 | install_child(tmp_path, monkeypatch) |
| 55 | watchlist.cmd_run_all(None) |
| 56 | output = json.loads(capsys.readouterr().out) |
| 57 | assert output["budget_used"] == pytest.approx(1.2) |
| 58 | assert [row["status"] for row in output["results"]] == ["completed", "completed", "skipped"] |
| 59 | |
| 60 | |
| 61 | def test_spend_survives_later_child_failure(isolated_store, tmp_path, monkeypatch, capsys): |
| 62 | install_child(tmp_path, monkeypatch, cost=1.25, fail=True) |
| 63 | watchlist.cmd_run_all(None) |
| 64 | output = json.loads(capsys.readouterr().out) |
| 65 | assert output["budget_used"] == pytest.approx(1.25) |
| 66 | assert [row["status"] for row in output["results"]] == ["failed", "skipped", "skipped"] |
| 67 | |
| 68 | |
| 69 | def test_free_topics_do_not_consume_budget(isolated_store, tmp_path, monkeypatch, capsys): |
| 70 | install_child(tmp_path, monkeypatch, free=True) |
| 71 | watchlist.cmd_run_all(None) |
| 72 | output = json.loads(capsys.readouterr().out) |
| 73 | assert output["budget_used"] == 0 |
| 74 | assert [row["status"] for row in output["results"]] == ["completed"] * 3 |
| 75 | |
| 76 | |
| 77 | def test_missing_paid_cost_is_explicit_and_blocks_next_topic(isolated_store, tmp_path, monkeypatch, capsys): |
| 78 | install_child(tmp_path, monkeypatch, cost=None) |
| 79 | watchlist.cmd_run_all(None) |
| 80 | output = json.loads(capsys.readouterr().out) |
| 81 | assert [row["status"] for row in output["results"]] == ["completed", "skipped", "skipped"] |
| 82 | assert output["budget_unknown_runs"] == 1 |
| 83 | assert "unknown" in output["results"][1]["reason"].lower() |
| 84 | |
| 85 | |
| 86 | def test_completed_spend_survives_child_timeout(isolated_store, tmp_path, monkeypatch, capsys): |
| 87 | install_child(tmp_path, monkeypatch, cost=1.25, after="import time; time.sleep(60)\n") |
| 88 | run = subprocess.run |
| 89 | |
| 90 | def short_timeout(*args, **kwargs): |
| 91 | kwargs["timeout"] = 1 |
| 92 | return run(*args, **kwargs) |
| 93 | |
| 94 | monkeypatch.setattr(watchlist.subprocess, "run", short_timeout) |
| 95 | watchlist.cmd_run_all(None) |
| 96 | output = json.loads(capsys.readouterr().out) |
| 97 | assert output["budget_used"] == pytest.approx(1.25) |
| 98 | assert output["results"][0]["error"] == "timeout" |
| 99 | assert [row["status"] for row in output["results"]] == ["failed", "skipped", "skipped"] |
| 100 | |
| 101 | |
| 102 | def test_partial_unknown_spend_retains_known_subtotal(isolated_store, tmp_path, monkeypatch, capsys): |
| 103 | install_child( |
| 104 | tmp_path, monkeypatch, cost=0.4, |
| 105 | after="http.post('https://api.openai.com/v1/responses', {'model': 'example'})\n", |
| 106 | ) |
| 107 | watchlist.cmd_run_all(None) |
| 108 | output = json.loads(capsys.readouterr().out) |
| 109 | assert output["budget_used"] == pytest.approx(0.4) |
| 110 | assert output["budget_unknown_runs"] == 1 |
| 111 | assert [row["status"] for row in output["results"]] == ["completed", "skipped", "skipped"] |
| 112 | |
| 113 | |
| 114 | def test_run_one_respects_spend_from_previous_failure(isolated_store, tmp_path, monkeypatch, capsys): |
| 115 | install_child(tmp_path, monkeypatch, cost=1.25, fail=True) |
| 116 | watchlist._run_topic(store.get_topic("First")) |
| 117 | args = type("Args", (), {"topic": "Second"})() |
| 118 | watchlist.cmd_run_one(args) |
| 119 | output = json.loads(capsys.readouterr().out) |
| 120 | assert output["status"] == "skipped" |
| 121 | assert store.get_daily_cost() == pytest.approx(1.25) |
| 122 | |
| 123 | |
| 124 | @pytest.mark.parametrize( |
| 125 | ("cost", "unknown", "reason"), |
| 126 | [(1.25, 0, "Budget exceeded"), (0.4, 1, "Budget unknown")], |
| 127 | ) |
| 128 | def test_removing_topic_preserves_budget_gate(isolated_store, cost, unknown, reason, capsys): |
| 129 | first = store.get_topic("First") |
| 130 | run_id = store.record_run(first["id"], status="failed", token_cost=cost) |
| 131 | store.update_run(run_id, cost_unknown=unknown) |
| 132 | watchlist.cmd_remove(SimpleNamespace(topic="First")) |
| 133 | assert json.loads(capsys.readouterr().out)["action"] == "removed" |
| 134 | |
| 135 | watchlist.cmd_list(None) |
| 136 | listing = json.loads(capsys.readouterr().out) |
| 137 | assert [topic["name"] for topic in listing["topics"]] == ["Second", "Third"] |
| 138 | assert listing["budget_used"] == pytest.approx(cost) |
| 139 | assert listing["budget_unknown_runs"] == unknown |
| 140 | watchlist.cmd_run_one(SimpleNamespace(topic="Second")) |
| 141 | skipped = json.loads(capsys.readouterr().out) |
| 142 | assert skipped["status"] == "skipped" |
| 143 | assert skipped["reason"].startswith(reason) |
| 144 | |
| 145 | |
| 146 | def test_late_usage_for_removed_run_does_not_overwrite_a_new_run(isolated_store): |
| 147 | third = store.get_topic("Third") |
| 148 | removed_run = store.record_run(third["id"], status="running") |
| 149 | store.update_run(removed_run, status="completed") |
| 150 | assert store.remove_topic("Third") |
| 151 | assert store.get_daily_unknown_cost_runs() == 1 |
| 152 | |
| 153 | replacement = store.add_topic("Replacement") |
| 154 | assert replacement["id"] == third["id"] |
| 155 | current_run = store.record_run(replacement["id"], token_cost=0.25) |
| 156 | assert current_run != removed_run |
| 157 | assert store.store_findings( |
| 158 | removed_run, third["id"], [{"source_url": "https://example.invalid/discarded"}], |
| 159 | ) == {"new": 0, "updated": 0} |
| 160 | store.update_run(removed_run, token_cost=1.25, cost_unknown=0) |
| 161 | assert store.get_daily_cost() == pytest.approx(1.50) |
| 162 | assert store.get_daily_unknown_cost_runs() == 0 |
| 163 | assert store.get_latest_completed_runs(replacement["id"])[0]["token_cost"] == 0.25 |
| 164 | assert store.get_stats()["runs_7d"] == 1 |
| 165 | assert not store.search_findings("discarded") |
| 166 | |
| 167 | |
| 168 | @pytest.mark.parametrize("failure", ["directory", "journal"]) |
| 169 | def test_prelaunch_setup_failure_does_not_block_later_research( |
| 170 | isolated_store, tmp_path, monkeypatch, capsys, failure, |
| 171 | ): |
| 172 | install_child(tmp_path, monkeypatch) |
| 173 | topic = store.get_topic("First") |
| 174 | with monkeypatch.context() as setup_failure: |
| 175 | if failure == "directory": |
| 176 | unavailable = tmp_path / "not-a-directory" |
| 177 | unavailable.write_text("file blocks temporary directory creation") |
| 178 | setup_failure.setattr(watchlist.tempfile, "tempdir", str(unavailable)) |
| 179 | else: |
| 180 | original_open = usage.os.open |
| 181 | |
| 182 | def deny_journal(path, *args, **kwargs): |
| 183 | if Path(path).name == "usage.db": |
| 184 | raise PermissionError("journal creation denied") |
| 185 | return original_open(path, *args, **kwargs) |
| 186 | |
| 187 | setup_failure.setattr(usage.os, "open", deny_journal) |
| 188 | with pytest.raises(OSError): |
| 189 | watchlist._run_topic(topic) |
| 190 | |
| 191 | assert store.get_daily_unknown_cost_runs() == 0 |
| 192 | assert store.get_daily_cost() == 0 |
| 193 | watchlist.cmd_run_one(SimpleNamespace(topic="First")) |
| 194 | output = json.loads(capsys.readouterr().out) |
| 195 | assert output["status"] == "completed" |
| 196 | assert store.get_daily_cost() == pytest.approx(0.6) |
| 197 |