Skip to content

feat(runtime): keep tier 2 query results live - #436

Merged
allisonmahmood merged 2 commits into
mainfrom
tier2/403-query-subscriptions
Oct 1, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
tier2/403-query-subscriptions

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Tier 2 pages can call server queries, but their results do not stay in sync when a colleague changes the data.

Enable generated query .subscribe and useQuery through the existing document stream and scheduler. The host tracks resources read by each query, preserves the last value through refusals, and recovers on reshare. Permanent failures end only the affected subscription; loss of document authority stops the document. The installed SDK uses one Preact runtime in optimized development and production builds.

Stacked on #435, tier2/402-init-tier2. This PR targets that branch and adds only the query-subscription work for #403.

Closes #403.

Verification

  • Typecheck and lint passed.
  • 39 focused runtime tests and 27 Postgres concurrency tests passed.
  • Three published-browser scenarios passed, covering two-viewer updates, reconnect and hidden-tab recovery, unshare/reshare, handler removal, and argument limits.
  • Packed Preact checks passed in optimized development and production builds. Manual browser smoke used real published workerd patches.
  • Standards and spec reviews have no remaining findings.

The full offline suite is not green: 123/125 files passed, with four timeout failures. Postgres mapping passed in isolation, and refresh passed with a longer diagnostic deadline. Both unchanged CLI-init cases still timed out. No diagnostic edits or timeout changes are included.

Implemented with OpenAI GPT-6 Astra using the omp harness.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli 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 620b94b against origin/tier2/402-init-tier2 for #403 and parent spec #384. One pass, no subagents. Merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

[P1] Keep rerun slots until the hosted invocation settles

The new query adapter calls Invocation.call, but it runs inside the scheduler's three-second timeout. Invocation.call owns execution in a separate fiber; interrupting its waiter only marks the reply undelivered. The invocation and its snapshot cleanup continue.

When that outer timeout fires, the scheduler decrements its company and patch counters and starts another rerun before the first releases its snapshot. Slow cancellation therefore lets reruns exceed the connection budget and compete with writes.

#403 requires "Bounds and scheduling as on tier 1: the re-run caps"; #384 §8 specifies "At most 2 of a company's connections run re-runs" and "1 re-run per patch at a time."

Reproduced with the real Subscriptions, Invocation and InvocationCapabilities, a non-returning executor, and a retained snapshot whose cancellation takes one second. Two subscriptions on one patch produced:

first subscription: handler_timeout at 3000 ms
retained snapshot resources when second query started: 2
expected: 1

Keep the scheduler slot until invocation settlement releases or destroys its resources, including after timeout or document disconnect. Reuse the invocation's deadline and settlement ownership rather than timing out only its waiter. Cover delayed cancellation in the rerun-cap regression test.

Standards: 0 blockers. Spec: 1 blocker, rerun slots released before invocation cleanup finishes.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Two blocking findings, most severe first.

1. A timed-out tier 2 re-run releases its re-run slot before the invocation settles

packages/runtime/src/Subscriptions.ts:282-288 wraps reads.read in Effect.timeout(deadline) (3 s). For server.call, Invocation.call forks its owner into the Invocation's own scope, so the timeout only interrupts the join (packages/runtime/src/Invocation.ts:874-883). The owner keeps running. The outer timeout always wins the race: it starts before the invocation's startedAt, because QuerySubscriptions.read first does the platform before lifecycle read (packages/runtime/src/QuerySubscriptions.ts:82).

When it fires, the pump's ensuring (Subscriptions.ts:372-387) decrements companyRunning/patchRunning and schedules the next dirty subscription. Meanwhile the timed-out invocation still holds its workerd call and, for queries with resources, its snapshot's company-database lease. It holds them until its own deadline plus up to tier2.settlement.cleanup (5 s). A slow or spinning query handler, which agent-written code will produce, therefore overlaps re-runs for one patch. The company's re-runs can then hold more than 2 connections at once. Those are the two caps this ticket must keep (spec §8, Scheduling).

Fix: don't apply the outer timeout to server.call. The Invocation already enforces tier2.query.deadline and returns handler_timeout only after settlement, so the slot stays held until the connection is released. One more change comes with that: a query that fails to settle within cleanup would then surface UnsettledInvocation (unknown_outcome). That code is missing from the recoverable table (Subscriptions.ts:110-118), so it would permanently end the subscription for an infrastructure hiccup. Add it for queries.

2. The tier 2 fence trusts client-supplied vector keys

On install, sub.vector is the client's input.vector (Subscriptions.ts:494, :530). Subscriptions.ts:246 folds Object.keys(sub.vector) into input.dependencies, and QuerySubscriptions.admit returns those keys unfiltered as the fence (QuerySubscriptions.ts:297). When the fence equals the vector, Subscriptions.ts:259-271 sends up-to-date without invoking anything. Tier 1 is not exposed, because its admit recomputes keys from the op and ignores the client's keys.

