| 1 | """Only authoritative provider response amounts become budget dollars.""" |
| 2 | |
| 3 | import io |
| 4 | import json |
| 5 | import sqlite3 |
| 6 | import subprocess |
| 7 | from concurrent.futures import ThreadPoolExecutor |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | from lib import brightdata, grok_x, hosted, http, parallel_mcp, transcribe, usage, xurl_x |
| 12 | |
| 13 | |
| 14 | @pytest.fixture |
| 15 | def journal(tmp_path, monkeypatch): |
| 16 | path = tmp_path / "usage.db" |
| 17 | usage.create_journal(path) |
| 18 | monkeypatch.setenv(usage.JOURNAL_ENV, str(path)) |
| 19 | return path |
| 20 | |
| 21 | |
| 22 | def request(monkeypatch, url, payload): |
| 23 | class Response(io.BytesIO): |
| 24 | status = 200 |
| 25 | |
| 26 | monkeypatch.setattr(http, "_open_request", lambda req, timeout: Response(json.dumps(payload).encode())) |
| 27 | return http.post(url, {"model": "example"}, retries=1) |
| 28 | |
| 29 | |
| 30 | def test_perplexity_agent_records_usd_and_tokens(journal, monkeypatch): |
| 31 | request(monkeypatch, "https://api.perplexity.ai/v1/agent", { |
| 32 | "status": "completed", |
| 33 | "usage": {"input_tokens": 80, "output_tokens": 20, "cost": {"currency": "USD", "total_cost": 0.75}}, |
| 34 | }) |
| 35 | assert usage.read_journal(journal) == { |
| 36 | "token_cost": 0.75, "cost_unknown": 0, "prompt_tokens": 80, "completion_tokens": 20, |
| 37 | } |
| 38 | |
| 39 | |
| 40 | @pytest.mark.parametrize("cost", [None, True, -0.1, float("nan"), float("inf"), "0.50", {}]) |
| 41 | def test_invalid_cost_never_becomes_known_spend(journal, monkeypatch, cost): |
| 42 | request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": cost}}) |
| 43 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 44 | |
| 45 | |
| 46 | def test_usage_counts_and_non_usd_currency_are_unknown(journal, monkeypatch): |
| 47 | request(monkeypatch, "https://api.perplexity.ai/v1/agent", { |
| 48 | "usage": {"input_tokens": 1000, "cost": {"currency": "credits", "total_cost": 20}}, |
| 49 | }) |
| 50 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 51 | assert usage.read_journal(journal)["token_cost"] == 0 |
| 52 | |
| 53 | |
| 54 | def test_in_progress_remote_charge_is_unknown(journal, monkeypatch): |
| 55 | request(monkeypatch, "https://api.perplexity.ai/v1/agent", { |
| 56 | "status": "in_progress", "usage": {"cost": {"currency": "USD", "total_cost": 0.3}}, |
| 57 | }) |
| 58 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 59 | assert usage.read_journal(journal)["token_cost"] == 0.3 |
| 60 | |
| 61 | |
| 62 | def test_untrusted_search_result_cannot_add_cost(journal, monkeypatch): |
| 63 | request(monkeypatch, "https://example.org/article", {"usage": {"cost": 99.9}}) |
| 64 | assert usage.read_journal(journal)["token_cost"] == 0 |
| 65 | assert usage.read_journal(journal)["cost_unknown"] == 0 |
| 66 | |
| 67 | |
| 68 | def test_parallel_requests_keep_every_charge(journal, monkeypatch): |
| 69 | request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": 0.1}}) |
| 70 | with ThreadPoolExecutor(max_workers=5) as executor: |
| 71 | list(executor.map(lambda _: http.post("https://openrouter.ai/api/v1/chat/completions", {}), range(20))) |
| 72 | assert usage.read_journal(journal)["token_cost"] == pytest.approx(2.1) |
| 73 | assert usage.read_journal(journal)["cost_unknown"] == 0 |
| 74 | |
| 75 | |
| 76 | def test_pending_transport_is_unknown_and_journal_excludes_secrets(journal, monkeypatch): |
| 77 | def interrupted(req, timeout): |
| 78 | raise KeyboardInterrupt |
| 79 | |
| 80 | monkeypatch.setattr(http, "_open_request", interrupted) |
| 81 | with pytest.raises(KeyboardInterrupt): |
| 82 | http.post("https://openrouter.ai/api/v1/chat/completions?secret=forbidden-query", {"input": "forbidden-prompt"}, headers={"Authorization": "Bearer forbidden-token"}) |
| 83 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 84 | assert b"forbidden" not in journal.read_bytes() |
| 85 | assert journal.stat().st_mode & 0o777 == 0o600 |
| 86 | |
| 87 | |
| 88 | def test_unscoped_calls_have_no_accounting_side_effects(tmp_path, monkeypatch): |
| 89 | monkeypatch.delenv(usage.JOURNAL_ENV, raising=False) |
| 90 | request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": 0.1}}) |
| 91 | assert list(tmp_path.iterdir()) == [] |
| 92 | |
| 93 | |
| 94 | def test_broken_journal_remains_unknown(journal): |
| 95 | with sqlite3.connect(journal) as conn: |
| 96 | conn.execute("DROP TABLE attempts") |
| 97 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 98 | |
| 99 | |
| 100 | def test_transcription_charge_without_usd_remains_unknown(journal, tmp_path, monkeypatch): |
| 101 | audio = tmp_path / "sample.mp3" |
| 102 | audio.write_bytes(b"dummy-audio") |
| 103 | monkeypatch.setattr("urllib.request.urlopen", lambda *a, **kw: io.BytesIO(b'{"text":"words"}')) |
| 104 | assert transcribe._post_audio("openai", str(audio), "dummy-key", 1) == "words" |
| 105 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 106 | |
| 107 | |
| 108 | def test_brightdata_charge_without_usd_remains_unknown(journal, monkeypatch): |
| 109 | monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata") |
| 110 | monkeypatch.setattr(brightdata.subproc, "run_with_timeout", lambda *a, **kw: subprocess.CompletedProcess([], 0, "[]", "")) |
| 111 | brightdata.run_pipeline("gd_x", {}, timeout=1, config={"BRIGHTDATA_API_KEY": "dummy-key"}) |
| 112 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 113 | |
| 114 | |
| 115 | def test_grok_charge_without_usd_remains_unknown(journal, tmp_path, monkeypatch): |
| 116 | monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok") |
| 117 | monkeypatch.setattr(grok_x, "_stage_child_home", lambda _: str(tmp_path)) |
| 118 | calls = [] |
| 119 | |
| 120 | def run(cmd, **kwargs): |
| 121 | calls.append(cmd) |
| 122 | if cmd == ["/dummy/grok", "--version"]: |
| 123 | assert usage.read_journal(journal)["cost_unknown"] == 0 |
| 124 | return subprocess.CompletedProcess(cmd, 0, "grok 1.0.46 (2765805b9442)", "") |
| 125 | assert cmd[:3] == ["/dummy/grok", "-p", "topic"] |
| 126 | return subprocess.CompletedProcess(cmd, 0, "{}", "") |
| 127 | |
| 128 | monkeypatch.setattr(grok_x.subproc, "run_with_timeout", run) |
| 129 | assert grok_x._invoke("topic", 1) == {"text": "{}"} |
| 130 | assert len(calls) == 2 |
| 131 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 132 | |
| 133 | |
| 134 | def test_hosted_charge_without_usd_remains_unknown(journal, monkeypatch): |
| 135 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 136 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-key") |
| 137 | request(monkeypatch, "https://example.org", {}) |
| 138 | hosted.submit("topic", "quick") |
| 139 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 140 | |
| 141 | |
| 142 | def test_authenticated_parallel_tool_charge_without_usd_remains_unknown(journal, monkeypatch): |
| 143 | class Response(io.BytesIO): |
| 144 | headers = {"Content-Type": "application/json"} |
| 145 | |
| 146 | class Opener: |
| 147 | def open(self, *args, **kwargs): |
| 148 | return Response(b'{"jsonrpc":"2.0","id":1,"result":{}}') |
| 149 | |
| 150 | monkeypatch.setattr("urllib.request.build_opener", lambda *args: Opener()) |
| 151 | parallel_mcp._request({"jsonrpc": "2.0", "id": 1, "method": "tools/call"}, "dummy-key") |
| 152 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 153 | |
| 154 | |
| 155 | def test_xurl_search_charge_without_usd_remains_unknown(journal, monkeypatch): |
| 156 | monkeypatch.setattr(xurl_x.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess([], 0, '{"data":[]}', "")) |
| 157 | assert xurl_x.search_x("topic") == {"data": []} |
| 158 | assert usage.read_journal(journal)["cost_unknown"] == 1 |
| 159 | |
| 160 | |
| 161 | def test_xurl_local_auth_probe_does_not_consume_budget(journal, monkeypatch): |
| 162 | monkeypatch.setattr(xurl_x.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess([], 0, "bearer: ✓", "")) |
| 163 | assert xurl_x._is_available_uncached() |
| 164 | assert usage.read_journal(journal)["cost_unknown"] == 0 |
| 165 | |
| 166 | |
| 167 | def test_missing_xurl_binary_has_no_charge(journal, monkeypatch): |
| 168 | def missing(*args, **kwargs): |
| 169 | raise FileNotFoundError |
| 170 | |
| 171 | monkeypatch.setattr(xurl_x.subprocess, "run", missing) |
| 172 | assert xurl_x.search_x("topic") == {"error": xurl_x.ERR_NOT_FOUND} |
| 173 | assert usage.read_journal(journal)["cost_unknown"] == 0 |
| 174 |