Skip to content

feat(runtime): track server-call usage and limit pressure - #431

Merged
allisonmahmood merged 4 commits into
mainfrom
tier2/399-metering
Oct 1, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
tier2/399-metering

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Tier 2 calls need durable usage accounting without creating an invocation row for every quiet query. Request events need timing and limit data that explain failures and refusals.

Record invocation metrics and database-held time, excluding connection queues. Quiet queries use transactional, deduplicated minute rollups without waiting for persistence before replying. Request events include operation counts, commit outcomes, limit peaks, configuration revisions and the closest limit. API and domain docs describe the accounting boundaries.

Stacked on tier2/398-server-call. This PR contains only the metering commit above that branch. Nested mutation execution remains in #400; nested accounting is verified with supported query calls.

Verification

  • Full suite: 1,346 tests passed before the final review fixes.
  • Post-review focused suite: 44 tests passed, including real-workerd replies while the rollup table is locked.
  • Typecheck and lint passed after the review fixes.
  • Standalone Postgres smoke: 60 settlements for 20 unique runs produced exact totals.
  • Standalone supervisor HTTP smoke preserved the observed capacity peak and configuration revision on a 503 refusal.

Closes #399.

Model: GPT-6 Astra. Harness: omp.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Sep 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 3e987f8 against origin/tier2/398-server-call using git diff origin/tier2/398-server-call...HEAD. One pass, no subagents. Scope: #399 and #384 §14; merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

[P1] Commit failures terminate rollup settlement instead of retrying

Invocation.ts:633–649, QueryRollups.ts:51–55.

#399 requires settlement to be “retried with the same id after an ambiguous failure, so each run counts exactly once.” The pinned Effect SQL client runs COMMIT through Effect.orDie. A connection failure there therefore escapes Effect.retry, which handles typed failures, and terminates the settlement fiber. If PostgreSQL did not commit, a successfully answered query is permanently unmetered even though the host remains alive.

Reproduced against disposable real PostgreSQL through a socket proxy, using QueryRollups.record with the same retry schedule:

  • Drop the connection before forwarding COMMIT: 1 attempt, defect, 0 persisted runs.
  • Let PostgreSQL commit but drop its acknowledgement: 1 attempt, defect, 1 persisted run.

Make commit uncertainty recoverable by the same-id retry. The increment and dedup insert already share one atomic SQL statement; executing that statement without the outer withTransaction, with pruning separate, avoids this defect conversion. Keep a regression covering connection loss around commit, rather than only statement failures and explicit duplicate calls.

Summary: Standards 0 blockers; Spec 1 blocker, lost rollup metering after a commit-path connection failure.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/398-server-call...HEAD against #399 and spec #384 §5–7, §14 and §16. Findings are ranked most severe first.

1. Rollup settlement retries forever at a fixed 50 ms and can double count past the dedup window (correctness)

packages/runtime/src/Invocation.ts:649: rollups.record(...).pipe(Effect.retry(Schedule.spaced("50 millis")), Effect.forkIn(scope))

  • No cap, and permanent errors are retried. Every error is retried, including non-transient ones. QueryRollups.test.ts shows one itself: a CHECK violation (guestMs: -1) fails with SqlError on every attempt. A permanent failure like that leaves a fiber in the Invocation layer scope that retries 20 times a second until the host shuts down. One such fiber is added for every quiet query.
  • Retry storm during a platform-database blip. Each quiet query settled during an outage adds another fiber retrying at 20 Hz against the shared platform pool, which is the same pool that serves session and admission reads. At 100 quiet queries/s, a 30 s outage leaves 3,000 fibers making about 60k attempts/s just as the database comes back.
  • Exactly-once holds only inside the hour. QueryRollups.ts:53 prunes run ids older than one hour on every settlement, from any replica. Take a replica whose first commit landed but whose acknowledgement was lost, and which then cannot reach the platform database for more than an hour (a partition, not a full outage). Other replicas prune its id in the meantime. Its eventual retry then inserts the id again and adds the run a second time. The spec only works if retries end inside the dedup window.

Fix: exponential backoff with jitter, retries only on connection-class or ambiguous SqlErrors, and a total retry budget well under the one-hour id retention. Log and drop after that; a host that gives up loses the run, as the spec already allows for crashes.

2. QuerySnapshot.Resource.dbMs is now an orphaned second db-time meter (method)

This PR replaced its only production consumer (capability?.snapshot.value?.dbMs) with DatabaseMeter. It left the old wall-clock measurement in place:

  • the interface at packages/runtime/src/QuerySnapshot.ts:9
  • the implementation at packages/primitives/src/QuerySnapshot.ts:64 (startedAt/stoppedAt exist only to feed it)
  • its tests at packages/primitives/src/QuerySnapshot.test.ts:120,366

We now have two definitions of "time holding a company connection", and only one of them is metered. Delete the getter, its fields and its assertions so DatabaseMeter is the single source.

3. A nested call's deadline sets limitId on the parent's request event (correctness, event attribution)

packages/runtime/src/Invocation.ts:493: if (timedOut) yield* WideEvents.enrich({ limitId: ... }) has no parent === undefined guard. The outcome and code enrichment next to it does (:697, and the ...(parent === undefined ? …) block).

