Skip to content

feat(runtime): keep tier 1 pages in sync - #426

Merged
allisonmahmood merged 2 commits into
mainfrom
tier2/394-revisions-wakes
Oct 1, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
tier2/394-revisions-wakes

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Tier 1 pages do not see colleagues' saves until reload, and lifecycle updates only reach documents on the same host.

Adds live list and get subscriptions for owned and shared tables through .subscribe and useQuery. Writes and source lifecycle changes commit durable revisions; local and Postgres wakes trigger bounded reruns, while reconciliation recovers missed notifications. Ordered resync preserves the last result and keeps the reconnecting pill visible until catch-up completes.

Stacked on tier2/393-stream. This PR targets that branch and contains only the #394 changes.

Multi-replica ingress must use patchy_stream_affinity application-cookie routing. The API reference and ADR document the required configuration.

Verification

  • pnpm typecheck and pnpm lint passed.
  • pnpm test: 104 files, 1,166 tests passed.
  • Chromium stream and subscription acceptance: 23 scenarios passed, including two viewers, lost admission frames, reconnect fences and seven HTTP/2 streams.
  • Real two-host and local PGlite smoke checks passed. Missed notifications and listener loss recovered; equal-vector resume avoided a rerun; 50 committed writes coalesced into one rerun and one snapshot.

Closes #394.

Implemented with OpenAI GPT-6 Astra via omp.

@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 area:primitives Patch tables and files area:ui Portal and first-party browser pages, shared rendering and styles size:xl Over 1,000 changed lines; review in multiple passes labels Sep 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 142b8c9 with git diff origin/tier2/393-stream...HEAD, against #394 and #384. One inline pass, no subagents. Two merge blockers.

Standards

No merge-blocking method or YAGNI findings.

Spec

  1. [P1] Intent: enforce the public-scope refusal for subscriptions.

    RuntimeStream.ts:322-337 checks version eligibility and tier, but not the loaded version's effective scope. Tier 2: hosted server code, live sync and the execution service #384 §7 requires admission with "scope not public"; ADR-0010 explicitly keeps the lifecycle stream alive after a company patch becomes public while data operations remain refused.

    Reproduced through the real API: open a company document, insert a row, then share its current version publicly. Direct tables.list returns 403 not_available_on_public, but a new tables.list subscription on that same document returns a snapshot containing the row. Apply the normal effective-loaded-version scope check before subscription reads and reruns, returning the data-operation refusal without closing the lifecycle stream. Historical company-scoped versions must retain their existing behavior.

  2. [P1] Intent: repair missing snapshots instead of acknowledging undelivered data.

    Subscriptions.ts:434-441 ignores the replacement's vector/revision when its operation and arguments match an existing subscription. The equal-vector shortcut then compares durable state with the server's last sent vector, not the client's last received vector. feat(runtime): revisions and wakes from every writer, cross-host NOTIFY with reconciliation, resync, and tier 1 list/get subscriptions #394 requires vector-equal resync; Tier 2: hosted server code, live sync and the execution service #384 §8 says a "missed wake or frame delays a document and never leaves it wrong."

    Reproduced by delivering snapshot 1, dropping snapshot 2, and replacing the desired set with snapshot 1's vector. The server replies up-to-date at revision 2, and the real query registry reports ready while retaining snapshot 1's rows. Subsequent equal-vector reconciliation cannot repair those rows. Honor the client's vector on replacement and resend the cached snapshot or rerun when it is behind. Only answer up-to-date when the client's retained data is current.

Verification: pnpm build passed. Both failures reproduced against a disposable server and real Postgres with offline test sessions; the dropped-frame scenario also exercised createQueryRegistry. No source edits.

Summary: Standards 0 blockers; Spec 2, worst P1 public-scope admission bypass.

@allisonmahmood

allisonmahmood commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner Author

Opus review

