Repository navigation
feat(proxy): record the subscription limit headers and serve GET /api/me/limits - #991
Conversation
…/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
left a comment
There was a problem hiding this comment.
| 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 runsEXPLAIN QUERY PLANonSELECT ts FROM requests ..., butLatestLimitsselects 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—limitStatusOKrejects every byte outsidea-zand_. 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 byts DESC, id DESC, but neither partial index carriesid. 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, anddocs/design.md. - Column alignment. Counted the insert columns, placeholders, and
Execargs indash/store.go: 102 = 102 = 102. CountedrequestColsagainst thescanRequestargs indash/query.go: 94 = 94, and every name maps to the right scan target. - Migration order. The new indexes live in
additiveDDL2, whichmigrateruns afteraddColumnson both the fresh and the already-at-version path (dash/schema.go:1046,:1066,:1075). So thelimit_seencolumn exists before an index names it. Each new column appears in bothddlandadditiveColumns, as the additive rule requires. - Capture path.
noteLimitssits inserve, 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.serveis the only upstream-forwarding path;/compact(proxy/proxy.go:958) never calls a provider.noteLimitsandnoteUpstreamare nil-receiver safe.finishreadsc.limitsin 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-zand_, 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/limitsis declaredscopeTenantin the route table, soTestAPIScopesEveryRouteDeclaresItsScopewalks it.meLimitsre-narrows the filter to the principal's own tenant afterscope(), 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.
LatestLimitspicks the newest row byts 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 indash.dashdoes not importproxy. No library package changed. - Repo rules.
docs/data-dependence.mdgains a row for the new feature (metadata). The feature is new, so no existing feature's data dependence changed./statsfields 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
left a comment
There was a problem hiding this comment.
| 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 exceedslimitMaxUtilization(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.CompactionPointSourcein 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-limitsanchor 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]>
|
Comment-only fix after both approvals: the |
…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]>
|
The owner changed the rule: What changed in
The PR body is updated to match. |
amiddavid
left a comment
There was a problem hiding this comment.
| 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_subscriptionlast in both.boolInt(e.AuthSubscription)sits afterlimitArgsin the args, matching the column order. - Auth-kind detection.
callerIsSubscriptionreads the same slotCallerKeyandCallerAuthSchemepick (proxy/tenancy.go:291-316). A context-guru token (cg_live_…) failstenant.LooksLikeToken's inverse test, so our own token inAuthorizationis skipped and reads as not-a-subscription. Anx-api-keyslot returns scheme"", so an oat token sent there does not count. Only the fixed prefixsk-ant-oatis tested; a lone "Bearer" yields no credential. The header is read innewCapture, beforesetUpstreamAuth/scrubTokentouch the outbound copy — nothing deletes fromr.Headeranywhere 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:
authSubis a bool on the capture and the Event. - The endpoint's gating.
subscriptioncomes fromLatestAuthSubscription(the account's newestprovider = 'anthropic',keepalive = 0row);{}when that row is not a subscription, even when older rows carry limit values. The pings the proxy sends carry no client auth kind, andkeepalive = 0leaves them out. The five_hour/seven_day blocks still come fromLatestLimits, the newest row that carried the headers, andat_msis 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 (newCapturesetsc.providerfrom it), so theprovider = '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_subscriptionis in the CREATE TABLE and inadditiveColumns(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
LatestLimitsignores the kind. This matches the documented rule ("the newest row that carried the headers") and the docs tell the reader to treat a pastreset_sas 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/setUpstreamAuthin proxy/tenancy.go and proxy/proxy.go,newCaptureandfinishin proxy/dashcapture.go, and the dash store/query/schema paths. Live tests were not approved, so I read the code only.
amiddavid
left a comment
There was a problem hiding this comment.
| 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_subscriptionis 0 on every old row. A subscription account therefore reads{}fromGET /api/me/limitsuntil 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—LatestAuthSubscriptionhas 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 tsquery, not the production seven-column one;limitStatusOKdrops digits; theid DESCtie-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) and8c0f7cb7(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
94c5b23cchanges one comment line only. - Author comment "The owner changed the rule" (19:28) — reviewed
8c0f7cb7in full, as a first review of the new code. - Reviewer 1's round-1 note on the "whole percents" comment — fixed by
94c5b23c.
- Author comment "Comment-only fix" (17:13) — verified
- The new rule.
meLimitsasksLatestAuthSubscriptionfirst:{}when the account's newest Anthropic request (pings left out) did not use a subscription token, even when older rows carry limit values. ThenLatestLimitsaddsfive_hour,seven_dayandat_msfrom 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.
callerIsSubscriptionrequiresCallerAuthScheme == "bearer"and thesk-ant-oatprefix onCallerKey. I read both helpers inproxy/tenancy.go:headerCredentialreturns nothing for a lone "Bearer", both helpers skip the proxy's own tokens (tenant.LooksLikeToken), andx-api-keynever 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.scrubTokenruns on the outgoing header map, not onr.Header, sonewCapturereads 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
Execpasses 95 + 7 + 1 = 103 args.requestColshas 95 columns andscanRequestscans 95 targets,auth_subscriptionlast in both.insertBatchis still the only writer ofrequests. - Migration.
auth_subscriptionappears in both theCREATE TABLEblock andadditiveColumns(INTEGER NOT NULL DEFAULT 0), so a fresh and an upgraded database get the same shape. It names no index, so theadditiveDDL2ordering question from round 1 does not arise. - Provider value.
LatestAuthSubscriptionfiltersprovider = 'anthropic', and rows getstring(bschemas.Anthropic)fromnewCapture. The end-to-end test drives the real path and getssubscription: 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:
meLimitsre-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]>
|
Merged
Output of |
amiddavid
left a comment
There was a problem hiding this comment.
| 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..d2ad8a9coverproxy/,dash/,config/andcmd/. 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-mergeslists 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. Thestrategiessubcommand andcache.strategyconfig key do not touch the limits path.
Earlier findings
- Mine, rounds 1-2, non-blocking (index-less
LatestAuthSubscription,meLimitsignoring other filters, single-tenant pairing edge, status charset, index-test query shape,idtie-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 = 0after 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-raceon the eval box and a cleango vet; I could not run them myself.
amiddavid
left a comment
There was a problem hiding this comment.
| 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 main8864db29, the only file that changes isdocs/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
569c609band diffed each one between8c0f7cb7and the merge. Onlydocs/data-dependence.mddiffers. The three approved commits stand unchanged, as the PR comment says. - The conflict resolution loses nothing. The merged
docs/data-dependence.mdkeeps 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/andproxy/. Main's new Go code touchesconfig/andcmd/context-guru-proxy, and addsbob-plugin/andpi-package/. I checked the new Go files there: they are standalone Python-test wrappers and import nothing fromdash,proxyorconfig. The branch only adds a route and columns, so main's new readers of the dash API are unaffected. The route table still registersGET /api/me/limitsonce. - No Makefile or workflow conflict. The branch never touched
Makefile,.github/workflows/release.yamlorscripts/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,
limitStatusOKdropping digits, theid DESCtemp b-tree,LatestAuthSubscriptionhaving no index for its filter, old rows reading{}after an upgrade, the single-tenant pairing edge,meLimitsignoring 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..HEADcontains 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 tocmd/andconfig/, 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).
- Merge commit
- 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 vetclean) are quoted from the PR comment; I could not run them.
…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]>
…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]>
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.subscriptioncomes 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
8c0f7cb7does this.Behavior change (asked for by the owner on 2026-11-09):
anthropic-ratelimit-unified-*response headers and the auth kind.auth_subscription, on each request row. A new route,GET /api/me/limits, returns them.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 indocs/data-dependence.md.What changed
proxy/limitheaders.go:readLimitHeadersreadsanthropic-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 ofa-zand_(lower-cased first). It only reads the headers.callerIsSubscriptionis true when the client sentAuthorization: Bearer sk-ant-oat…. It reads the same slot asCallerKeyandCallerAuthSchemeinproxy/tenancy.go. Anx-api-key, a bearer API key and one of our own tokens are not a subscription.proxy/proxy.goandproxy/dashcapture.go:noteLimits(resp.Header)besidenoteUpstream. With several upstream rounds, the last answer with the headers wins.newCapturesets the auth kind on Anthropic requests only.dash: 8 newrequestscolumns, added throughadditiveColumns(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).WHERE limit_seen = 1) for the limit read.insertBatchwrites them andscanRequestreads them back, so/api/requests/{id}shows them too.dash/limits.go:GET /api/me/limits, in the route table asscopeTenant.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.five_hourandseven_daycome 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 (noat_ms).utilizationis a 0..1 fraction in steps of 0.01.?tenant=is ignored). A single-tenant proxy reads all rows.reset_sin 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 indocs/reference/reference.md, and a row indocs/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 loneBearerno.TestLimitHeadersReachTheRowAndTheEndpoint: OAuth bearer through the real proxy. The answer reaches the client unchanged. The row holds the values andauth_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.TestEveryMountedRouteDeclaresItsScopecovers 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 -landgo vet ./dash/ ./proxy/: clean.Open questions
keepalivelibrary, not on this path. Should they? It would make the newest share fresher when the user is idle.reset_sis in the past? Today the caller does it, as the contract says.🤖 Generated with Claude Code