Skip to content

fix(usage): the meter counts every forwarded internal read, and its spec cannot fail - #896

Merged
sydevs-bot merged 7 commits into
mainfrom
claude/fix-891-usage-meter-forwarded-reads
Oct 9, 2026
Merged

sydevs-bot merged 7 commits into
mainfrom
claude/fix-891-usage-meter-forwarded-reads

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The usage meter counted one request per forwarded internal read, so a shaped endpoint cost 3–5.
  • One client request now counts exactly 1 — and a route counting 0 is treated as equally wrong.

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 req looked 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-open

The dedup is a mutable object on req.context, and each of its three properties is load-bearing:

 asTrustedReq(req)                                             src/plugins/usage/hooks.ts
+  countCell(req)                                              # seeded on req, BEFORE the spread
   return { ...req, context: { ...req.context, skipClientQueryValidation: true } }
+
+countCell(req)
+  req.context.usageCounted ??= { counted: false }             # an OBJECT, copied by reference
  • An object, not a boolean. The spread copies req.context into 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.
  • Seeded before the spread, on the req the copies are made from. Spreading first would give each read its own cell.
  • So the count lands inside the first read, after that read's own gates — which is the part that matters beyond the counter itself. See the next view.

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)  asTrustedReq

No collection endpoint changes. Only the two root endpoints, which run no collection beforeOperation hook 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 now

Contract — what one route costs a client's daily quota

 GET /api/events/geojson                     1 → 1
 GET /api/lectures/for-audience              1 → 1
 GET /api/app-cards/for-audience             1 → 1
 GET /api/audiences/for-user                 1 → 1
 POST /api/clients/report                    0 → 0   # excluded collection, by design
-GET /api/meditations/:id/related-lectures   3–5
-GET /api/lectures/:id/related-meditations   3
-GET /api/meditations/:id/songs              1–2
-GET /api/frames/by-narrator/:id             2
-GET /api/atlas/sitemap                      3
-GET /api/atlas/seo  (region / event route)  3–5
-GET /api/atlas/seo  (root route)            0        # read no metered collection
-any client read selecting webPath / webUrl  2        # the region-tree resolver
+every route above                           1
+
+a read refused 403 for its origin           0 → 0   # unchanged, and see Notes

Behaviour — the spec that could not fail

 tests/int/usage-tracking-dedup.int.spec.ts
-  8 cases, 7 of them:
-    read initial dailyRequests
-    payload.update clients  → dailyRequests = initial + 1     # the case writes it
-    expect dailyRequests === initial + 1                       # then asserts it
-  the 8th: read `managers` as a manager, assert the CLIENT row unchanged
-  describe title + one comment name a `req.context` flag absent from the tree
+  22 cases, every one:
+    read the counter → drive a real read → assert the delta
+    all 11 client-reachable routes · a list read · a webPath read
+    a populating read · a global read · the cell, in both directions
+    a manager read · an anonymous read · 2 refusals

Preview

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (2279 cases)
  • Targeted: ✓ usage-tracking-dedup (22), globals-client-reads, atlas-seo, atlas-sitemap, client-origin-enforcement, api — 135 cases
  • Full integration lane: ran green on the earlier, larger version of this change (1501 cases); re-running at push time had not finished, and this design touches a strict subset of those files. CI is the gate.
  • Build: N/A — Railway builds the preview

Each half of the fix was reverted and the result measured

Reverted Red
the per-request cell 7 cases, at 2, 2, 2, 4, 4, 2 and 6
the root endpoints' countClientRead exactly 1, at 0 — the seo root route