Scope: git diff origin/tier2/393-stream...HEAD, read against #394 and spec #384 §8, §15 and §16. I read the whole revision/wake/NOTIFY/reconciliation path (Subscriptions.ts, RuntimeStream.ts, Wakes*.ts, SubscriptionReads.ts, Inventory.ts, CompanyDatabases.withPatchLock, Patches.withLifecycleTransaction) and the shell and client protocol (serving/src/stream.ts, clientTransport.ts, queryRegistry.ts). Five findings, most severe first.

1. A refused shared source leaves the document stuck on "Reconnecting" and re-runs the whole document every 30 s

packages/serving/src/stream.ts:274 handles every non-permanent error frame by marking the entry stale, calling status.connecting() and scheduling a full replace. access_denied and patch_paused count as recoverable (packages/runtime/src/Subscriptions.ts:112), and that part is right: a refused source should stay subscribed. The problem is what follows. While the source is retired, deleted or unshared, that subscription never becomes fresh, so reconciled() never clears the pill. reconciliationAttempts never resets either, so every 30 s the shell posts a full replace. On the server, every install of an existing id sets epoch++, dirty and retryAt = 0 (Subscriptions.ts:440), so every subscription in the document runs admit plus fence again, and the failing one skips its own backoff.

The spec calls a refusal recoverable and reserves the reconnecting element for stream reconciliation to the fences. This implementation shows a consumer of a retired source "Reconnecting" for as long as the source stays retired, which is the acceptance scenario this ticket owns. Fix: treat a transient subscription error as reconciled for the pill (it reached the server and has an answer), leave its retry to the server's backoff, and don't answer one subscription's error with a document-wide replace.

2. Every stream close puts every subscribed query into an error state immediately, including routine token-expiry closes

stream.ts:310 sends {type:"disconnected"} whenever the SSE ends, and packages/patchy/src/clientTransport.ts:119 turns that into a source_unavailable error on every query listener. The stream already closes at every session-token expiry (RuntimeStream.ts:462, close("reauthenticate"); Clerk session tokens default to 60 s). So every subscribed screen flips to status: "error" about once a minute until the replace answers. The patchy-tables skill's example renders {query.error && <p role="alert">…} (packages/sdk/skills/patchy-tables/SKILL.md:95), so agents will build pages that flash an alert on a schedule. The shell deliberately delays its own reconnecting pill by 2 s for this reason. Page-level staleness should follow the fence, as the pill does, and not the raw socket. Drop the synthetic disconnected error, or delay it the same way.

3. POST /api/runtime/subscriptions has no rate limit at all

apps/server/src/ApiGuard.ts:87 adds the path to the runtime bypass, whose comment says the handler "owns its session, audience and per-viewer limit". RuntimeStream.update (packages/runtime/src/RuntimeStream.ts:524) does session verification, a viewer lookup and a limits read, but consumes no limiter; /api/runtime/call enforces runtime.calls.perMinute. Any signed-in member can loop replace requests. Each one runs that platform work and re-dirties every subscription in the document with its backoff reset, which occupies the company's two re-run slots. Finding 1 makes the shell do a milder version of this by itself. Charge these requests to the same per-viewer bucket as calls, or give them their own registry entry.

4. The re-run pump can starve every other subscription on a patch while one table is under steady writes

pump (Subscriptions.ts:312-316) always walks documents and each document's subscriptions in insertion order, with at most one re-run per patch. When a run finishes, ensuring re-dirties it if a wake arrived mid-run, and the next pump picks the same first subscription again. If writes arrive faster than one run takes (a browser inserting rows in a loop, for example the 50-write case), the first document's subscription takes the patch slot every time, and a second viewer's screen stays stale until the burst ends. The "two browsers stay in sync" check passes only when the observer happens to be first in the set. A rotating start index, or moving a served subscription to the back, fixes it.

5. Surface: docs/DEVELOPMENT.md migration list

