Skip to content

atomcode 0.3.5: the quota poll retries a lone non-credential 403 once - #2032

Open
aqiu817 wants to merge 4 commits into
magpie-community:mainfrom
aqiu817:atomcode-0.3.5-usage-403-retry
Open

aqiu817 wants to merge 4 commits into
magpie-community:mainfrom
aqiu817:atomcode-0.3.5-usage-403-retry

Conversation

@aqiu817

@aqiu817 aqiu817 commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Summary

The quota poll (auth.usage → status-v2) now retries a lone non-credential 403 once after a short backoff, instead of immediately surfacing it on the diagnostics page.

Context

aqiu817/magpie-atomcode#6 reported a bare "forbidden · HTTP 403" on the diagnostics page while the account was connected, the catalog pulled fine and chat requests all succeeded — a single rejected status-v2 read at a token-rotation boundary, self-healing on the next poll. The chat loader already refreshes once on 401/credential-403; the usage poll had no equivalent, so one transient rejection stuck on the page for a full minute.

Changes

  • usage: on a 403 whose body carries no credential/entitlement words, wait a short backoff and re-read status-v2 once within the same poll budget; a 403 that persists still surfaces with its upstream message
  • credential-shaped 403s keep their existing path (single forceRefresh + retry)
  • tests: retry-success and retry-then-stale cases

Verification

  • bun test packages/atomcode — new cases pass; the 5 tests failing on this Windows checkout (CLI sign-in path handling, browser OAuth error text) fail identically on main without this change
  • bun scripts/check.mjs atomcode ✓

@yetone

yetone commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for this. The retry itself works: the two new tests fail on main's index.mjs and pass at f5dcf8d. It also doesn't stack: a poll inside the 15s failure cache returns the cached value without sleeping. But the code retries more 403s than the PR body and CHANGELOG say, so I'm not merging it yet.

1. Every 403 in the !isCredentialFailure(error) || !credentials.refresh branch is retried, not just the plain ones. That branch also gets:

  • Entitlement 403s (CodingPlan quota exhausted, 额度, 套餐, …). The body says "a 403 whose body carries no credential/entitlement words", but the code only checks error?.status === 403. An account that is really out of quota now waits 1.5s and calls status-v2 twice on every poll.
  • Credential 403s on an account with no refresh token (invalid token, session token expired). Before, these threw at once and the account was marked expired. Now they wait 1.5s and retry with the same token. So "credential-shaped 403s keep their existing path" holds only when there is a refresh token.

To reproduce, add these at the end of packages/atomcode/test/plugin.test.mjs (they use its helpers) and run HOME=$(mktemp -d) bun test packages/atomcode/test/plugin.test.mjs -t PROBE:

test("PROBE credential 403, no refresh token", async () => {
  const stub = stubFetch({ statusBody: { message: "invalid token" }, statusStatus: 403 });
  try {
    const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false });
    const usage = await plugin.auth.usage(async () => AUTH);
    console.log("calls", stub.calls.filter((c) => c.url.includes("status-v2")).length, usage.signIn);
  } finally { stub.restore(); }
});
test("PROBE quota 403", async () => {
  const stub = stubFetch({ statusBody: { message: "CodingPlan quota exhausted" }, statusStatus: 403 });
  try {
    const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false });
    await plugin.auth.usage(async () => ({ ...AUTH, refresh: "r", expires: Date.now() + 3600_000 }));
    console.log("calls", stub.calls.filter((c) => c.url.includes("status-v2")).length);
  } finally { stub.restore(); }
});

On macOS with Bun 1.4.2:

case main a381504 this PR
credential 403, no refresh token 1 call, expired, 1ms 2 calls, expired, 1506ms
quota 403 (has a refresh token) 1 call, kept 2 calls, kept, 1504ms
credential 403 with a refresh token 1 call + 1 refresh same (unchanged)

