From 7c0032eef9f6dd9c22a585c8eccb33ca5bf55044 Mon Sep 17 00:00:00 2001 From: afterimaginary <126125402+afterimaginary@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:40:11 -0800 Subject: [PATCH 1/2] Paid commands stop early without API credentials `run --model ` and `estimate --counter api` now check that the SDK found credentials before doing any work, and stop with one line saying none were found and how to provide them, instead of dying on the SDK's bare TypeError at the first request (after `run` had already written its estimate). The check reads the client's auth headers and credentials provider, so nothing is sent. `best_counter` uses the same check in place of catching the TypeError. Closes #109 Co-Authored-By: Claude Opus 5.5 --- src/backread_exp/estimate.py | 37 +++++++++++++++++-------- src/backread_exp/grid.py | 19 +++++++++++-- tests/test_estimate.py | 13 +++++++++ tests/test_run.py | 53 ++++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 14 deletions(-) diff --git a/src/backread_exp/estimate.py b/src/backread_exp/estimate.py index a38e626..bae9ebe 100644 --- a/src/backread_exp/estimate.py +++ b/src/backread_exp/estimate.py @@ -136,29 +136,42 @@ def count( return counted.input_tokens +NO_CREDENTIALS = ( + "no Anthropic API credentials found; set an API key in the environment or run `ant auth login`" +) + + +def has_credentials(client: anthropic.Anthropic) -> bool: + """Whether the SDK found credentials for `client`, checked without sending anything. + + The SDK finds credentials itself, from the environment or an `ant auth login` profile. When + it finds none, building the client still works and the first request raises a bare + `TypeError` ("Could not resolve authentication method"), so callers check this first. It + mirrors the SDK's own check: an auth header from a key or token, or a credentials provider. + """ + return bool(client.auth_headers) or client.credentials is not None + + def best_counter( model: str, *, client: Callable[[], anthropic.Anthropic] = anthropic.Anthropic, say: Callable[[str], None] = print, ) -> TokenCounter: - """`ApiCounter` if the API answers for `model` with the credentials found, else `CharCounter`. - - The SDK finds credentials itself, from the environment or an `ant auth login` profile. When - it finds none it raises a `TypeError` ("Could not resolve authentication method") on the - first request rather than an `AnthropicError`, so that one is caught too. - """ + """`ApiCounter` if the API answers for `model` with the credentials found, else + `CharCounter`.""" try: - counter = ApiCounter(client().with_options(max_retries=8)) + made = client() + if not has_credentials(made): + say( + "Token counting unavailable (no API credentials found); estimating from characters." + ) + return CharCounter() + counter = ApiCounter(made.with_options(max_retries=8)) counter.count(model, [{"role": "user", "content": "hi"}], [], PROBE_SCHEMA, "low") except anthropic.AnthropicError as error: say(f"Token counting unavailable ({type(error).__name__}); estimating from characters.") return CharCounter() - except TypeError as error: - if "authentication" not in str(error): - raise - say("Token counting unavailable (no API credentials found); estimating from characters.") - return CharCounter() return counter diff --git a/src/backread_exp/grid.py b/src/backread_exp/grid.py index a9b23ef..53d6326 100644 --- a/src/backread_exp/grid.py +++ b/src/backread_exp/grid.py @@ -4,7 +4,9 @@ --model claude-haiku-5-5 --max-usd 2 uv run python -m backread_exp estimate # the core grid, as `make estimate` prints -`run` prints its estimate before the first request and refuses to start without `--max-usd`, +A paid `run`, and `estimate --counter api`, refuse to start when the SDK finds no Anthropic API +credentials. `run` prints its estimate before the first request and refuses to start without +`--max-usd`, which caps the run's spend over every attempt in its run directory: ledger spend under the same run id from before the directory was created, by a run since moved aside, isn't counted. A paid run also refuses to start while any memory it needs is missing. `--model fake` runs offline @@ -39,6 +41,7 @@ ) from backread_exp.dataset import Case, load_practice from backread_exp.estimate import ( + NO_CREDENTIALS, ApiCounter, CharCounter, RunEstimate, @@ -47,6 +50,7 @@ best_counter, estimate_run, format_estimate, + has_credentials, ) from backread_exp.gates import PILOT_CASES, harness_hash, save_pilot_estimate from backread_exp.memories import estimate_memories @@ -198,11 +202,20 @@ def spec_for( return RunSpec(model, effort, question_set or default_set, tuple(arms), cases) +def require_credentials() -> None: + """Refuse a paid command before it does any work if the SDK finds no credentials, rather + than let the first request die with the SDK's bare `TypeError`.""" + if not has_credentials(anthropic.Anthropic()): + raise RunError(NO_CREDENTIALS) + + def run_command(args: argparse.Namespace, *, say: Say = print) -> None: spec = spec_for(args.model, args.arms, args.cases, args.effort, args.question_set) + fake = spec.model == FAKE + if not fake: + require_credentials() harness = harness_hash() check_size(spec.cases, args.gates, harness) # before loading anything - fake = spec.model == FAKE run_id: str = args.run_id or f"{spec.question_set}-{spec.model}" run_dir: Path = (args.runs_dir or (FAKE_RUNS_DIR if fake else RUNS_DIR)) / run_id items = grid(select(read_manifest(), spec.question_set, spec.cases), spec.arms) @@ -322,6 +335,8 @@ def estimate_command(args: argparse.Namespace, *, say: Say = print) -> None: ] if given: raise RunError(f"{', '.join(given)} need --model; the core grid fixes them") + if args.counter == "api": + require_credentials() cases = practice_cases() manifest = read_manifest() memories = MemoryFiles() diff --git a/tests/test_estimate.py b/tests/test_estimate.py index 6f7ab4a..d151f17 100644 --- a/tests/test_estimate.py +++ b/tests/test_estimate.py @@ -6,6 +6,7 @@ import anthropic import pytest +from anthropic.lib.credentials import AccessToken from anthropic.types import MessageParam, ToolParam from grid_fixtures import CASES, QUESTIONS_PER_CYCLE, Memories, NoMemories, case, entries @@ -18,6 +19,7 @@ best_counter, estimate_run, format_estimate, + has_credentials, ) from backread_exp.model import Effort from backread_exp.run import grid @@ -188,3 +190,14 @@ def broken() -> anthropic.Anthropic: with pytest.raises(TypeError, match="unexpected keyword"): best_counter(MODEL, client=broken, say=print) + + +@pytest.mark.usefixtures("no_credentials") +def test_has_credentials_sees_what_the_sdk_found() -> None: + assert not has_credentials(anthropic.Anthropic()) + assert has_credentials(anthropic.Anthropic(auth_token="a token")) + + def provider(*, force_refresh: bool = False) -> AccessToken: + return AccessToken("a token") + + assert has_credentials(anthropic.Anthropic(credentials=provider)) diff --git a/tests/test_run.py b/tests/test_run.py index 132c7aa..e941dfb 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -371,6 +371,12 @@ def no_loading() -> None: assert not (tmp_path / "main-fake").exists() +@pytest.fixture +def credentials_found(monkeypatch: pytest.MonkeyPatch) -> None: + """Let a paid run past its credentials check; its model and counter are faked anyway.""" + monkeypatch.setattr(cli, "require_credentials", lambda: None) + + def synthetic_data(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(cli, "practice_cases", lambda: CASES) monkeypatch.setattr(cli, "read_manifest", entries) @@ -473,6 +479,7 @@ def complete(self, *args: Any, **kwargs: Any) -> Reply: return self._inner.complete(*args, **kwargs) +@pytest.mark.usefixtures("credentials_found") def test_an_error_in_a_paid_run_stops_every_further_paid_call( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -524,6 +531,7 @@ def __init__(self) -> None: super().__init__("claude-haiku-5-5") +@pytest.mark.usefixtures("credentials_found") def test_a_paid_run_caps_only_spend_since_its_directory_was_created( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: @@ -640,6 +648,7 @@ def test_run_locks_are_ignored() -> None: assert ignored.returncode == 0 +@pytest.mark.usefixtures("credentials_found") def test_a_paid_run_refuses_to_start_without_its_memories( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: @@ -699,6 +708,50 @@ def test_estimate_without_credentials_falls_back_to_characters( assert any(line.split()[:1] == ["total"] and "$" in line for line in said) +NO_CREDENTIALS_LINE = ( + "error: no Anthropic API credentials found; " + "set an API key in the environment or run `ant auth login`" +) + + +@pytest.mark.usefixtures("no_credentials") +def test_a_paid_run_without_credentials_stops_before_doing_anything( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + def no_work(*args: object, **kwargs: object) -> None: + raise AssertionError("did work before checking for credentials") + + for name in ("harness_hash", "check_size", "practice_cases", "read_manifest", "best_counter"): + monkeypatch.setattr(cli, name, no_work) + args = run_args(tmp_path, "--cases", "1", "--max-usd", "1") + args[4] = "claude-haiku-5-5" + assert main(args) == 1 + assert lines(capsys) == [f"run: {NO_CREDENTIALS_LINE}"] + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.usefixtures("no_credentials") +def test_a_fake_run_needs_no_credentials( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + synthetic_data(monkeypatch) + assert main(run_args(tmp_path, "--cases", "1", "--max-usd", "1")) == 0 + assert lines(capsys)[-1].startswith("Done: ") + + +@pytest.mark.usefixtures("no_credentials") +def test_estimate_with_the_api_counter_and_no_credentials_stops_before_doing_anything( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + def no_work(*args: object, **kwargs: object) -> None: + raise AssertionError("did work before checking for credentials") + + for name in ("practice_cases", "read_manifest", "MemoryFiles"): + monkeypatch.setattr(cli, name, no_work) + assert main(["estimate", "--counter", "api", "--model", "claude-haiku-5-5"]) == 1 + assert lines(capsys) == [f"estimate: {NO_CREDENTIALS_LINE}"] + + def core_grid( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], *extra: str ) -> dict[str, dict[str, int]]: From 57897316ef0ef76fc03fd75b0c9585c466216c13 Mon Sep 17 00:00:00 2001 From: afterimaginary <126125402+afterimaginary@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:44:17 -0800 Subject: [PATCH 2/2] Tidy the credentials check after review Keep the message next to the check in grid.py and close the client built for it. Drop the test of the removed TypeError handler, update its neighbour's docstring, spell out the paid run's arguments in the new test, and rewrap the module docstring. Co-Authored-By: Claude Opus 5.5 --- src/backread_exp/estimate.py | 5 ----- src/backread_exp/grid.py | 25 +++++++++++++++---------- tests/test_estimate.py | 11 ++--------- tests/test_run.py | 4 ++-- 4 files changed, 19 insertions(+), 26 deletions(-) diff --git a/src/backread_exp/estimate.py b/src/backread_exp/estimate.py index bae9ebe..fbf54fb 100644 --- a/src/backread_exp/estimate.py +++ b/src/backread_exp/estimate.py @@ -136,11 +136,6 @@ def count( return counted.input_tokens -NO_CREDENTIALS = ( - "no Anthropic API credentials found; set an API key in the environment or run `ant auth login`" -) - - def has_credentials(client: anthropic.Anthropic) -> bool: """Whether the SDK found credentials for `client`, checked without sending anything. diff --git a/src/backread_exp/grid.py b/src/backread_exp/grid.py index 53d6326..9ba37d6 100644 --- a/src/backread_exp/grid.py +++ b/src/backread_exp/grid.py @@ -6,13 +6,13 @@ A paid `run`, and `estimate --counter api`, refuse to start when the SDK finds no Anthropic API credentials. `run` prints its estimate before the first request and refuses to start without -`--max-usd`, -which caps the run's spend over every attempt in its run directory: ledger spend under the same -run id from before the directory was created, by a run since moved aside, isn't counted. A paid -run also refuses to start while any memory it needs is missing. `--model fake` runs offline -against `AnsweringFake`, priced as Haiku so its dollars can be read against an estimate, with -placeholder text for any memory not produced yet; it makes no paid call, writes no ledger, and -keeps its runs under the ignored `data/cache/fake-runs/` unless `--runs-dir` says otherwise. +`--max-usd`, which caps the run's spend over every attempt in its run directory: ledger spend +under the same run id from before the directory was created, by a run since moved aside, isn't +counted. A paid run also refuses to start while any memory it needs is missing. `--model fake` +runs offline against `AnsweringFake`, priced as Haiku so its dollars can be read against an +estimate, with placeholder text for any memory not produced yet; it makes no paid call, writes no +ledger, and keeps its runs under the ignored `data/cache/fake-runs/` unless `--runs-dir` says +otherwise. Each start saves the whole run's estimate as `estimate.json`. A start of at most `gates.PILOT_CASES` cases also saves it as `pilot-estimate.json`, which the pilot's cost gate @@ -41,7 +41,6 @@ ) from backread_exp.dataset import Case, load_practice from backread_exp.estimate import ( - NO_CREDENTIALS, ApiCounter, CharCounter, RunEstimate, @@ -202,11 +201,17 @@ def spec_for( return RunSpec(model, effort, question_set or default_set, tuple(arms), cases) +NO_CREDENTIALS = ( + "no Anthropic API credentials found; set an API key in the environment or run `ant auth login`" +) + + def require_credentials() -> None: """Refuse a paid command before it does any work if the SDK finds no credentials, rather than let the first request die with the SDK's bare `TypeError`.""" - if not has_credentials(anthropic.Anthropic()): - raise RunError(NO_CREDENTIALS) + with anthropic.Anthropic() as client: + if not has_credentials(client): + raise RunError(NO_CREDENTIALS) def run_command(args: argparse.Namespace, *, say: Say = print) -> None: diff --git a/tests/test_estimate.py b/tests/test_estimate.py index d151f17..1937271 100644 --- a/tests/test_estimate.py +++ b/tests/test_estimate.py @@ -176,7 +176,8 @@ def no_client() -> anthropic.Anthropic: @pytest.mark.usefixtures("no_credentials") def test_best_counter_falls_back_to_characters_when_the_sdk_finds_no_credentials() -> None: - """The real SDK raises a `TypeError`, not an `AnthropicError`, when it finds no credentials.""" + """The real SDK builds a client with no credentials; the check catches that before a request, + which would raise a bare `TypeError`.""" said: list[str] = [] assert isinstance(best_counter(MODEL, say=said.append), CharCounter) assert said == [ @@ -184,14 +185,6 @@ def test_best_counter_falls_back_to_characters_when_the_sdk_finds_no_credentials ] -def test_best_counter_does_not_hide_other_type_errors() -> None: - def broken() -> anthropic.Anthropic: - raise TypeError("unexpected keyword argument") - - with pytest.raises(TypeError, match="unexpected keyword"): - best_counter(MODEL, client=broken, say=print) - - @pytest.mark.usefixtures("no_credentials") def test_has_credentials_sees_what_the_sdk_found() -> None: assert not has_credentials(anthropic.Anthropic()) diff --git a/tests/test_run.py b/tests/test_run.py index e941dfb..3694c68 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -723,8 +723,8 @@ def no_work(*args: object, **kwargs: object) -> None: for name in ("harness_hash", "check_size", "practice_cases", "read_manifest", "best_counter"): monkeypatch.setattr(cli, name, no_work) - args = run_args(tmp_path, "--cases", "1", "--max-usd", "1") - args[4] = "claude-haiku-5-5" + args = ["run", "--arms", "floor", "--model", "claude-haiku-5-5", "--cases", "1"] + args += ["--max-usd", "1", "--runs-dir", str(tmp_path)] assert main(args) == 1 assert lines(capsys) == [f"run: {NO_CREDENTIALS_LINE}"] assert list(tmp_path.iterdir()) == []