docs/DEVELOPMENT.md:812 still ends at 0009_limits_overrides. CLAUDE.md, ADR-0003 and the three migrator spreads now include 0010_patches_lifecycle_revision; this list needs it too.

On the patchy_stream_affinity cookie

The spec doesn't ask for it, and NOTIFY plus reconciliation doesn't make it unnecessary. NOTIFY and reconciliation carry resource wakes and lifecycle frames to whichever host holds a stream. They don't route a subscribe/unsubscribe POST to the process whose in-memory Document it must mutate. Without some form of affinity, every cross-replica POST is a 409 and a stream abort. With the one-way SSE plus POST design the PR chose, affinity or forwarding is required, and cookie stickiness is the smallest option. I would keep it. It is a deploy constraint the spec never recorded, though, so it belongs on the CDK ticket (#415) as well as in ADR-0010, or the ALB will be built without it.

Checked without findings: migration numbering and the three spreads, idempotent inventory upgrade for resource_revision, revision bumps in the same transaction for row writes, file put/delete, putTable/putColumn/putIndex/putStore, reclamation and every patch lifecycle act (portal and bulk paths included), post-commit-only publication in withPatchLock and withLifecycleTransaction, NOTIFY splitting under 8,000 bytes, listener reconnect forcing full reconciliation, mid-run wake retention, refused-read dependency retention, the equal-vector resume path, ordered-delta buffering, the gap timer and replace supersession, and the per-document/snapshot bounds.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed against #394 and #384 §8, on 05ea99c...142b8c9.

The hosted path is the method §8 named. A write bumps one durable revision inside its transaction. After commit, the transaction owner publishes resource keys. One LISTEN on the platform database carries those keys to other replicas, and a 30 second reconcile compares the stored vectors when the hint is lost. Tier 1 list and get subscribe on the document stream. useQuery subscribes through the query registry.

patchy dev does not load a tier 1 page after this change.

Spec

The local shell returns before the frame loads. packages/serving/src/broker.ts now opens a stream for data-scope="local" and, when data-viewer-id is missing, calls notice("bootstrap_failed") and returns. That return sits above frame.src = contentSrc, so the iframe never gets its document. packages/serving/src/shell.ts emits data-viewer-id only for scope === "company", and includes the shell styles on that same condition. packages/patchy/src/devServer.ts renders scope: "local" and does not pass a viewer id, while the same function already knows prepared.identity.user.id and mounts RuntimeStream. A local tier 1 page shows the bootstrap failure and an empty frame. Pass the viewer id through for local, emit the attribute, and include the shell styles.

Dev lifecycle has no counter to reconcile. SubscriptionReads.devLifecycle returns "0" while the version is loaded and "-1" otherwise. A missed publish, retire, or restore in patchy dev cannot be repaired from durable state. Production SubscriptionReads.lifecycle reads patches.lifecycle_revision. Hosted publish, sharing changes, retire, delete, restore, and rollback advance that counter and announce patch:<id>. Portal batches go through withDependencyLock. The nested-rollback test shows a cancelled retire emits nothing, and the committed retire emits its key after the lock's transaction commits.

The done-when lines are only partly tested. The diff does prove three of them:

  • Two browsers on one instance. a colleague's write updates the subscribed screen and reconnect catches a missed write sees the other page's rows change, including a write made while the stream was paused.
  • An equal vector skips the query. re-admits an equal resume vector without executing and suppresses unchanged results asserts up-to-date and reads === 0.
  • Source lifecycle wakes consumers, portal acts included. keeps an admitted consumer through source publishes, sharing and CLI lifecycle acts and portal retire, delete and restore wake the same consumer without replacing its last result cover publish, unshare, retire, delete, and restore. Restore keeps the last snapshot.

These three are not in the diff:

  • 50 committed writes coalescing to a handful of re-runs. retains a wake received during a read and coalesces a burst into one following read calls reconcile 50 times on a stub reader and asserts two reads. Nothing commits 50 rows.
  • A wake on host A reaching a subscriber on host B. delivers committed resource keys and write linkage to another replica asserts that a second client on the same pool received keys. No document is subscribed.
  • A dropped listener, and a host that dies between commit and NOTIFY, both recovering a subscription from revisions. requests durable reconciliation after a dropped listener reconnects terminates the LISTEN backend and asserts an empty key set. reconciles a source commit whose owner never delivers its wake stubs publish and, after 30 seconds, expects a lifecycle up-to-date in the same process.

The code path for those cases is real. Empty keys call DocumentSubscriptions.reconcile, and reachesFence refuses a snapshot behind the pre-read vector. The PR body describes two-host and PGlite smoke checks, and "50 committed writes coalesced into one rerun and one snapshot." Those runs are not tests in this diff. PGlite cannot LISTEN across sessions.

An equal vector still counts as a re-run. #394 says resume with an equal vector costs no re-run. pump sets running, and takes the company and patch permits, before run compares vectors. The query is skipped and doc.reruns stays put. events.withEvent({ type: "re-run" }) still opens around admit and revisions().

The 256 and 1,024 caps count this process. install sums documents on this host. Each document has its own gate, so two subscriptions for one patch can both pass the check and both insert. A second replica can admit another full set. The registry scopes those limits to the patch and the company. §14 also says admission is counted per replica in v1, so a cross-replica counter would be new machinery. The same-process race overshoots even the per-replica reading. The document cap of 64 is serialized on that document's gate. Nothing is evicted.

Checked and present: row writes and store put/delete bump resource_revision inside the write transaction and publish keys after commit. Sweeps bump through Reclamation.reclaimNamespace. Unshare bumps through inventory. Migration 0010_patches_lifecycle_revision is on the shared patches migrator, so the server, the dev runner, and the vitest template all apply it. One channel, patchy_runtime_wakes. get depends on table:<owner>:<table> and patch:<owner>, so a missing row updates when any write to that table commits. Ordered deltas, a buffer of 64, and a 5 second gap. A refused or permanent subscription is left out of the admitted set until the page subscribes again. An access refusal records the resource first, and access_denied stays recoverable so a reshare can wake it. The reconnecting chip clears only when admitted === sequence and every desired entry is fresh. Tier 2 query subscriptions and row-level keys are absent, which is what this ticket should leave for later.

Standards

Hard. packages/primitives/src/SubscriptionReads.ts reports a lifecycle change during a read as new Runtime.SourceUnavailable({ cause: { reason: "lifecycle_changed" } }). SourceUnavailable.cause is Schema.Defect(). The effect-service conventions say a pure domain failure does not get a manufactured cause, and lifecycle_changed never becomes a tag or a catchTags case. The client still sees source_unavailable, which is the recoverable retry §8 asks for. Put the condition on a real field, or a small tagged error mapped to that code at the wire.

Hard. ADR-0003's ledger lists 0010. docs/DEVELOPMENT.md still ends the migration list at 0009_limits_overrides. ADR-0009 still says the platform ledger has eight entries and ends at 0008.

Hard. RuntimeStream.update refuses a subscription POST with an Authorization header, a Sec-Fetch-Site other than same-origin, a wire version that is not current, or a principal that is null or not the admitted viewer. The GET /api/runtime/stream description states those rules. The POST /api/runtime/subscriptions description, and the same paragraph in docs/API.md, do not. That POST text also calls snapshot.vector a resource revision vector. SubscriptionReads.dependencies always records patch:<id> beside the table key. The Runtime glossary already lists patch: as a revision key.

Judgement. The Busy and company-database catchTags mapper is copied in SubscriptionReads.ts and TableOperations.ts. The same "missing key is "-1", then overlay rows" fill appears twice in SubscriptionReads.ts. The Wakes-to-ResourceChanges adapter is written out in Server.ts, devResources.ts, and two test fixtures. duringReadKey in packages/runtime/src/Subscriptions.test.ts is never assigned. RuntimeStreamApi repeats the bounded body read already in RuntimeApi.

Wakes.ts, WakesPostgres.ts, and StreamLimits.ts follow the service file order. Subscriptions.ts stays a module inside Runtime. No HTML or CSS changed, so the UI-consistency spec does not apply.

Method

For a table write the path is short. TableOperations.withWriteTable increments patchy.tables.resource_revision in the same transaction as the row change, then Wakes.publish sends table:<patchId>:<name>. WakesPostgres.publish hands that set to in-process listeners and NOTIFYs patchy_runtime_wakes, splitting so the payload stays under 8,000 bytes. Server.ts starts one LISTEN. On connect it publishes [], which marks every subscription dirty. A matching wake does the same for the subscriptions that named that key. Subscriptions.run reads the current vector. An equal vector sends up-to-date and does not call read. A moved vector reads under REPEATABLE READ and sends snapshot, or up-to-date when the JSON is unchanged, only if the snapshot reaches the pre-read fence. Otherwise it marks the subscription dirty and tries again. Each open document also sleeps subscriptions.reconcile.interval and reconciles served version, patch state, and authority from stored rows.

Listen and notify use different connections, so a replica can also receive its own NOTIFY. The second hint lands on a subscription that is already running or already fresh, and the fence turns it into up-to-date or one coalesced extra pass.

withLifecycleTransaction drops the hint when some other platform transaction is already open. That is the branch at Patches.ts where sql.transactionService is present and the function returns the result without wakes.publish. Callers that are themselves the lifecycle transaction, including withDependencyLock, publish after commit. Reconciliation is the backup for the other case, which matches the rule that a hint may be lost and the counter may not.

Keep causedByEventId, the per-query revision, store-key wakes, and the transient backoff. #394 asks for the re-run wide event to name the write that caused it, and for snapshot to carry the query revision. §8 says transient failures back off and keep the last value. Store writes have no tier 1 subscriber yet. The wake rule still says the writer announces the keys it touched. Shared stores are a later ticket. The shell's sequence, admitted cursor, and replace timer are the client half of ordered deltas. The server cannot notice a POST that never arrived.

YAGNI

The new modules are about as small as this behavior gets. Wakes.ts is the in-process listener set. WakesPostgres.ts is one LISTEN, a reconnect reconcile, and the byte split. StreamLimits.ts is local defaults versus SQL overrides, which dev needs because it has no override database. Subscriptions.ts is long because the sequence, the buffer, the fence, coalescing, and the caps are one registry.

The 1,762-line change in CompanyDatabases.test.ts is reindent. Ignoring whitespace, that file plus OrphanSweep.test.ts and PgliteCompanyDatabases.test.ts are about +86/−39, from providing ResourceChanges on the test layer. There are no new assertions in that churn. The runtime and patches subscription tests assert frames and whether a read ran. They do not assert SQL text, and they do not mock Postgres.

Summary

Standards: 3 hard findings, worst is the manufactured lifecycle_changed cause, next to the two docs that still describe the old migration ledger. Spec: 4 findings, worst is that patchy dev fails bootstrap and never loads the frame.

Reviewed with Grok 4.7 in the Grok CLI, eight read-only agents.

@allisonmahmood

allisonmahmood commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner Author

Review disposition in 277d6e3. Read the Astra, Opus and Grok conversation reviews; GitHub reported no separate review bodies or inline comments.