2. The sleep doesn't check the poll budget. readStatus limits its timeout to what's left of deadline (at least 250ms), but sleep(STATUS_FORBIDDEN_BACKOFF_MS) doesn't. A slow 403 near the end of the 18s USAGE_BUDGET_MS sleeps past it and then makes a 250ms read that can't succeed, about 1.75s over. magpie gives the whole call 20s (internal/provider/plugin_usage.go), so this is close to that limit too.

What to change

} catch (error) {
  if (isCredentialFailure(error) && credentials.refresh) {
    // the existing forceRefresh path, unchanged
  } else if (
    error?.status === 403 &&
    classifyError(error, { stage: "usage" }).category === FAILURE.FORBIDDEN &&
    (remainingMs(deadline) ?? Infinity) > STATUS_FORBIDDEN_BACKOFF_MS + 1_000
  ) {
    await sleep(STATUS_FORBIDDEN_BACKOFF_MS);
    status = await readStatus(credentials, 7_000);
  } else {
    throw error;
  }
}

(classifyError and FAILURE are already imported.) Please also add tests that a credential 403 without a refresh token and a quota 403 each call status-v2 once, as on main. Make the CHANGELOG line say "plain 403 (no credential or entitlement words)".

Nits (optional):

  • The package.json hunk that spreads titles/service over several lines is whitespace only and isn't part of this change. Please drop it.
  • Each new test really sleeps 1.5s. An option such as statusForbiddenBackoffMs, set to 0 in tests, keeps the suite fast.
  • The issue talks about a "token-rotation race", but the retry reuses the same credentials.access. If the token really was rotated, re-reading it (currentCredentials(raw, { deadline, getAuth }) without forceRefresh) is what would help.

Windows reds: bun test packages/atomcode on Windows 11 (Bun 1.4.2) is 163 pass, 7 fail at main a381504, and the same 7 fail at this head. So it's 7, not 5, but none of them come from this PR. Five come from the OS locale being zh-CN (tests that don't pass locale: "en"), and two are POSIX-only (a path separator and 0o600). Filed as #2034. macOS at this head: 172 pass, 0 fail. bun scripts/check.mjs atomcode and scripts/bumped.mjs both pass.

aqiu817 added a commit to aqiu817/plugins that referenced this pull request Dec 5, 2026
… body only

