Skip to content

feat(proxy): record the subscription limit headers and serve GET /api/me/limits - #991

Merged
amiddavid merged 4 commits into
mainfrom
feat/limit-headers
Nov 10, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/limit-headers

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The proxy now reads the subscription limit headers on each Anthropic answer, stores them on the request's dashboard row, and serves the newest values at GET /api/me/limits. subscription comes from the auth kind of the account's newest Anthropic request, not from the headers.

Closes #984 (steps 1 to 3 only; no weight fitting).

Agents B (#985, dashboard) and C (#986, status and insights commands) build on this endpoint. Its shape is the shared contract below.

Rule change after round 1 (owner, 2026-11-09): "subscription" must come from the auth kind, not from the presence of the headers. The owner's words: "auth kind is safer, the headers might change if they change the plan." Commit 8c0f7cb7 does this.

Behavior change (asked for by the owner on 2026-11-09):

  • Who: every proxy with the dashboard on.
  • Old: the proxy ignored the anthropic-ratelimit-unified-* response headers and the auth kind.
  • New: the proxy stores 6 values from the headers (5h and 7d utilization, reset, status) and one flag, auth_subscription, on each request row. A new route, GET /api/me/limits, returns them.
  • How to turn it off: turn the dashboard off. Nothing is stored without it. The forwarded answer never changes.

Data dependence: metadata only. Numbers, short status words and one yes/no flag. The proxy tests only the token's fixed prefix (sk-ant-oat). It never stores or logs the token. Off: nothing stored. Metadata only and everything: the same values. A row is in docs/data-dependence.md.

What changed

  • proxy/limitheaders.go:
    • readLimitHeaders reads anthropic-ratelimit-unified-{5h,7d}-{utilization,reset,status}. Header names are case-insensitive. Each missing or bad value is left out by itself. Utilization must be a finite number from 0 to 10. Reset must be a positive integer. Status must be a short word of a-z and _ (lower-cased first). It only reads the headers.
    • callerIsSubscription is true when the client sent Authorization: Bearer sk-ant-oat…. It reads the same slot as CallerKey and CallerAuthScheme in proxy/tenancy.go. An x-api-key, a bearer API key and one of our own tokens are not a subscription.
  • proxy/proxy.go and proxy/dashcapture.go: noteLimits(resp.Header) beside noteUpstream. With several upstream rounds, the last answer with the headers wins. newCapture sets the auth kind on Anthropic requests only.
  • dash: 8 new requests columns, added through additiveColumns (no version bump):
    • limit_seen (0/1) and 6 nullable value columns. NULL means "missing", so it stays apart from a share of 0.
    • auth_subscription (0/1).
    • Two partial indexes (WHERE limit_seen = 1) for the limit read.
    • insertBatch writes them and scanRequest reads them back, so /api/requests/{id} shows them too.
  • dash/limits.go: GET /api/me/limits, in the route table as scopeTenant.

The contract:

{
  "subscription": true,
  "at_ms": 1794233089000,
  "five_hour": {"utilization": 0.54, "reset_s": 1794249600, "status": "allowed"},
  "seven_day": {"utilization": 0.08, "reset_s": 1794348000, "status": "allowed"}
}
  • {} when the account's newest Anthropic request (keep-alive pings left out) did not use a subscription token. This holds even when older rows carry limit values. So an account that moves from a subscription to an API key stops showing the old share at once.
  • On a subscription, five_hour and seven_day come from the newest row that had the headers. A window or a field that row did not carry is left out. With no such row, the answer is {"subscription": true} alone (no at_ms).
  • utilization is a 0..1 fraction in steps of 0.01.
  • Always the caller's own account, a manager's too (?tenant= is ignored). A single-tenant proxy reads all rows.
  • The server returns the values as recorded. A window with reset_s in the past is over: the caller treats it as absent.

Docs: a "Subscription limits" section in docs/dashboard.md, a row in the dashboard routes table in docs/reference/reference.md, and a row in docs/data-dependence.md.

How it was tested

New tests:

  • TestReadLimitHeaders: good, missing, bad and mixed-case values.
  • TestCallerIsSubscription: OAuth bearer (any case) yes; bearer API key, x-api-key (even with an OAuth-shaped value) and a lone Bearer no.
  • TestLimitHeadersReachTheRowAndTheEndpoint: OAuth bearer through the real proxy. The answer reaches the client unchanged. The row holds the values and auth_subscription. The endpoint returns {} before, then the values. The token is not in the row read back, nor anywhere in the database or WAL files.
  • TestLimitsAreEmptyForAnAPIKey: x-api-key (with headers on the answer) gives {}; a bearer API key too.
  • TestLimitsStopAfterASwitchToAnAPIKey: OAuth, then an API key, gives {}.
  • TestLimitsRoundTrip, TestMeLimitsEndpoint (tenant scoping, manager, pings and other providers ignored, subscription without headers, single-tenant switch back and forth), TestLatestLimitsUsesThePartialIndex.
  • The existing TestEveryMountedRouteDeclaresItsScope covers the new route.

On the eval box (go test -race -count=1 -timeout 30m), each package in 2 halves (-run '^Test[A-H]' and '^Test[^A-H]'):

  • ./proxy/...: ok, 0 failures. [A-H] 391 tests (360 s); [^A-H] 445 passed, 1 skipped (174 s).
  • ./dash/...: ok, 0 failures. [A-H] 397 passed, 3 skipped (290 s); [^A-H] 577 passed, 9 skipped (366 s).
  • gofmt -l and go vet ./dash/ ./proxy/: clean.

Open questions

  • Keep-alive ping rows do not record the headers. Pings are built in the keepalive library, not on this path. Should they? It would make the newest share fresher when the user is idle.
  • Should the server drop a window whose reset_s is in the past? Today the caller does it, as the contract says.
  • Through a gateway that injects its own key (hosted mode with a server-held key), the client's credential is our token, so the row reads "not a subscription". Is that right for hosted users?

🤖 Generated with Claude Code

…/me/limits

The proxy reads the anthropic-ratelimit-unified-5h-* and -7d-* response
headers (utilization, reset, status) on each upstream answer. It stores
them on the request's dashboard row, beside the token counts. A missing
or bad value is left out. The forwarded answer does not change.

GET /api/me/limits returns the newest values for the caller's own
account, or {} when it never saw them.

Data dependence: metadata only (numbers and status words).

Closes #984

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 0d8cfe0bab76 approve

Verdict: approve

Findings

None. I found no wrong behavior, no data loss, no broken fail-open path, and no security problem.

Non-blocking

  • dash/limits_test.go:307 — The index test runs EXPLAIN QUERY PLAN on SELECT ts FROM requests ..., but LatestLimits selects seven columns. The plan for the production query can differ from the tested one, because the tested query is covering and the production one is not. The read stays correct either way. Consider testing the exact query text.
  • proxy/limitheaders.go:607 — limitStatusOK rejects every byte outside a-z and _. A future status word with a digit is dropped silently. The comment says this is deliberate, so a header cannot put free text on a row. Acceptable.
  • dash/limits.go:102 — The query orders by ts DESC, id DESC, but neither partial index carries id. SQLite adds a temp b-tree for the tie-break. The result stays correct, and the work stays bounded by the rows in the partial index.

What I checked

  • Read the full diff, CLAUDE.md, and docs/design.md.
  • Column alignment. Counted the insert columns, placeholders, and Exec args in dash/store.go: 102 = 102 = 102. Counted requestCols against the scanRequest args in dash/query.go: 94 = 94, and every name maps to the right scan target.
  • Migration order. The new indexes live in additiveDDL2, which migrate runs after addColumns on both the fresh and the already-at-version path (dash/schema.go:1046, :1066, :1075). So the limit_seen column exists before an index names it. Each new column appears in both ddl and additiveColumns, as the additive rule requires.
  • Capture path. noteLimits sits in serve, after the deferral retry resolves to its final response, and runs once per upstream round (proxy/proxy.go:2228). The retry path's earlier 400 responses are replaced before that point. serve is the only upstream-forwarding path; /compact (proxy/proxy.go:958) never calls a provider. noteLimits and noteUpstream are nil-receiver safe. finish reads c.limits in the same goroutine that wrote it, so there is no race. An answer without usable headers does not clear an earlier round's values, which matches the stated "last answer that carried them wins".
  • Fail open. The reader only reads resp.Header; it cannot change the forwarded answer. The end-to-end test proves a garbage header value passes through to the client unchanged.
  • Validation. Utilization rejects NaN, Inf, negatives, and values over 10. Reset must parse as a positive integer. Status is lower-cased, at most 32 bytes, and limited to a-z and _, so no free text reaches a row. Missing values stay NULL, and a real 0 stays 0 — the round-trip test pins both.
  • Scoping. /api/me/limits is declared scopeTenant in the route table, so TestAPIScopesEveryRouteDeclaresItsScope walks it. meLimits re-narrows the filter to the principal's own tenant after scope(), so a manager's ?tenant=* default and a crafted ?tenant= cannot widen it. The tests cover a manager, a plain tenant, a tenant without headers, and the single-tenant case.
  • Query correctness. LatestLimits picks the newest row by ts DESC, id DESC, so equal timestamps break by insert order. The whole snapshot comes from one row, and the docs say a window is left out when the newest answer did not carry it. The tests pin this.
  • Boundaries. Header reading is transport and lives in proxy; the stored type lives in dash. dash does not import proxy. No library package changed.
  • Repo rules. docs/data-dependence.md gains a row for the new feature (metadata). The feature is new, so no existing feature's data dependence changed. /stats fields are untouched.
  • Tests. New behavior has tests on both sides: header parsing, the row round trip, the endpoint, and the end-to-end path through a live upstream.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 0d8cfe0bab76 approve

Verdict: approve

Findings

None. I read every changed line of the one commit (0d8cfe0) and the code around each change. I found no wrong behavior, no data loss, no broken fail-open path, and no missing test for the new behavior.

Non-blocking

  • dash/limits.go:48 — the LimitWindow doc says "as the header gives it (whole percents)", but the stored value is a 0..1 fraction (0.54). A fraction is not "whole percents". The docs in dashboard.md say it right. Fix the one comment when the file is next touched.
  • proxy/limitheaders.go:44 — if the provider ever changes the header to whole-percent integers ("54"), every value exceeds limitMaxUtilization (10) and is dropped silently. The feature goes dark, not wrong. The bound is the right call today; this is only a note for a format change no one will see coming.
  • dash/limits.go:150 — meLimits ignores every other filter parameter. A caller sending ?since= or ?model= gets the newest row anyway. The docs promise only "the newest values", so this is a possible surprise, not a defect.
  • dash/limits.go:98 — LatestLimits writes its two query strings out in full instead of building one. Style only.

What I checked

  • Insert arithmetic. The INSERT names 102 columns, has 102 placeholders, and the Exec passes 95 args + 7 from limitArgs = 102. I counted all three with a script, not by eye. limitCols order (limit_seen, 5h utilization/reset/status, 7d utilization/reset/status) matches limitArgs order, and both sit after compaction_point_source in the column list and after e.CompactionPoint, e.CompactionPointSource in the args.
  • Read arithmetic. requestCols has 94 columns and scanRequest scans 94 targets. The 6 new limit columns are last in both, in the same order (u5, r5, s5, u7, r7, s7).
  • Migration. addColumns runs before additiveDDL2 on both the fresh and the already-at-version path (dash/schema.go:1040-1081), so the two partial indexes are created on an existing database after the columns they name exist. additiveColumns carries all 7 columns; the CREATE TABLE carries them for fresh databases.
  • One write path. insertBatch is the only INSERT INTO requests in the tree, so no other writer can produce a column mismatch. Cold-storage fetch does not reinsert rows (read-only, per docs/reference).
  • Scoping. meLimits calls a.scope and returns 401 without a principal. It overrides the manager's widened filter (?tenant=*, ?tenant=<other>) back to the caller's own tenant, so "me" holds for a manager too. A non-manager cannot widen: scope overwrites the tenant rather than merging. In single-tenant mode (auth nil) scope sets TenantAll=true, which the endpoint's own auth-nil branch also relies on. The generic route-scoping test walks routes(), so the new route is checked without registration.
  • Fail open. readLimitHeaders only reads the http.Header; it cannot change the forwarded answer. noteLimits is nil-safe on the capture. A missing or bad value is left out, never read as 0 (nullable columns, limit_seen flag). The end-to-end test asserts the answer passes through unchanged, including a bad header value.
  • Injection and storage safety. The status word is constrained to lower-case letters and underscores, at most 32 bytes, so a header cannot put free text on a row. Utilization is bounded (0..10, NaN and Inf rejected); reset is a positive int64 and out-of-range strings fail ParseInt. The queries are parameterized.
  • Call site. noteLimits runs in serve after noteUpstream, on every non-error round, before both the streamed and buffered SSE paths, so it covers stream and non-stream, bypass and Bob traffic. finish() copies c.limits onto the Event; the deferred finish runs on the same goroutine, so there is no race on the pointer.
  • Tests. Round trip (values, NULL-vs-0, limit_seen count), endpoint (empty {}, newest row wins over a newer header-less row, tenant isolation, manager self-scope, single-tenant newest), partial-index use via EXPLAIN QUERY PLAN, header parsing (good, absent, bad one-by-one, case-insensitive names, status charset and length), and an end-to-end proxy test through a real httptest upstream with lower-case header names. All helpers used (openTestDB, asTenant, dashHandler, anthropicRequest, waitForRows) exist; the new names (limF, limI, Limits, limitWindow) collide with nothing in package dash.
  • Docs. data-dependence.md gets a new row (metadata at both working levels, off needs the dashboard), reference.md and dashboard.md describe the endpoint, and the #subscription-limits anchor the reference links to exists. The behavior is new storage plus a new route; nothing existing changes, so no RELEASING.md behavior-change sign-off is needed. I reviewed the code and in-repo docs only, not the PR body.

Limitations: live tests were not approved, so I read the code only; Go is not installed on this machine. I could not run the test suite or the EXPLAIN plans myself — the index-use test rests on SQLite preferring the partial index, which the planner does when the query's WHERE implies the index's WHERE (limit_seen = 1).

…0.01

Comment only.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Comment-only fix after both approvals: the LimitWindow.Utilization doc now says it is a 0..1 fraction in steps of 0.01. Output of scripts/release/approval-still-valid.sh 991 0d8cfe0bab76a08507f94c6f97da44dcca02d998:

approved: 0d8cfe0bab76 (base 569c609bed65) patch-id 0a5077812bb6
head:     94c5b23cd2d1 (base 569c609bed65) patch-id d02e8adf7518
--- git range-diff
1:  0d8cfe0b = 1:  0d8cfe0b feat(proxy): record the subscription limit headers and serve GET /api/me/limits
-:  -------- > 2:  94c5b23c docs(dash): say the limit utilization is a 0..1 fraction in steps of 0.01
COMMENTS ONLY: 0d8cfe0bab76..94c5b23cd2d1 changes only comment lines in .go and .sh files. The approval of 0d8cfe0bab76 still counts. Say so on the PR.

…aders

The owner changed the rule for GET /api/me/limits: "subscription" now
comes from the auth kind of the account's newest Anthropic request. A
Claude subscription is an "Authorization: Bearer sk-ant-oat..." token.

- The proxy stores one flag per row, auth_subscription (0/1). It tests
  only the fixed prefix and never stores or logs the token.
- The endpoint returns {} when the newest Anthropic request (pings
  left out) used an API key or another credential, even when older
  rows carry limit values.
- The five_hour and seven_day blocks still come from the headers.

Data dependence: still metadata only (a flag).

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

The owner changed the rule: subscription now comes from the auth kind, not from the limit headers. The owner's words: "auth kind is safer, the headers might change if they change the plan."

What changed in 8c0f7cb7:

  • New flag on each row: auth_subscription (0/1). It is 1 when the client sent Authorization: Bearer sk-ant-oat… (a Claude sign-in token). The proxy tests only that fixed prefix. It reuses the CallerKey / CallerAuthScheme slot logic in proxy/tenancy.go. The token is never stored or logged.
  • GET /api/me/limits: subscription is the auth kind of the account's newest Anthropic request. Keep-alive pings are left out. When that request is not a subscription, the answer is {}, even when older rows carry limit values. So a switch to an API key hides the old share at once.
  • Unchanged: five_hour / seven_day still come from the headers. A subscription with no header rows answers {"subscription": true} alone.
  • Tests: OAuth bearer gives subscription: true. x-api-key gives {}, even with headers on the answer. OAuth then API key gives {}. The token is not in the stored row, nor in the database or WAL files.
  • Docs: docs/dashboard.md, docs/reference/reference.md and docs/data-dependence.md are updated. It is still metadata only: one flag.
  • Eval box (-race -timeout 30m, 2 halves each): ./proxy/... 836 passed, 1 skipped, 0 failed. ./dash/... 974 passed, 12 skipped, 0 failed.

The PR body is updated to match.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.321 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 8c0f7cb75b77 approve

Verdict: approve

Findings

None. The owner's rule change is implemented as asked, and I found no defect in it.

Earlier findings

  • Mine, round 1, non-blocking 1 (the "whole percents" comment): fixed. Commit 94c5b23 changes exactly that one comment line; I read the full commit. It is comment-only, as the PR comment says.
  • Mine, round 1, non-blocking 2 (a future whole-percent header format would go dark): not addressed. It was an observation about a format change that has not happened. No action needed.
  • Mine, round 1, non-blocking 3 (meLimits ignores other filter parameters) and 4 (duplicated query strings): still true, still fine. LatestAuthSubscription now duplicates its two query strings the same way. Style only.
  • Reviewer 2's round-1 notes (index-test query shape, status charset, temp b-tree for the id tie-break): not addressed. All three were optional and correct as stated. I checked the same ground myself in round 1 and agree with their reading.

The rule change (8c0f7cb)

The owner's words, quoted in the PR comment: "auth kind is safer, the headers might change if they change the plan." The comment is the human permission the repo rules require for a behavior change, so that rule is met.

What I checked in the new code:

  • Insert arithmetic, again by script. 95 literal columns + 7 limitCols + auth_subscription = 103 columns, 103 placeholders, and 95 Exec args + 7 + 1 = 103. requestCols is 95 columns against 95 scan targets, with r.auth_subscription last in both. boolInt(e.AuthSubscription) sits after limitArgs in the args, matching the column order.
  • Auth-kind detection. callerIsSubscription reads the same slot CallerKey and CallerAuthScheme pick (proxy/tenancy.go:291-316). A context-guru token (cg_live_…) fails tenant.LooksLikeToken's inverse test, so our own token in Authorization is skipped and reads as not-a-subscription. An x-api-key slot returns scheme "", so an oat token sent there does not count. Only the fixed prefix sk-ant-oat is tested; a lone "Bearer" yields no credential. The header is read in newCapture, before setUpstreamAuth/scrubToken touch the outbound copy — nothing deletes from r.Header anywhere in the proxy — so the flag reads the pristine client header. The end-to-end tests prove this through the real proxy route.
  • The token never lands. The stored value is one bool. The new test marshals the read-back rows and greps the database and WAL files for the token's marker tail. I found no other path that could carry it: authSub is a bool on the capture and the Event.
  • The endpoint's gating. subscription comes from LatestAuthSubscription (the account's newest provider = 'anthropic', keepalive = 0 row); {} when that row is not a subscription, even when older rows carry limit values. The pings the proxy sends carry no client auth kind, and keepalive = 0 leaves them out. The five_hour/seven_day blocks still come from LatestLimits, the newest row that carried the headers, and at_ms is left out when none did ({"subscription": true} alone). Tests cover: OAuth bearer true, x-api-key {} with headers on the answer, a bearer API key {}, a switch to an API key hiding the old share at once, a subscription with no header rows, a ping not counting, an OpenAI row not counting, and tenant isolation plus the manager's own-account rule.
  • Provider filter. string(bschemas.Anthropic) is "anthropic", the same string the dash rows store (newCapture sets c.provider from it), so the provider = 'anthropic' filter matches what the proxy writes. Bedrock and Vertex callers present no oat bearer token, so they read as not-a-subscription.
  • Migration. auth_subscription is in the CREATE TABLE and in additiveColumns (INTEGER NOT NULL DEFAULT 0), the established additive pattern; addColumns runs before the index phase on every open. No new index is needed for correctness.
  • Docs. dashboard.md, reference.md and the data-dependence row all state the new rule and stay metadata-only (numbers, status words, one flag). The PR comment reports the eval-box test runs (./proxy/... 836 passed, ./dash/... 974 passed); I could not run them myself.

Non-blocking

  • dash/limits.go:60 — LatestAuthSubscription has no index for its filter. It scans the tenant's rows newest-first on idx_requests_tenant and stops at the first Anthropic non-ping row. Fast on Anthropic-heavy traffic. An account whose newest rows are all OpenAI or pings walks back through them, bounded by that tenant's rows. The repo measures a full-table scan at about 2 s over 1.58 M rows, and this is a dashboard read, so it is acceptable today. A partial index is the fix if it ever shows up.
  • dash/limits.go:148 — in single-tenant mode the endpoint can pair a subscription auth kind with limit values from an API-key-era row. Headers are still recorded on rows whatever the auth kind, and LatestLimits ignores the kind. This matches the documented rule ("the newest row that carried the headers") and the docs tell the reader to treat a past reset_s as over. Noted so the edge is known.

What I checked

  • Last review: round 1, 0d8cfe0, 2026-11-09T17:09:07Z
  • New commits read: 2 — 94c5b23 "docs(dash): say the limit utilization is a 0..1 fraction in steps of 0.01" (comment-only, verified), 8c0f7cb "feat(proxy): take 'subscription' from the auth kind, not the limit headers"
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review, and what I did about each:
    • PR comment 17:13:59Z (comment-only fix note): verified 94c5b23 changes one comment line and nothing else.
    • PR comment 19:28:50Z (the owner's rule change): reviewed commit 8c0f7cb in full, as described above.
    • Reviewer 2's round-1 review was already in my round-1 window; no review or comment newer than my last review other than the two above.
  • I also re-read the code around every changed line: CallerKey/CallerAuthScheme/scrubToken/setUpstreamAuth in proxy/tenancy.go and proxy/proxy.go, newCapture and finish in proxy/dashcapture.go, and the dash store/query/schema paths. Live tests were not approved, so I read the code only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.321 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 8c0f7cb75b77 approve

Verdict: approve

Findings

None. The new rule works as the owner asked, the token never reaches the database, and the queries stay inside the caller's own account.

Non-blocking

  • dash/schema.go:897 — After an upgrade, auth_subscription is 0 on every old row. A subscription account therefore reads {} from GET /api/me/limits until its next request, because its newest row cannot say it used a subscription token. The schema comment names this, and it self-heals on the next request. One read, once.
  • dash/limits.go:62 — LatestAuthSubscription has no index for its filter (provider = 'anthropic' AND keepalive = 0). It walks a tenant's rows newest-first and stops at the first match. A tenant with mostly non-Anthropic traffic pays a longer walk per call, bounded by the tenant's row count. The results stay correct.
  • Carried from round 1, unchanged and still non-blocking: the EXPLAIN test checks a SELECT ts query, not the production seven-column one; limitStatusOK drops digits; the id DESC tie-break needs a temp b-tree.

What I checked

  • Last review: round 1, 0d8cfe0bab76a08507f94c6f97da44dcca02d998, 2026-11-09T17:08:27Z.
  • New commits read: 2 — 94c5b23c (docs: the utilization comment now says a 0..1 fraction in steps of 0.01) and 8c0f7cb7 (subscription from the auth kind).
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review, and what I did about each:
    • Author comment "Comment-only fix" (17:13) — verified 94c5b23c changes one comment line only.
    • Author comment "The owner changed the rule" (19:28) — reviewed 8c0f7cb7 in full, as a first review of the new code.
    • Reviewer 1's round-1 note on the "whole percents" comment — fixed by 94c5b23c.
  • The new rule. meLimits asks LatestAuthSubscription first: {} when the account's newest Anthropic request (pings left out) did not use a subscription token, even when older rows carry limit values. Then LatestLimits adds five_hour, seven_day and at_ms from the newest row that carried the headers. A subscription with no header rows answers {"subscription": true} alone. The tests pin each case, including the switch from a subscription to an API key.
  • The auth-kind test. callerIsSubscription requires CallerAuthScheme == "bearer" and the sk-ant-oat prefix on CallerKey. I read both helpers in proxy/tenancy.go: headerCredential returns nothing for a lone "Bearer", both helpers skip the proxy's own tokens (tenant.LooksLikeToken), and x-api-key never yields the bearer scheme. So an API key in either slot, a bare "Bearer", and one of our own tokens all read as not-a-subscription. scrubToken runs on the outgoing header map, not on r.Header, so newCapture reads the client's pristine headers.
  • Token safety. Only the prefix is tested; the flag is one bit. The end-to-end test searches the stored row, the database file and the WAL for the token's marker tail and finds none. I checked the same by reading the write path: boolInt(e.AuthSubscription) is the only thing derived from the credential.
  • Arithmetic. Recounted with a script: the INSERT names 103 columns, has 103 placeholders, and the Exec passes 95 + 7 + 1 = 103 args. requestCols has 95 columns and scanRequest scans 95 targets, auth_subscription last in both. insertBatch is still the only writer of requests.
  • Migration. auth_subscription appears in both the CREATE TABLE block and additiveColumns (INTEGER NOT NULL DEFAULT 0), so a fresh and an upgraded database get the same shape. It names no index, so the additiveDDL2 ordering question from round 1 does not arise.
  • Provider value. LatestAuthSubscription filters provider = 'anthropic', and rows get string(bschemas.Anthropic) from newCapture. The end-to-end test drives the real path and gets subscription: true, which proves the stored value matches the filter. The author's eval-box run (836 proxy tests, 974 dash tests, 0 failed) covers the same path.
  • Scoping. Unchanged from round 1: meLimits re-narrows a manager's widened scope to the caller's own tenant, and both new queries take the same filter. The route-walking scoping test still covers the route.
  • Repo rules. The PR body names the behavior change at the top, says the owner asked for it on 2026-11-09, and says how to turn it off. The data-dependence row now names the flag. Still metadata only.
  • Limitation: live tests were not approved for me, so I read the code only. I did not run the suite; the author's eval-box numbers are quoted from the PR comment.

Keeps both new rows in docs/data-dependence.md: the Bob plugin row
from main and the subscription limit headers row from this branch.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Merged origin/main into this branch (d2ad8a9), because main moved on and the PR had a conflict. No force-push: the approved commits are unchanged.

  • The only conflict: docs/data-dependence.md. main added the Bob plugin row at the same place as this PR's limit-headers row. The merge keeps both rows. No code conflict.
  • Tests on the merged tree (eval box, -race -count=1 -timeout 30m, two halves each): ./dash/... ok (289 s, 363 s); ./proxy/... ok (356 s, 171 s). go vet ./dash/ ./proxy/ clean.

Output of scripts/release/approval-still-valid.sh:

approved: 8c0f7cb75b77 (base 569c609bed65) patch-id 2c73e5037c8f
head:     d2ad8a9c40ed (base 8864db29e921) patch-id 9af5ca138e16
--- git range-diff
1:  0d8cfe0b = 1:  0d8cfe0b feat(proxy): record the subscription limit headers and serve GET /api/me/limits
2:  94c5b23c = 2:  94c5b23c docs(dash): say the limit utilization is a 0..1 fraction in steps of 0.01
3:  8c0f7cb7 = 3:  8c0f7cb7 feat(proxy): take "subscription" from the auth kind, not the limit headers
CHANGED: the head has new code or a conflict resolution. Each reviewer re-checks the delta.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.321 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 d2ad8a9c40ed approve

Verdict: approve

Findings

None. The only new commit is the merge of origin/main. It changes no branch code and resolves the one conflict correctly.

The merge (d2ad8a9)

  • No branch code changed. I diffed 8c0f7cb7..d2ad8a9c over proxy/, dash/, config/ and cmd/. The only files that moved are main's own (cmd/context-guru-proxy/main.go, config/strategy.go, config/config.go, config/strategy_test.go). Every file this PR touches is byte-identical to the approved head.
  • The branch commits are unchanged. git log 8864db29..d2ad8a9c --no-merges lists exactly the three approved commits: 0d8cfe0b, 94c5b23c, 8c0f7cb7. The PR diff at the new head is the same 14 files I reviewed in rounds 1 and 2.
  • The conflict resolution is right. The only conflict was docs/data-dependence.md: main added the Bob plugin row where this branch added the subscription limit headers row. The merge keeps both rows, side by side (lines 239-240). I counted the table rows in both parents and the merge: 85 + 86 = 87 in the merge result, each row exactly once. No row was lost or duplicated.
  • No semantic conflict. Main's new code (named cache strategies, the Bob plugin, the Pi package, the release workflow) shares no file with this branch outside docs/data-dependence.md, and reads nothing this branch writes. The strategies subcommand and cache.strategy config key do not touch the limits path.

Earlier findings

  • Mine, rounds 1-2, non-blocking (index-less LatestAuthSubscription, meLimits ignoring other filters, single-tenant pairing edge, status charset, index-test query shape, id tie-break temp b-tree): not addressed. All were optional notes, and all still hold as stated. No action needed.
  • Reviewer 2's round-2 notes (old rows read auth_subscription = 0 after an upgrade, same index note, carried round-1 notes): agree. I checked the same ground myself in round 2 and my reading matches.

What I checked

  • Last review: round 2, 8c0f7cb, 2026-11-09T19:34:08Z
  • New commits read: 1 — d2ad8a9 "Merge origin/main into feat/limit-headers"
  • Read in full: 4 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review, and what I did about each:
    • Reviewer 2's round-2 review (19:35:39Z): read in full; their notes match my own round-2 reading.
    • Author's merge comment (23:20:26Z): verified every claim myself — the conflict list, the unchanged branch commits, and the row arithmetic in docs/data-dependence.md.
    • Merge commit d2ad8a9: reviewed as a first review, as described above.
  • Limitation: live tests were not approved, so I read the code only. The author's comment reports the merged tree passing ./proxy/... and ./dash/... with -race on the eval box and a clean go vet; I could not run them myself.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.321 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 d2ad8a9c40ed approve

Verdict: approve

Findings

None. The one new commit is a merge of origin/main into the branch. The merge keeps every approved line of this PR unchanged, resolves the one conflict correctly, and I found no semantic conflict with the code main added.

The merge (d2ad8a9)

What I verified:

  • Both directions are clean. I diffed the merge result against each parent. Against the branch tip 8c0f7cb7, the only repo files that change are the files main added or changed. Against main 8864db29, the only file that changes is docs/data-dependence.md. So the merge altered no file on either side except the named conflict file.
  • The branch's 14 files are byte-identical to the approved head. I listed every file the branch changed since the merge-base 569c609b and diffed each one between 8c0f7cb7 and the merge. Only docs/data-dependence.md differs. The three approved commits stand unchanged, as the PR comment says.
  • The conflict resolution loses nothing. The merged docs/data-dependence.md keeps main's side (the rewritten cache-strategy table with the "Decided by" column, the Bob plugin row) and this PR's side (the Subscription limit headers row). Both rows sit in the component table, in order, with their full text. The table structure is intact.
  • No code overlap. This PR touches dash/ and proxy/. Main's new Go code touches config/ and cmd/context-guru-proxy, and adds bob-plugin/ and pi-package/. I checked the new Go files there: they are standalone Python-test wrappers and import nothing from dash, proxy or config. The branch only adds a route and columns, so main's new readers of the dash API are unaffected. The route table still registers GET /api/me/limits once.
  • No Makefile or workflow conflict. The branch never touched Makefile, .github/workflows/release.yaml or scripts/offload-review.sh; main's changes there apply as-is.

Earlier findings

  • Reviewer 1, round 1, "whole percents" comment: fixed by 94c5b23c (confirmed in round 2; the merge does not touch it).
  • All other non-blocking notes (mine and reviewer 1's): not addressed, still non-blocking, still true as stated. The EXPLAIN test's query shape, limitStatusOK dropping digits, the id DESC temp b-tree, LatestAuthSubscription having no index for its filter, old rows reading {} after an upgrade, the single-tenant pairing edge, meLimits ignoring other filter parameters. None of these changes with the merge, because the merge changes no code on either side.
  • Nothing was rejected by the author.

Non-blocking

  • The merge brings about 14,000 lines of already-merged main code into this branch's history. I checked its interaction with this PR, not its content line by line: each main commit was approved in its own PR (#983, #979, #987, #968, #977, #971) and none of it is part of this PR's diff (8864db29..HEAD contains only the three branch commits and the merge). No action needed; noted so the scope of this round is clear.

What I checked

  • Last review: round 2, 8c0f7cb75b774a23b00f961d0a38388492fa0af6, 2026-11-09T19:35:39Z
  • New commits read: 7 in git log 8c0f7cb7..HEAD — d2ad8a9c "Merge origin/main into feat/limit-headers" (the branch's one new commit, reviewed in full as described above), plus 6 main-side commits that arrived through the merge: 8864db29 (bob installer, #971), c550c7c9 (pi package, #977), 10329879 (bob plugin, #968), b49cbeb6 (named cache strategies, #987), 8c12384e (offload-review fork fix, #979), 7bfd2f42 (mkdocs nav, #983). For these 6 I read the stat, the diff to cmd/ and config/, and checked every one for file and import overlap with this PR's changes; their full content is main's, outside this PR's diff, approved in their own PRs.
  • Read in full: 4 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review, and what I did about each:
    • Merge commit d2ad8a9c — reviewed in full: both parent diffs, byte-identity of the branch's files, conflict resolution, interaction surface. Described above.
    • PR comment 23:20:26Z (the merge note) — verified each claim myself: the only conflict was docs/data-dependence.md (true, it is the only file that differs from both parents), no code conflict (true), both rows kept (true), no force-push (true, the three approved commits are byte-identical in the merge).
  • Limitation: live tests were not approved for me, so I read the code only. The author's eval-box runs on the merged tree (./dash/... ok, ./proxy/... ok, go vet clean) are quoted from the PR comment; I could not run them.

@amiddavid
amiddavid merged commit 8cbb700 into main Nov 10, 2026
9 checks passed
amiddavid added a commit that referenced this pull request Nov 10, 2026
…pi/stats (#999)

Part 1 of #998. The dashboard stored only the dollars of each saving.
The tokens were lost after the write. This PR stores the tokens
by tier beside the dollars.

- 8 new columns in request_components and 32 in requests
  (default 0). Tokens follow the same attribution as the dollars.
- /api/stats (full and lean=1) now returns tokens,
  tokens_unmeasured_requests and the two keepalive_ping token fields.
  Both paths call one function, DB.AccTokens.
- PRs #988 and #989 use the new fields as their token source.

Behavior change: none stated; new fields in /api/stats. No existing
figure, field or column changes its value.
Owner's yes, 2026-11-10, in the integrator session: "999 approve".

Data dependence: metadata only. The new columns are token counts.
They are the same at each storage level. docs/data-dependence.md
row "Accountant savings" is updated.

Reviews: 2 offload reviews (GLM), round 4 (owner granted round 4), both approve at 3ae7056. Round 4 reviewed the rebase onto main after #991, which merged #991's limit columns and #999's token columns by hand in 4 files.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
…1012)

The keep-alive now records the subscription limit headers
(anthropic-ratelimit-unified-5h-* and -7d-*) from each ping's answer
on the ping's dashboard row, as #991 does for a user's own requests.
So GET /api/me/limits stays current while the user is idle. A refusal
carries the headers too, and is recorded. Requested in #995.

Behavior change: subscription users with keep-alive on. Old: GET
/api/me/limits showed the 5-hour share from the user's last own
request. New: a ping's answer also updates it. Off: turn keep-alive
off (cache strategy none); then no ping rows exist. Nothing is stored
without the dashboard.
Owner's yes, 2026-11-10, in the integrator session: "pls also add 1012 to the release and merge it".

Data dependence: metadata only (numbers and short status words from
response headers). The same at every storage level. The row in
docs/data-dependence.md now also names ping rows.

Reviews: 2 offload reviews (GLM), round 1, both approve at 74db21c.
14c23ef changes only comment lines.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
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.

proxy: record the subscription limit headers, to learn how the 5-hour limit weights tokens

1 participant