Fixed

  • Public-scope bypass: subscription admission and delivery recheck the loaded version’s effective scope. Public data access returns not_available_on_public without closing the lifecycle stream; historical company versions remain eligible.
  • Dropped-snapshot recovery: replacements use the vector/revision the client actually received. A behind client receives a current whole-result snapshot rather than an incorrect up-to-date answer.
  • Refusal/reconnect feedback: a recoverable query refusal answers its reconciliation fence. It retains data/error and recovers through server backoff or source wakes, without a stuck reconnect pill or document-wide replacement loop. Routine stream closure no longer manufactures query errors.
  • Control-request rate limit: subscription POSTs share the existing runtime.calls.perMinute store and viewer/patch bucket with ordinary calls, including 429/Retry-After behavior.
  • Fairness and events: completed runs rotate behind pending subscriptions/documents. Successful equal-vector checks do not read the query or emit a re-run event. Removed the unused duringReadKey test state.
  • Local bootstrap: scripted local shells receive the local viewer ID and shell styles. The packed CLI’s previously failing local browser flow now passes.
  • Structured lifecycle failure and docs: replaced the fabricated defect cause with a tagged lifecycle-change error; updated migration ledgers and generated API documentation for authentication, scope, rate limiting, received vectors and lifecycle keys.
  • Committed acceptance: the browser suite now covers cross-host writes, terminated LISTEN connections, and an actual publisher SIGKILL after a real API write commits but before NOTIFY. A barrier exists only in the disposable database; NOTIFY stays blocked until the surviving subscriber reconciles. Added refusal/restore and token-refresh regressions. The offline init fixture’s deadline is now 60s after measuring its successful install/typecheck/refusal path at 31.1s; no production timeout changed.

Kept, with reasons

  • Affinity cookie: retained. Subscription controls address a process-local SSE registry; NOTIFY does not route control requests. Added the requested ALB application-cookie requirements to #406 and #415.
  • No extra cap lock: after the asynchronous limit lookup, count/check/insert is synchronous with no yield between them. Separate document gates do not create the reported same-process race. Per-host ceilings remain the specified v1 contract.
  • Bounded equal-vector preflight: authority and revision checks still share the concurrency bound, preventing unbounded database work. They do not count as query reruns.
  • Fixed local lifecycle authority: local fixtures/configuration change on restart and code builds reload the shell. There is no local publish/retire/restore transition to represent with a new lifecycle counter; real local data revisions and subscriptions remain live.
  • Small boundary-specific duplication: retained the capability error mappings, platform/company vector overlays, explicit host/dev Wakes adapters and route-owned bounded-body readers. Their separate authority/storage/transport boundaries do not justify a new cross-boundary abstraction in this fix.

Verification

  • pnpm typecheck and pnpm lint passed.
  • pnpm test:packed-cli-e2e passed the complete packed-CLI real-server contract.
  • All 25 stream/subscription Chromium scenarios passed across the targeted runs, including the real commit-before-NOTIFY publisher death.
  • Manual Chromium smoke: two actual local documents loaded; a save in one updated the other’s useQuery result without reload or reconnect state. Disposable services and smoke files were removed.
  • Final pnpm test: 104 files, 1,177 tests passed.
  • All eight checks passed on 277d6e3: Node 22/24 tests, Postgres concurrency, Clerk live, lint, packed CLI smoke, dependency review and labels. CI run. GitHub reports no separately configured required-check list for this stacked branch.
  • Final review check: no new or edited reviewer findings, no formal reviews or inline comments. PR is MERGEABLE / CLEAN; no merge performed. The base remains tier2/393-stream.

Base automatically changed from tier2/393-stream to main October 1, 2026 01:50
@allisonmahmood
allisonmahmood force-pushed the tier2/394-revisions-wakes branch from 277d6e3 to 1d2a24d Compare October 1, 2026 01:50
@allisonmahmood
allisonmahmood merged commit c4c49f9 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/394-revisions-wakes branch October 1, 2026 02:01
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:primitives Patch tables and files area:server Touches the server area area:ui Portal and first-party browser pages, shared rendering and styles 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): revisions and wakes from every writer, cross-host NOTIFY with reconciliation, resync, and tier 1 list/get subscriptions

1 participant