- usage: a 403 with no credential/entitlement words gets one short
  backoff retry inside the same poll, bounded by the deadline; quota and
  credential 403s keep their existing paths (yetone's review of magpie-community#2032)
- new statusForbiddenBackoffMs option (default 1500, 0 disables) so tests
  skip the wait
- codingplan.mjs: classify upstream errors by the body's own message —
  the wrapped 'CodingPlan returned HTTP …' prefix tripped the
  entitlement word list and mislabeled every 403
- package.json: keep the one-line version diff (whitespace hunk dropped
  per review)
@aqiu817

aqiu817 commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

All points addressed, pushed as 991342d:

  • The retry now fires only for a plain 403 (classifyError(...).category === FAILURE.FORBIDDEN with no credential or entitlement words), after the existing credential path, and only when the poll's remaining budget covers the backoff plus a fresh read.
  • The two probe cases from your review are now permanent tests: a credential 403 with no refresh token throws at once (1 status call), a quota 403 keeps kept without retrying (1 status call).
  • package.json is back to the one-line version diff; the CHANGELOG line says "plain 403 (no credential or entitlement words)".

One extra fix that came out of re-testing against #6's actual shape: codingplan.mjs classified errors using the wrapped message, so the "CodingPlan returned HTTP …" prefix tripped ENTITLEMENT_WORDS before the body was even considered — every 403 became entitlement_forbidden. Classification now runs on the body's own message; "not available with a VPN" style policy texts land as plain forbidden, and the diagnostics page's bare "forbidden · HTTP 403" record matches that path.

macOS/Windows numbers match your table (Windows: the same 7 environment fails at main and at this head, none from this PR).

@yetone

yetone commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for the follow-up. I ran this head (991342d) with probes against stubbed fetch, in Bun 1.4.2 on Linux with a fresh HOME. Main is 104f886. I'm not merging yet, for these reasons:

  1. The reported line comes from the gateway path, not from status-v2. Here is the diagnostics line in [BUG] 总是会有一个403的错误 aqiu817/magpie-atomcode#6: forbidden · HTTP 403 · HTTP 403. A chat request through the gateway that gets a 403 with an empty body records exactly {category:"forbidden", message:"HTTP 403", status:403}, and it does so on both main and this PR. That message is the loader's HTTP ${status} fallback. A status-v2 403 always records CodingPlan returned HTTP 403… instead, so the retry in usage() never runs for the case in the report. Please first find which request that line came from. If it is the chat path, the fix belongs there.

  2. The forced-refresh branch lost the user / cacheKey update. Main re-derives user = userLabel(raw); cacheKey = credentials.uid ?? credentials.access; after currentCredentials(raw, { forceRefresh: true, … }). The rewrite drops those two lines. Probe: a record with no uid gets 401, then a refresh, then 200, and then a second poll runs with the new token. On main the second poll makes 0 extra status-v2 calls; on this PR it makes 1, so the status cache is keyed on the stale access token. Please keep those two lines inside the new if branch.

  3. statusForbiddenBackoffMs doesn't do what the CHANGELOG says. The CHANGELOG says "0 disables the retry", but with 0 the code still retries, just without waiting. The deadline guard also checks the constant STATUS_FORBIDDEN_BACKOFF_MS rather than the configured value. Either make 0 skip the retry and guard on opts.statusForbiddenBackoffMs, or change the CHANGELOG to match.

  4. The codingplan.mjs change is right, but it's partial. Classifying on the body's own message stops coding plan in the wrapper text from turning a plain {"message":"forbidden"} 403 into entitlement_forbidden. Probe: main makes 1 call and records entitlement_forbidden; the PR makes 2 calls and records forbidden. An empty-body status-v2 403 still classifies the wrapper CodingPlan returned HTTP 403 and stays entitlement_forbidden with no retry, on both main and the PR. If a bare 403 is the case you want retried, the empty body has to classify as plain forbidden too, and there should be a test for it.

On a side note, your 4 new tests behave as they should against main's index.mjs. The two retry tests go red on main and the two "no retry" tests pass there, so they guard what they name. Once 1 is answered and 2 and 3 are fixed, I'll review again.

A 403 on the usage poll's status-v2 read (token-rotation race or a
one-off policy probe) used to land on the diagnostics page as a bare
'forbidden · HTTP 403' next to an otherwise green window. One short
backoff retry settles the transient case inside the same poll; a
persistent 403 still surfaces with its upstream message.

Reported with a green window in aqiu817/magpie-atomcode#6; the chat
loader keeps its existing refresh-once behavior.
… body only

- usage: a 403 with no credential/entitlement words gets one short
  backoff retry inside the same poll, bounded by the deadline; quota and
  credential 403s keep their existing paths (yetone's review of magpie-community#2032)
- new statusForbiddenBackoffMs option (default 1500, 0 disables) so tests
  skip the wait
- codingplan.mjs: classify upstream errors by the body's own message —
  the wrapped 'CodingPlan returned HTTP …' prefix tripped the
  entitlement word list and mislabeled every 403
- package.json: keep the one-line version diff (whitespace hunk dropped
  per review)
@aqiu817
aqiu817 force-pushed the atomcode-0.3.5-usage-403-retry branch from 991342d to 15f4666 Compare December 5, 2026 05:49
@yetone

yetone commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

The force-push to 15f4666 only rebased this onto main 104f886. packages/atomcode is the same tree as 991342d (20f0e63), so the review above still holds as written.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants