Repository navigation
fix(usage): the meter counts every forwarded internal read, and its spec cannot fail - #896
Conversation
…d read The meter's only internal-read signal was the numeric `currentDepth` Payload attaches while populating a selected relationship. A read an endpoint issues itself on the caller's `req` carries no such signal, so each one was billed as a separate request: `/api/meditations/:id/related-lectures` cost 3 to 5, `/api/lectures/:id/related-meditations` 3, and any client read selecting `webPath` cost 2 through the region-tree resolver. `usage_daily_requests` feeds `HIGH_USAGE_THRESHOLD`, so an inflated route fired the high-usage alert early. `countClientRead` is extracted from the hook and made idempotent per request, through a mutable object on `req.context`. Three things about that cell are load-bearing, and its comment says so: - It is an **object**, not a boolean. `asTrustedReq` spreads `req.context` into a new object, so a boolean written through one copy is invisible to the next. That is the mechanism #559's commit message describes and never had. A nested object is copied by reference, so every copy mutates one cell. - It is **seeded before the spread**, by `asTrustedReq` on the `req` it copies from. Spreading first would give each read its own cell. - The bill therefore lands **inside the first read, after that read's own gates**. The meter runs last in the chain, so an origin-denied or malformed read still costs no quota. A handler billing before its first read would let a misconfigured host page drain a client's daily quota while being refused 403 every time — a collection endpoint has no origin check of its own, because enforcement happens in the forwarded read. So no collection endpoint changes: its own reads bill it, exactly once. Only the two root endpoints call `countClientRead`, because they run no collection `beforeOperation` hook and may read no metered collection at all — `GET /api/atlas/seo`'s root route resolves through two globals and the caller's own `clients` row, and so billed nothing. `/api/atlas/sitemap` reads the region tree on every call and is billed by it anyway, so its call is the floor rather than the only bill. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_016cZPs447tmZb6Qc8xKcrVs
… delta The 362-line spec was vacuous end to end. Seven of its eight cases ran `payload.update` writing `dailyRequests = initial + 1` by hand and then asserted `initial + 1`, so they passed against any implementation, including none. The eighth drove a real read, but read `managers` as a manager and asserted the *client* row was unchanged — true whatever the hook does. Its `describe` title and one comment also named `req.context.usageCounted` and a "shared tracker", neither of which was in the tree. Twenty-two cases now read the counter, drive a real read, and assert the delta, following `globals-client-reads.int.spec.ts`. Every client-reachable route is enumerated — eleven of them — plus an ordinary list read, a `webPath` read, a populating read, a global read, the per-request cell in both directions, the callers that must bill nothing, and two refusals. `/api/clients/report` is the one route deliberately absent, and the header says why. Each half of the fix was reverted and the result measured, rather than claimed: - without the per-request cell, seven go red at 2, 2, 2, 4, 4, 2 and 6; - without the root endpoints' `countClientRead`, exactly one goes red at 0 — the seo root route, the only one reading no metered collection. Five of the eleven route cases pass under both reverts, because with these fixtures each reaches exactly one metered read. The header names them as contract pins rather than regression tests instead of letting them read as either — and they are why the file enumerates every route, not only the ones that were wrong. Three fixtures are load-bearing and say so: the client owns a region, or the sitemap returns before both of its reads; the `webPath` case asserts the resolved path, or a null field would mean nothing was read; and the origin-denied case pairs with an allowed-origin control, because `/songs` maps a refused read onto the same 404 a missing meditation gets. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_016cZPs447tmZb6Qc8xKcrVs
`docs/rules/api-clients.md` said a wrapped read leaves "usage tracking still
seeing the authenticated client", which was true and is the thing that changes.
It gains a section stating the rule a new endpoint has to follow, and the three
hazards a reader cannot re-derive: why the per-request cell is an object rather
than a boolean, why it is seeded before the spread, and why the bill lands
inside the first read rather than at the top of a handler.
`docs/rules/endpoints.md` had the old rule for a root endpoint ("the request is
not counted ... must do it itself"); both atlas endpoints now do it, so it says
how, and says a collection endpoint needs nothing.
Refs #891
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016cZPs447tmZb6Qc8xKcrVs
|
🚅 Deployed to the SahajCloud-pr-896 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The redesign is the right call. It answers #891 with one idempotent cell instead of the ticket's four phases, in 8 files rather than 17. The seven collection endpoints and the region-tree resolver stay untouched.
The mechanism holds. billCell seeds on the pre-spread req, and ctx === req.context whenever a context exists, so it leaves memoizeOnRequest's key alone. Gate ordering is as claimed: usagePlugin.ts:40-45 puts the meter last, and both root endpoints bill after assertClientOriginAllowed. The quota-drain the earlier review rejected is closed. The spec is no longer vacuous — expectOneBill asserts status 200 as well as a delta of 1.
One shape question the PR body already names. usagePlugin wraps collections and globals, and config.endpoints is the third sibling left outside, so "a root endpoint bills itself" is unenforced prose. Rejecting the registration seam is sound, because a wrapper would bill before the handler's own origin check. Raised as an enforcement question only.
Findings
should-fix—docs/rules/api-clients.md:271. "Writes are not metered" is wrong in the published contract. A clientPOST /api/user-submissionscosts 1.consider—usage-tracking-dedup.int.spec.ts:18. The enumeration's completeness claim omits that same write.
What was checked. Profile read. Diff from the checkout at 72df5fc against origin/main. Read whole: hooks.ts, usagePlugin.ts, both atlas handlers, the spec. On the write path, gateRegistration.ts:48 forwards asTrustedReq and bills, while computeReviewFields.ts:47 deliberately does not forward req. Client-reachable endpoints enumerated by requireActiveClient: 12 files, 10 in the spec, and setProject.ts and review.ts use requireActiveManager. No contract surface moved, so there is no consumer side to follow.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
"Writes are not metered, here or anywhere" is the line a consumer budgets against, and it is wrong for the one route it matters on. A client's registration `POST /api/user-submissions` costs 1, because `gateRegistration` forwards `asTrustedReq(req)` for its events lookup and the meter bills that read. The sentence after it already said so, which is the contradiction. The lead now carries the cost. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SHigwMqVeWgZjZE9BDSUFG
The header claimed `/api/clients/report` was the one client-reachable route absent from the list. A client's registration `POST /api/user-submissions` is absent too, and unlike that one it bills — 1, through the registration gate's own events lookup. The two are absent for opposite reasons, so the header names both and says what each costs. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SHigwMqVeWgZjZE9BDSUFG
|
Both adversarial-review findings adopted. Pushed
Lean gate green (2279 unit cases). The review's open shape question — Anomaly: 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Nothing charges a client for a read. `usage_daily_requests` is an abuse signal, read by `HIGH_USAGE_THRESHOLD` to raise `highUsageAlert` — so the billing vocabulary this change introduced (`BillCell`, `billCell`, `usageBilled`, "the one bill", "a route billing 0") named something the system does not do, and set a reader up to look for an invoice. Renamed across the diff: `countCell` / `CountCell` / `usageCounted` and `cell.counted` in the hook, `countedBy` / `expectOneCount` in the spec, and "count" for "bill" in every comment and doc line. `countClientRead` already had the right name. Identifiers and prose only — no behaviour moves, and the 22 metering cases assert the same deltas. `countClientRead`'s JSDoc and the "One request, one count" section now say what the counters are for, since that is the part the vocabulary got wrong. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X23Kv8db1aAqcuCPAH2X49
|
Review addressed. Pushed
Lean gate green (2279 unit cases). PR body refreshed: its 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
`CountCell` was a one-field interface read in one function — its return type, a `satisfies`, and a cast. The JSDoc above `countCell` already says what the type's own comment said, so the name earned nothing a reader could not get from the signature. The cell itself stays an **object**, which is what #891 turns on: `asTrustedReq` spreads `req.context`, so a boolean written through one copy is invisible to the next. Without the shared cell the seven cases `usage-tracking-dedup.int.spec.ts:29` names go red, at 2, 2, 2, 4, 4, 2 and 6. `interface`, `satisfies` and `as` all erase, so no behaviour moves. Refs #891 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PGnuRRzrDQqgbMaoNxUBcc
|
Review addressed. Pushed
Lean gate green (2279 unit cases). PR body unchanged: no 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
Change outline
Behaviour — what the meter counts as "a request"
The meter had one internal-read signal, and Payload only ever sets it for relationship population. A read an endpoint issues itself on the caller's
reqlooked identical to a top-level client read.usageTrackingBeforeOperationHook({ args, operation, req }) src/plugins/usage/hooks.ts - not a published client, or not a `read` → return + not a `read` → return numeric args.currentDepth → return # Payload's relationship population - increment usage_daily_requests, usage_total_requests + countClientRead(req) + +countClientRead(req) # extracted, and now idempotent + not a published client → return + cell = countCell(req); cell.counted → return # every later read of this request + cell.counted = true + one atomic UPDATE on the pg pool # unchanged, incl. fail-openThe dedup is a mutable object on
req.context, and each of its three properties is load-bearing:req.contextinto a new object, so a boolean written through one copy is invisible to the next. That is the mechanism perf(usage): usageTrackingHook still N+1s usage UPDATEs on depth>=1 populate reads #559's commit message describes and never had.reqthe copies are made from. Spreading first would give each read its own cell.Flow — one route, and where the count lands
meditationLectures(req) src/collections/Meditations/endpoints/lectures.ts requireActiveClient, parseQuery findByID meditations asTrustedReq beforeOperation: origin → select → rate → meter - └─ UPDATE # counted 1 + └─ cell unset # counted 1, cell set recomputeWeightsForMeditation asTrustedReq - beforeOperation → UPDATE # counted 1 + beforeOperation → cell set, skip find subtle-system-nodes asTrustedReq # same, ×3 more find lectures asTrustedReq find lectures (fallback pool) asTrustedReqNo collection endpoint changes. Only the two root endpoints, which run no collection
beforeOperationhook at all:atlasSeo(req) src/endpoints/atlas/seo/index.ts requireActiveClient, assertClientOriginAllowed, parseQuery, parseAtlasRoute + countClientRead(req) # the root route reads NO metered collection rootSeo → 2 globals (onlyOnCallerAuthority skips) + the caller's own clients row regionSeo → find regions, find events # count nothing extra nowContract — what one route costs a client's daily quota
Behaviour — the spec that could not fail
Preview
usage.dailyRequests,peakDailyRequestsandhighUsageAlertTest results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(2279 cases)usage-tracking-dedup(22),globals-client-reads,atlas-seo,atlas-sitemap,client-origin-enforcement,api— 135 casesEach half of the fix was reverted and the result measured
countClientReadFive of the eleven route cases pass under both reverts, because with these fixtures each reaches exactly one metered read. The spec's header names them as contract pins rather than regression tests instead of letting them read as either — and they are why the file enumerates every route, not only the ones that were wrong.
Manual verification
usage.dailyRequests, issue oneGET /api/meditations/<id>/related-lectures?audiences=<id>&limit=5, and read it again — the delta is 1, not 3–5.GET /api/regions?select[webPath]=true— the delta is 1, not 2.highUsageAlertstill populate for that client.Notes for reviewer
The counters are an abuse signal, not an invoice. Nothing charges a client for a read —
usage_daily_requestsfeedsHIGH_USAGE_THRESHOLD, which raiseshighUsageAlert. An earlier revision of this branch named the cellbillCelland storedusageBilled, which pointed a reader at an invoice that does not exist.fe92885renames it tocountCell/usageCountedand spells the vocabulary "count" throughout — code, comments anddocs/rules/api-clients.md, whose section is now "One request, one count". Identifiers and prose only; the 22 metering cases assert the same deltas.The design moved after review, and the reason is worth a look. The first implementation added a second
req.contextflag (internalRead) that the meter skipped, and then an explicitcountClientRead(req)in nine endpoint handlers, because a collection endpoint whose every read is skipped counts nothing. Two review lenses rejected it independently, on two counts:validateClientOriginHookruns inside the forwarded read and deliberately does not honourasTrustedReq. Counting at the top of the handler therefore spent the quota before the 403, so a misconfigured or hostile host page could drain a client's whole daily allowance while being refused every time.tests/int/usage-tracking-dedup.int.spec.tsnow pins that case, with an allowed-origin control beside it.asTrustedReqspreadsreq.context. That is true of a boolean and false of an object, which the spread copies by reference — the same thingmemoizeOnRequestrelies on. Once the meter is idempotent, the flag, nine call sites, and a two-mode rule a future endpoint author would have to choose between correctly all go away. The diff is 8 files instead of 17, and the seven collection endpoints and the region-tree resolver are untouched.Three smaller judgement calls:
/api/atlas/sitemap'scountClientReadis a floor, not the only count. It reads the region tree on every call, so its own reads count it anyway, and disabling the call leaves its spec case green. It stays because "a root endpoint counts itself" is the rule a reviewer can check, and without it the route silently goes to 0 the day that read moves. Its comment says so.docs/rules/api-clients.mdpublishes, so it is left alone.POST /api/user-submissionscounts 1 through the registration gate's own events lookup. The earlier design made that 0; this one does not touch it, which keeps the behavioural footprint to reads.Two corrections to the ticket's approach, both from the code:
src/lib/atlas/regionOwners.ts:98,221need no change. The ticket lists them as metered raw-reqreads. They readclients, whichusagePluginexcludes, so nobeforeOperationhook fires;:191reads a global atoverrideAccess: true, whichonlyOnCallerAuthorityalready skips. ⚠ They are correct by exclusion, not by rule — the dayclientsleaves that set, those three start counting and so does/api/clients/report.src/lib/meditations/nodeWeights.ts:76needs no change either. Its only client-reachable caller already forwardsasTrustedReq(req); the other two are write hooks the meter never reaches.Detail
Review findings taken, beyond the redesign: the duplicated client-user guard between the hook and
countClientReadis gone (the hook now checks only what the callee cannot know); the spec'sclientReq/managerReqshare onereqAsbuilder and reusecreateClientAuthenticatedRequest, which owns the two load-bearing details (the id must be numeric or self-access silently denies;_status: 'published'is the auth gate);callHandlertakes payload's ownEndpointinstead of an invented structural type.Review findings rejected, with reasons:
usagePluginalready maps every collection, and its exclusion set would even cover/api/clients/reportfor free. Rejected because the idempotent cell needs no new seam at all, keepsgeojsonmetering through the exact path it does today, and gets the gate ordering right by construction rather than by a rule about where to put a call.globals-client-reads.int.spec.ts. They are duplicates by assertion and not by subject: this PR moves the meter, so "the global surface did not move" is a claim about this change. The spec says so at each case.createCanonicalOwnerfactory totests/utils/testData.ts. The canonical-ownership fixture is now its fifth copy across the int lane, and a factory is the right fix — buttestData.tsis read by five other specs and sits outside this repo'sprAllowlistGlobs, so it is a follow-up rather than a widening of this PR.asTrustedReq(req)to one call per handler (10 sites acrosslectures.ts,relatedMeditations.ts,songs.ts). Harmless today — none of those collections has amemoizeOnRequestconsumer — and with the shared cell, per-read wrapping is no longer a counting hazard either. Churn without a behaviour change.The shared root cause, named because it now has four consumers.
asTrustedReq's clone is the reason the query gate, the meter,src/plugins/cache/cacheHeaders.ts(which already documents the live-preview stamp landing on the clone) and the per-request memos each need their own answer to "is this the caller's read or ours?". This PR adds the meter's answer and does not attempt the general one.The fixture pre-mortem. The canonical-ownership object assumes
canonical.verificationacceptsverified+failureCount+attempts+routingProbewith averdict. Checked againstsrc/lib/clients/verification.ts, the closed schema everyclientssave validates it against — not against the other specs that happen to use the same shape.Rejected mid-implementation, and why it is in the git history. An intermediate commit wrapped each read of the two atlas endpoints in
asInternalReqindividually.memoizeOnRequestkeys onreq.context, so a fresh copy per read is a memo miss, and the documents those endpoints read carrywebPath/webUrlhooks that resolve the region tree and the ownership map off the read's ownreq. It doubled both queries —{ regions: 2, clients: 2 }whereatlas-seo.int.spec.ts's query budget says 1 and 1. The final design makes no copy at all, so the hazard is gone rather than documented.Closes #891
🤖 Generated with Claude Code
https://claude.ai/code/session_016cZPs447tmZb6Qc8xKcrVs