Five 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

  1. Against a published client key on the preview, read usage.dailyRequests, issue one GET /api/meditations/<id>/related-lectures?audiences=<id>&limit=5, and read it again — the delta is 1, not 3–5.
  2. Same two reads around one GET /api/regions?select[webPath]=true — the delta is 1, not 2.
  3. Confirm the admin usage display and highUsageAlert still 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_requests feeds HIGH_USAGE_THRESHOLD, which raises highUsageAlert. An earlier revision of this branch named the cell billCell and stored usageBilled, which pointed a reader at an invoice that does not exist. fe92885 renames it to countCell / usageCounted and spells the vocabulary "count" throughout — code, comments and docs/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.context flag (internalRead) that the meter skipped, and then an explicit countClientRead(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:

  • It introduced a quota-drain. A collection endpoint has no origin check of its own — validateClientOriginHook runs inside the forwarded read and deliberately does not honour asTrustedReq. 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.ts now pins that case, with an allowed-origin control beside it.
  • Its central claim was false. The comment said a per-request flag "cannot be idempotent" because asTrustedReq spreads req.context. That is true of a boolean and false of an object, which the spread copies by reference — the same thing memoizeOnRequest relies 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's countClientRead is 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.
  • One acceptance criterion reads two ways. "A manager read, an admin-UI read and a live-preview read still increment nothing" — a manager's read counts nothing because it is not a client, and that is asserted. A client read carrying a preview secret still counts 1, which is what docs/rules/api-clients.md publishes, so it is left alone.
  • A write's forwarded read still counts, as it always has. POST /api/user-submissions counts 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,221 need no change. The ticket lists them as metered raw-req reads. They read clients, which usagePlugin excludes, so no beforeOperation hook fires; :191 reads a global at overrideAccess: true, which onlyOnCallerAuthority already skips. ⚠ They are correct by exclusion, not by rule — the day clients leaves that set, those three start counting and so does /api/clients/report.
  • src/lib/meditations/nodeWeights.ts:76 needs no change either. Its only client-reachable caller already forwards asTrustedReq(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 countClientRead is gone (the hook now checks only what the callee cannot know); the spec's clientReq/managerReq share one reqAs builder and reuse createClientAuthenticatedRequest, which owns the two load-bearing details (the id must be numeric or self-access silently denies; _status: 'published' is the auth gate); callHandler takes payload's own Endpoint instead of an invented structural type.

Review findings rejected, with reasons:

  • Metering at the endpoint-registration seam. usagePlugin already maps every collection, and its exclusion set would even cover /api/clients/report for free. Rejected because the idempotent cell needs no new seam at all, keeps geojson metering 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.
  • Dropping the global-read and refused-read cases as duplicates of 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.
  • Promoting a createCanonicalOwner factory to tests/utils/testData.ts. The canonical-ownership fixture is now its fifth copy across the int lane, and a factory is the right fix — but testData.ts is read by five other specs and sits outside this repo's prAllowlistGlobs, so it is a follow-up rather than a widening of this PR.
  • Hoisting asTrustedReq(req) to one call per handler (10 sites across lectures.ts, relatedMeditations.ts, songs.ts). Harmless today — none of those collections has a memoizeOnRequest consumer — 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.verification accepts verified + failureCount + attempts + routingProbe with a verdict. Checked against src/lib/clients/verification.ts, the closed schema every clients save 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 asInternalReq individually. memoizeOnRequest keys on req.context, so a fresh copy per read is a memo miss, and the documents those endpoints read carry webPath/webUrl hooks that resolve the region tree and the ownership map off the read's own req. It doubled both queries — { regions: 2, clients: 2 } where atlas-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

claude added 3 commits October 8, 2026 00:38
…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
@railway-app

railway-app Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-896 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Oct 9, 2026 at 10:23 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-896 October 8, 2026 00:46 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 8, 2026
@sydevs-bot

sydevs-bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 22:14Z address-review · attempt 1 · session · done
  • 22:14Z address-review · attempt 1 · session
  • 16:40Z address-review · attempt 1 · session · done
  • 16:40Z address-review · attempt 1 · session
  • 01:08Z address-review · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 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 client POST /api/user-submissions costs 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

Comment thread docs/rules/api-clients.md Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 8, 2026
claude added 2 commits October 8, 2026 01:11
"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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-896 October 8, 2026 01:14 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both adversarial-review findings adopted. Pushed 7bd74d4. Comment-only, two files.

  • Adopted — api-clients.md:271 (66a21fe). "Writes are not metered, here or anywhere" contradicted the sentence after it. The lead now names the cost: a client's registration POST /api/user-submissions is 1.
  • Adopted — usage-tracking-dedup.int.spec.ts:18 (7bd74d4). The header claimed one absent client-reachable route; it now names both and what each costs. Took the second option — this diff does not change the write's cost.

Lean gate green (2279 unit cases). usage-tracking-dedup green (22).

The review's open shape question — config.endpoints outside usagePlugin's wrap — needs a seam decision, not an edit.

Anomaly: issue_read method:get_labels answers Could not resolve to an Issue for PR 896, while method:get returns it with its labels.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 8, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review October 8, 2026 01:24
@sydevs-bot
sydevs-bot requested a review from Ardnived October 8, 2026 01:25
@sydevs-bot
sydevs-bot enabled auto-merge October 8, 2026 01:25
Comment thread src/plugins/usage/hooks.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Oct 9, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-896 October 9, 2026 16:50 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Review addressed. Pushed fe92885. One thread, adopted — naming only, no behaviour moves.

  • Adopted — hooks.ts:17-43. The counters are an abuse signal, not an invoice, so the billing vocabulary was wrong. Now countCell / CountCell / usageCounted / cell.counted, countedBy / expectOneCount in the spec, and "count" for "bill" in every comment, docs/rules/api-clients.md ("One request, one count"), docs/rules/endpoints.md and the PR body. countClientRead's JSDoc and the doc section now state what the counters are for.

Lean gate green (2279 unit cases). usage-tracking-dedup green (22) — same deltas as before the rename.

PR body refreshed: its Change outline views named billCell and usageBilled, which no longer exist.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 9, 2026
Comment thread src/plugins/usage/hooks.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Oct 9, 2026
`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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-896 October 9, 2026 22:20 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Review addressed. Pushed 6e09767. One thread, half adopted, half rebutted — type-level only, so no behaviour moves.

  • Adopted — hooks.ts:19-22. The CountCell interface earned nothing: one field, read in one function, and countCell's own JSDoc already said what its comment said. countCell now returns { counted: boolean } inline.
  • Rebutted, thread left open — same thread. The cell itself cannot be a boolean. asTrustedReq spreads req.context (hooks.ts:53), so a boolean written through one copy is invisible to the next, which is why perf(usage): usageTrackingHook still N+1s usage UPDATEs on depth>=1 populate reads #559's flag never worked. Removing the shared object turns seven spec cases red, at 2, 2, 2, 4, 4, 2 and 6.

Lean gate green (2279 unit cases). usage-tracking-dedup green (22) — same deltas as before.

PR body unchanged: no Change outline view named the interface. Review 5475840151 carried no body, so that one thread was the whole of it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 9, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Oct 9, 2026
Merged via the queue into main with commit 660ae7f Oct 9, 2026
27 of 28 checks passed
@sydevs-bot
sydevs-bot deleted the claude/fix-891-usage-meter-forwarded-reads branch October 9, 2026 22:47

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-896 — 6e097672 Deployed Oct 9, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(usage): the meter counts every forwarded internal read, and its spec cannot fail

3 participants