Consequences:

  • A company member can send any table:<patch>:<name> or patch:<id> key and read up-to-date versus snapshot as an equality oracle on revision and lifecycle counters. This works for resources the loaded version never declared. It is not "re-admits" in the spec's sense, and the keys are not canonicalised to what this binding can read.
  • The vector is outside the signature size check (Subscriptions.ts:503) and is bounded only by the ~68 MiB control body (RuntimeStreamApi.ts:865). One subscribe can put tens of thousands of keys into a single IN list (packages/primitives/src/ResourceRevisions.ts:13-19 and the lifecycle query). Past Postgres's 65,535 bind parameters that list fails as source_unavailable, and the subscription retries on backoff forever.

Fix: in QuerySubscriptions.admit, intersect the incoming keys with what the binding can produce: own table:/store: keys and declared sharedTable table and patch: keys. packages/primitives/src/QuerySnapshot.ts:96-105 already builds this exact set.

Checked, not blocking

I checked the following and found nothing blocking:

  • Dependency tracing records the canonical owner before the kind and access checks, and shared aliases map to table:<source> plus patch:<source>.
  • Successful runs replace dependencies, including equal-result runs. Failed runs keep the previous set plus attempted resources. Mid-run wakes are kept through duringRun.
  • Declared business errors and callback refusals are recoverable. handler_failed, schema violations, a removed or wrong-kind handler and oversize results are permanent.
  • Authority is re-checked (check with checkOperation) before snapshots, up-to-date and error frames, and lost authority closes the document.
  • The per-document, per-patch and per-company counts and the 8 MiB snapshot limit are enforced.
  • On mirrored surfaces: the broker's server-args budget, the api schema, docs/API.md, both skills, CONTEXT, product and README are all updated, and the packed Preact acceptance covers dev and the published artifact.

CLI-init timeouts: these are not caused by this diff. It touches no CLI or init code. Run in isolation on this branch, both initializes a tier %s typechecking tree offline… cases time out at 120 s using only ~32 s of CPU over 240 s of wall time. That points to a hang waiting on the local pnpm install or registry, not to load. The same cases pass in CI test (24) on this PR's head.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed the review blockers in 6a6649b.

Fixed

  • Astra P1 and Opus finding 1: hosted query reruns no longer have an outer waiter-only timeout. Invocation owns the deadline and settlement. The scheduler also owns these reruns at registry scope, so document disconnect cannot release a slot while its invocation retains resources. Regressions cover delayed cancellation with and without disconnect, one retained snapshot per patch, and two per company.
  • Opus finding 1, cleanup ceiling: unknown_outcome is recoverable. A regression verifies resource destruction at the cleanup ceiling followed by a successful automatic retry.
  • Opus finding 2: resume admission filters and deduplicates keys against the loaded version's owned tables/stores and declared shared tables' canonical table/source-patch keys. Undeclared keys never reach revision lookup. Regressions cover more than 20,000 forged keys, valid equal-vector resume, and first-access refusal recovery without watching unused declarations.

Updated the API contract and development verification docs.

Kept as is

  • Tier 1's read timeout remains. The detached invocation owner is specific to hosted queries; changing tier 1 would not address either finding.
  • Existing tracing, dependency replacement/union, mid-run wakes, refusal classification apart from unknown_outcome, final authority checks, subscription/snapshot limits, and SDK behavior remain. Opus found these correct, and the focused and full CI suites pass.
  • CLI-init tests and their deadlines remain unchanged. The previously reported local hangs are not fixed or hidden by this commit; both full CI suites pass on the latest commit, including those cases.

I checked conversation comments, review bodies, and inline review comments again after the push. There are no additional findings, and no Grok review was present in those channels. Neither blocking finding was dismissed.

Verification

  • Local typecheck and lint passed.
  • 54 focused tests passed across seven files, including all six new regression cases. The six new cases passed again after the final fixture cleanup.
  • All three published-workerd browser scenarios passed, including two-viewer updates, hidden/reconnect recovery, unshare/reshare, handler removal, and argument limits.
  • CI run 36578592179 passed on 6a6649b: test (22), test (24), postgres-concurrency, clerk-live, lint, cli-smoke, and dependency-review. The separate label check also passed.

GitHub reports no separately configured required checks for this stacked target. All eight reported checks pass, and the PR is MERGEABLE with merge state CLEAN against tier2/402-init-tier2. No unresolved PR blockers; not merged.

Base automatically changed from tier2/402-init-tier2 to main October 1, 2026 03:56
Implement #403 with host-traced dependencies, query-only server subscriptions, recoverable refusals, final authority fences, and the existing shared scheduler. Connect generated queries to useQuery through the installed Preact runtime and cover published stream recovery and packaging.
Keep hosted rerun slots until invocation settlement, including after document disconnect, and retry unknown query outcomes. Filter resume fences to the loaded version's declared canonical resources before revision lookup. Cover delayed cleanup, concurrency bounds, forged resume keys, and recovery.
@allisonmahmood
allisonmahmood force-pushed the tier2/403-query-subscriptions branch from 6a6649b to 39a7c23 Compare October 1, 2026 03:56
@allisonmahmood
allisonmahmood merged commit 6cf5bf7 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/403-query-subscriptions branch October 1, 2026 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area 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): tier 2 query subscriptions: traced dependencies, recoverable refusals, the re-run caps

1 participant