Repository navigation
fix(haiku): strip ANTHROPIC_API_KEY from the nested claude -p child env - #693
Conversation
ANTHROPIC_API_KEY, when present anywhere in the host environment, takes precedence over the operator's claude.ai login for the nested claude -p call the summarizer spawns -- the CLI resolves credentials in that order. A key with an exhausted or unfunded balance then fails every background summarize silently: save-session.sh --force exits 1 at session end with "Credit balance is too low", while the operator's own interactive sessions keep working fine off the login, so nothing about the failure points at this var without reading the child's own stderr. Reproduced in production: repeated "save-session.sh --force exited 1" warnings traced via the daily narrative log to exactly this cause, compounded once by a genuine rate limit and separately by this auth routing issue. ANTHROPIC_API_KEY was never a "parent session" marker the way CLAUDE_CODE_* is; _child_env() now strips it for the same reason it already strips CLAUDE_PROJECT_DIR -- the child should authenticate as if launched fresh, not inherit a credential the operator did not choose for this subprocess. Adds test_call_haiku_strips_anthropic_api_key alongside the existing parent-session-stripping test. 80/80 tests pass.
fdaviddpt
left a comment
There was a problem hiding this comment.
Thank you for this -- the diagnosis is correct and the evidence is exactly what a report like this needs: the CLI's own stderr, the frequency, and the fact that interactive sessions kept working off the login while the background summarizer did not. That last detail is what makes this failure so hard to see, and you named it precisely.
I'm requesting changes on one thing, plus some repo mechanics.
The strip is unconditional, and that breaks a different set of installations
_child_env() keeps exactly one credential:
_CHILD_ENV_KEEP = frozenset({"CLAUDE_CODE_OAUTH_TOKEN"})
For an operator whose only credential is ANTHROPIC_API_KEY -- no claude.ai login, no setup-token, which is a normal and documented way to authenticate the Claude CLI -- this patch leaves the nested claude -p with nothing to authenticate with. Every background save then fails, silently, surfacing as the same opaque save-session.sh --force exited 1 you spent days tracing. That is the failure class this PR exists to remove, relocated onto a different population rather than removed.
Worth noting that ANTHROPIC_API_KEY appears nowhere in docs/, README.md or scripts/ today, so neither behaviour is documented and we have no data on how many installs depend on it. That argues for caution rather than for assuming nobody does.
What I'd like instead: strip it only when another credential is actually available. Concretely, keep ANTHROPIC_API_KEY when none of CLAUDE_CODE_OAUTH_TOKEN (in the child env), REMEMBER_OAUTH_TOKEN or haiku.oauth_token is present; strip it when one of them is, since that is the case your report describes -- an ambient key out-ranking a login the operator actually chose. _inject_configured_oauth_token() already resolves the configured-token half, so the check has somewhere natural to live.
Test coverage
The new test is a good positive control. It needs its negative twin, and this repo asks for that pairing explicitly (CLAUDE.md: "a negative assertion needs a positive control", and the same in reverse): a case where ANTHROPIC_API_KEY is the sole credential and therefore survives. Without it, a future refactor that strips unconditionally again passes the suite.
test_call_haiku_keeps_oauth_token is the pattern to mirror.
Repo mechanics
- A changelog fragment is a merge gate here. Add
changelog.d/<issue>.fixed.md-- one line, user-facing. Theoss changelogcheck fails without it. - No linked issue. A
Closes #Nline binds the PR to an issue; a bare#Ndoes not. Happy for you to file one describing the symptom, or I can. - CI on this PR was waiting on first-time-contributor approval; I've approved it, so the twelve legs will report shortly.
Separately, and not your problem to fix
Your logs showed the real cause in memory-*.log while hook-errors.log carried only the exit code. That propagation gap is a bug of ours independent of this change, and it is why this took days instead of minutes to find -- filed as #694 with your trace as the evidence. Thanks for surfacing it.
…hen it is the only credential @Mega-Therion diagnosed this and the strip itself is theirs; this commit makes it conditional, which is what the review asked for. An unconditional strip does not remove the reported outage, it relocates it: authenticating the CLI with ANTHROPIC_API_KEY alone is normal and documented, and for those installs dropping the key leaves the nested claude -p with no credential at all -- every background save failing silently, the same shape that took the reporter days to trace. So the key is now dropped only when another credential is visible (CLAUDE_CODE_OAUTH_TOKEN, a configured OAuth token, or a login at ~/.claude/.credentials.json) and kept when it is the only one there is. A login held in an OS keychain is invisible to this process, so auto keeps the key for those operators -- todays behaviour, not a new failure -- and the new haiku.anthropic_api_key config key (auto|keep|strip) is how they overrule it. An unrecognised value falls back to auto and says so, rather than grading silently as one of the two behaviours. A failure that looks like a credential failure now names the variable and the config key in the RuntimeError, so it reaches hook-errors.log where the operator is already looking rather than the daily log alone (#694). The marker list is deliberately narrow: a hint on every failure would point unrelated outages at an innocent variable. Tests pair every strip case with its keep twin -- an unconditional strip and an unconditional keep each fail here -- and the failure hint has both a negative control (no key set) and a wrong-cause control (key set, prompt-length failure). Co-Authored-By: Max <noreply>
|
I've finished this one, in #704. Your commit is the first of the two there, unchanged and under your name — #704 adds the condition my review asked for rather than replacing your work, and the issue it closes (#703) is filed with your trace as the evidence. Two things worth saying plainly. Why I did not push to your branch. That was my first move — What changed from your patch. The strip is now conditional. The negative twin — the key surviving when it is the only credential — is the test that fails against the original patch, and it is there so a future refactor cannot quietly strip again. Closing this in favour of #704. Thank you for the report; the trace in it is what made the whole thing tractable, and the framing in your description (interactive sessions fine, background summarizer dead) is what pointed at the credential order in the first place. [AI-generated] |
CodeQL was right: the warning quoted the rejected config value, and this keys NAME invites an operator to paste an actual API key into it. A typo would then have written that credential to the daily log in clear text -- a leaked secret on disk as the punishment for a misspelling. The warning now names the length and type, the legal values and the fallback, and says explicitly that the value is withheld and why. The test asserts the absence (a pasted key-shaped value must not appear) and gains its positive control: a recognised value warns about nothing, so warns-on-bad-value cannot silently become warns-on-everything. Co-Authored-By: Max <noreply>
|
Correction to my comment above: the push to this branch went through on a retry, so the work is here, not in #704 — I've closed that one as a duplicate. Your branch now carries three commits: yours, the conditional-strip rework, and one more described below. Nothing of yours was rewritten; both of mine sit on top of The third commit is worth naming, because CodeQL caught it on the second push and it was right to. My warning for an unrecognised I also added CI is running on the branch now. Once it is green this is ready to merge as yours. [AI-generated] |
|
Merging this — the change my earlier review asked for is in the branch, so treat that CHANGES_REQUESTED as answered rather than standing. (I could not clear the review itself: approving a pull request is an action my tooling holds back from me, which seems right. The maintainer's decision to merge is on the record here instead.) State at the merge, named rather than summarised:
Thank you again for the report, the trace, and the patch. Landing as yours. [AI-generated] |
…u failure detail to hook-errors.log (#714) * fix(#691,#694): stop sorting every transcript to read one, route Haiku failure detail to hook-errors.log #691: previous_transcript() (and its no-CURRENT_SESSION_ID sibling) forked `ls -t` over the whole session directory on every start just to read one line off the top, throwing the sort away -- the only per-session cost that grows with how long a project has been used (0.104s at 500 past transcripts, 0.41s at 2000, per #660's own diagnostic). Both call sites are now a single pass over the glob that compares mtimes with bash's own `-nt` test builtin, so the cost no longer scales with transcript count at all. #694: a failed background save reported only `exited 1` in hook-errors.log while the nested Haiku CLI's own failure detail -- already computed and already length-capped -- went only to the daily narrative log nobody reads while diagnosing a live outage (#693: 12 occurrences over several days before anyone found it in the second file). save-session.sh's two internal failure sites (a failed call, an empty response) now call report_error() instead of log() alone, so the same detail reaches the file /remember:doctor tails and a reporter is asked to paste. Propagation only, no new diagnosis. New tests for both, each with a real red-before-fix run; guard set checked via scripts/lane_setup.py (no cross-cutting guards apply in this repo). Changelog fragments for both issues, verified against .oss/assemble_changelog.py --check. A new module-level win32 skip gets its docs/windows-skip-triage.md row in this same commit, per CLAUDE.md's own convention. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(#691): normalize path separators before comparing bash and pathlib output Self-review finding (oss:auditor) on e0357f6: three assertions in tests/test_previous_transcript_no_sort_691.py compared bash's own glob output (always joined with a literal forward slash, verbatim on whatever $dir it was handed) against Python's str(Path) (all-backslash on Windows), so a passing local run would still fail on windows-latest CI -- a correct fix reported as broken by its own test. Folds every occurrence of the platform separator byte to a forward slash on both sides before comparing. Re-ran the file after the fix: all 5 tests still pass. Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
Summary
ANTHROPIC_API_KEY, when set anywhere in the host environment, takes precedence over the operator'sclaude.ailogin for the nestedclaude -pcall the background summarizer spawns — the CLI resolves credentials in that order.Credit balance is too low, silently — the operator's own interactive sessions keep working fine off the login, so nothing about the failure points at this var without reading the child's own stderr.CLAUDE_CODE_OAUTH_TOKEN, this was never the child's own credential — it's an ambient host var the operator did not choose for this subprocess._child_env()now strips it, for the same reason it already stripsCLAUDE_PROJECT_DIR.Reproduced in production
Traced via the daily narrative log (
~/.remember/logs/memory-*.log) to exactly this cause, on a real installation withANTHROPIC_API_KEYset in the environment (for unrelated reasons) and an exhausted balance:12 occurrences across several days on that installation, each showing as an opaque
save-session.sh --force exited 1warning inhook-errors.logwith no indication of the actual cause unless you dig into the daily log.Test plan
test_call_haiku_strips_anthropic_api_key, matching the existingtest_call_haiku_strips_parent_session_envpatternpytest tests/test_haiku.py— 80/80 passing (79 pre-existing + 1 new)_child_env()no longer includesANTHROPIC_API_KEYwhen set in the parent environment🤖 Generated with Claude Code
Closes #703.
Maintainer edit (@fdaviddpt): only this closing reference and the note below were added — the description above is the author's own, unchanged. Two commits were pushed to this branch (see the comments below): the conditional-strip rework the review asked for, and a follow-up that stops the config warning echoing a value an operator might have pasted a real key into. #704 was a temporary duplicate of the same work, opened while pushing here was blocked, and is closed in favour of this PR.
[AI-generated]