Take an action that calls a nested query, catches its handler_timeout and returns ok. Its request event becomes outcome: "success" with limitId: "tier2.query.deadline". The new Analytics glossary entry says a limitId "names the limit that refused it", so this contradicts it. The nested peak already reaches the event through limits/closestLimitId. Guard this line the same way as the others.

4. A Done-when criterion is closed without being met (intent)

#399's Done-when includes "an action's db_ms covers its nested mutation's connection time". This stack refuses nested mutations, so the PR verifies the mechanism with a nested query (InvocationLocal.test.ts, parent_ms >= child_ms) and defers the rest to #400 in docs/product.md:398. That is a reasonable split. But the PR says Closes #399, and #400's Done-when does not include this check, so the criterion will be lost. Either add it to #400 (a nested-mutation db_ms assertion once ctx.run reaches mutations) or keep #399 open until it is met.

Checked and fine

  • Rollup SQL: the id and the increment commit in one statement and transaction, and a conflicting id adds nothing. The test covers the UTC start-minute bucketing, and the concurrent-runs test on real Postgres gives exact totals.
  • Quiet, logged, failed and nested query routing: no run gets both a rollup increment and an invocation row.
  • Client disconnect does not lose counts: the owner fiber and the rollup fork live in the layer scope, not the request's.
  • DatabaseMeter starts after source.reserve, so queue wait is excluded. Parent chaining covers nested reservations. The request event's per-reservation adds are overwritten by the inclusive top-level snapshot, so nothing is double counted on the settled path.
  • callbacks, attempts and bytes are additive in the request event, and elapsed, guest and db time are inclusive.
  • Supervisor busy peaks travel through Management.Refusal.limits, and docs/API.md is updated.
  • Surfaces: glossaries and docs/product.md are updated. The migrations were already present from the base stack, so no new record is needed.

@allisonmahmood

allisonmahmood commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the reviews in 3716c47.

  • Astra P1: fixed. Removed the explicit transaction around the atomic rollup CTE so commit-path connection loss stays recoverable. Real PostgreSQL socket tests cover loss before execution and loss of the entire committed response. Same-id retries leave exactly one run.
  • Opus 1: fixed. Settlement retries only retryable SQL failures, with jittered exponential delays starting at 100 ms and capped at 10 seconds. A five-minute total budget covers SQL acquisition, execution and retries, well inside the one-hour dedup window. Permanent failures and exhausted budgets log a normalized diagnostic and stop. Pruning failures do not retry an acknowledged increment.
  • Opus 2: fixed. Removed the orphaned QuerySnapshot.dbMs interface, timer state, test fixture field and assertions. DatabaseMeter is the sole connection-time meter.
  • Opus 3: fixed. Only root timeouts set the request refusal limitId. The regression verifies that an action handling a nested query timeout returns success without a refusal code or limitId, while retaining the child deadline peak. Root timeout attribution still works.
  • Opus 4: kept the implementation boundary, transferred acceptance. Per Foreman direction, nested mutations remain in feat(runtime): mutations: the host-owned SERIALIZABLE transaction, mutation keys and retry(), write_conflict #400. Added the nested-mutation db_ms acceptance check in feat(runtime): mutations: the host-owned SERIALIZABLE transaction, mutation keys and retry(), write_conflict #400 (comment). This PR does not claim to exercise nested mutations.

Conversation comments, review bodies and inline review comments were checked. No Grok finding was present.

Verification: 67 focused tests passed across six files; typecheck and lint passed. A standalone real-Postgres smoke exercised statement loss, lost commit acknowledgement and pruning-connection loss, retaining exact totals after duplicate settlement in all three cases. CI found a generator/document mismatch on both Node versions; the other 1,357 tests passed. Fixed the API documentation generator in 7f6c59b and removed its exact-Markdown copy assertion rather than retaining a wording snapshot. Running the real generator reproduced the committed API.md byte-for-byte, including the capacity metadata. All 22 remaining API tests, API typecheck and the formatting check passed. Node 24 then passed all 1,357 tests. Node 22 exposed two existing blob-asset publishing cases running into the default five-second test timeout. Commit 1177d5f gives that parameterized test the same 30-second real-subprocess budget as adjacent publishing cases; all four cases passed locally without changing their refusal assertions.

Final verification on 1177d5f: all eight checks passed: test (22), test (24), lint including formatting and typecheck, postgres-concurrency, clerk-live, cli-smoke, dependency-review and label. CI: https://github.com/allisonmahmood/patchy-cloud/actions/runs/36531312054. GitHub reports CLEAN and MERGEABLE against tier2/398-server-call. No required-check rules are reported for this branch. Rechecked conversation comments, review bodies and inline comments after CI; no additional findings or Grok review appeared. No unresolved blockers; the PR remains open and unmerged.

@github-actions github-actions Bot added the area:cli Touches the cli area label Sep 29, 2026
Base automatically changed from tier2/398-server-call to main October 1, 2026 02:59
@allisonmahmood
allisonmahmood merged commit 6afdffe into main Oct 1, 2026
14 of 15 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/399-metering branch October 1, 2026 03:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:docs Touches the docs area area:primitives Patch tables and files area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(runtime): metering and the request event: db_ms, invocation metering, query rollups, peaks against limits

1 participant