Skip to content

Prototype: the reactive query loop across two browsers #313

Closed

Description

@allisonmahmood

Part of #294.

Question

Does the reactive-query model feel right from the builder's chair and hold up under the hard cases? Build a throwaway loop on the dev stack: a query and a mutation as plain functions, a subscription from the frame through the shell over the stream the research recommended, invalidation after commit at the runtime's dispatch point, table-level tracking. Open the same patch in two browsers as two users and show a write in one arriving in the other. Then the hard cases: a write racing subscription setup, a second viewer whose authority differs receiving only their result, a viewer revoked mid-subscription, the stream dropped and reconnected with a fresh snapshot, and a burst of fifty writes coalesced. Note what a fresh agent would have to understand to write a correct subscribed screen.

Output: the prototype on a prototype/<name> branch and a never-merged PR with a Try it section; the findings in the resolution comment; astra's evaluation recorded beside Allison's.

Activity

  1. added
    wayfinder:prototype
    on Sep 19, 2026
  2. allisonmahmood commented on Sep 22, 2026

    @allisonmahmood
    OwnerAuthor

    Prototype: PR #343 (never merged), branch prototype/reactive-loop

    Built by a Fable subagent on 2026-09-22 against main at ef3e790. One command runs every hard case offline (isolated server and Postgres, two Playwright browser contexts as two users of one company):

    pnpm test:prototype-reactive
    

    The PR's Try it section has the two-window walkthrough on pnpm dev. Every file is marked PROTOTYPE for #313.

    What was built (the decided model, as code)

    • After-commit hook in Runtime.dispatch, after the mutation's log record succeeds; the wake carries only the resource key (table:<patch>/<name>, store:<patch>/<name>). In-process listener bus with an in-memory per-key revision and a process epoch.
    • Subscription identity: patch, version, op, canonical args (sorted keys, undefined stripped). Dependency is table-granular, derived from the args.
    • Transport: one text/event-stream per open document from the shell broker, forwarded to the frame as a subscription event over the existing MessageChannel. Frames: hello, must-resync, snapshot{id, revision, tableRevision, value}, up-to-date, error, stop. Native EventSource cannot carry the runtime's admission headers, so the broker uses fetch plus a hand-rolled SSE parser and reconnect.
    • Re-run through the runtime's call under the stream's own request, so every re-run re-admits the session, principal and deactivation state. Its own rate-limit bucket (3000/min per viewer × patch) plus a process-wide semaphore of 16 concurrent re-runs.
    • Coalescing: trailing debounce 25 ms, max wait 250 ms, one re-run in flight per subscription; unchanged serialised results suppressed; transient failures (busy, rate_limited, source_unavailable, timeout) retried with backoff, never dropped.
    • Revision: per-subscription, per-stream monotonic; must-resync resets the client's high-water mark. The client drops stale or duplicate snapshots in O(1).
    • Client: patchy.tables.<t>.list.subscribe(args, onSnapshot, { onStatus, onError }) (also on get), refcounted registry with a 1 s grace window.

    Hard cases, measured (Chromium)

    Case Result
    Two browsers, two users write-start to the other browser's snapshot 40–51 ms (mean 43); commit-ack to snapshot 31 ms
    Write racing subscription setup, 10 rounds 0 stale snapshots after up-to-date; 1 round where the wake landed after up-to-date (the model working)
    Second viewer, different authority each viewer gets only their own filtered result; identity comes from the stream's admission. Tier 1 table reads carry no per-viewer authority, so only viewer-dependent args differ today
    Revoked mid-subscription deactivation stops the stream with access_denied, 0 leaks; a 3 s session stops with session_expired 121 ms after the next write
    Stream dropped and reconnected resumed in 860 ms with must-resync then a fresh snapshot, 0 duplicates; a 10 s offline window delivered the missed write exactly once
    Burst 50 writes → 4 re-runs, 4 deliveries; 200 writes in 1.55 s → 21 re-runs, 17 deliveries, final value correct
    Fan-out, 30 documents × 5 subscriptions, one write 150 re-runs (2 transient retries), 150 deliveries, all within 510 ms, company-database connections peaked at 4
    HTTP/1.1 the seventh document in one browser context never loads while six streams hold the pool
    postgres.* subscription refuses with invalid_request and a plain message

    Where the model creaked (builder)

    1. HTTP/1.1 does not just stall extra tabs: six held streams block the seventh page load. Production ingress must terminate HTTP/2, and the broker should suspend its stream when the document is hidden.
    2. Fan-out produced busy from the company pool; without a concurrency ceiling and transient retry the subscription silently died. The ceiling belongs in the design, not only the per-minute limit.
    3. Continuity is never provable with in-memory state, so must-resync is sent on every resume followed by full snapshots. Durable per-table revisions would let the server skip the re-run when nothing changed.
    4. One frame per subscription snapshot; a write touching one table yields N frames for N subscriptions. There is no batch boundary.
    5. Session expiry is detected at the next re-run only; an idle stream with an expired session stays open until then.
    6. A subscribed list without limit is a window of 100, not the table.
    7. Shared-table subscriptions refused in the prototype (the key needs the owning patch's table from the manifest); straightforward, not done.

    What a fresh agent must understand (builder's draft)

    1. A subscription is your read, re-run as you: same args, same authority, same page window. Render the whole result every time; never merge snapshots.
    2. Only the tables the read names wake it. A read over a company Postgres connection does not update; subscribe to the table, not the derivation.
    3. The stream can end: handle stopped (authority gone; the shell takes over) and resyncing (keep showing data, a fresh snapshot follows). Unsubscribe on unmount; remounts within 1 s reuse the live subscription.

    Astra's evaluation (omp, --thinking xhigh, no tools; brief = decided context + builder's report + core diff)

    Verdict: sound architecture, incomplete tier 2 proof. Re-running authorised reads, replacing results and coalescing invalidations remain the right model. Its calls, condensed:

    1. One change before spec: commit-coupled durable resource revisions plus reconciliation are a correctness requirement, not a reconnect optimisation. The research already said so; the in-memory substitute is a substantive deviation. One refusal: an apparently live subscription that silently stops updating. In the broker a lost subscription-add POST leaves the subscription desired but not admitted while the SSE connection stays healthy, and recovery depends on a disconnect that need never happen. Desired and admitted sets must converge independently of reconnects. The authority case proves viewer binding and viewer-dependent args, not server-enforced differentiated access; that tier 2 acceptance case is still unproven.
    2. Transport survives. Browser WebSockets cannot carry arbitrary handshake headers either, so fetch-streamed SSE it is. The spec must require verified browser-to-ingress HTTP/2 (the backend hop may stay HTTP/1.1), gated on seven visible documents loading and updating, not on an ingress flag. Hidden documents: suspend after a documented grace, keep data as stale, re-admit and full-resync on return. Suspension does not rescue seven visible documents on HTTP/1.1.
    3. Full resnapshot on resume is acceptable (a query subscription is not an event log; intermediate values may vanish). The remaining hole is commit-to-notification while the stream survives: the hook follows the log record and the revision is memory-only, with no durable evidence or reconciliation path for an interrupted notification. Also: up-to-date is emitted right after the first snapshot regardless of queued wakes, so the promised fence is not established in code; define the marker against a captured commit watermark. And hello.epoch has no consumer, so it is not currently a guard. Equal table revisions alone cannot justify skipping re-admission on a viewer-dependent query.
    4. Right ingredients, wrong isolation boundary. The 3000/min bucket is viewer × patch, so many viewers multiply one patch's pressure. Put aggregate concurrency and work budgets at the company database boundary with fair per-patch scheduling and reserved capacity for interactive calls; keep a process ceiling as the last bound. Bound admitted subscriptions and buffered output too. Sixteen and 3000 are prototype settings, not capacity limits.
    5. Tearing is real and accepted for v1. A count can reflect a commit before its list does. Rendering both together would not make the reads consistent; where a screen needs an invariant, return the related values from one query whose underlying read provides it. Say plainly in the contract that an SSE frame is one subscription update, not a render boundary.
    6. Tier 3 and replicas. Any separately authorised writer of Patchy-owned data must emit the same keys; browser subscribers still re-run as their viewers; the non-null ctx.viewer cannot simply be reused for viewerless execution. Across replicas the read-and-replace semantics, dispatch authorisation, client registry and SSE survive; the process-local bus does not. NOTIFY needs a dedicated listener outside transaction pooling, durable revisions repair missed notifications, add/remove requests must reach the stream's owning replica, and company budgets must span replicas.
    7. The three facts: keep, correct the second, add a fourth. Teach patchy.server.<module>.<query>.subscribe and useQuery, not primitive table subscriptions. A client-side derivation does update when recomputed from subscribed inputs; the real rule is that a handler's dependency coverage conservatively includes every resource it declares, with shared aliases resolved to the owner's key. Lifecycle as drafted, but specify idle session-expiry rather than imply immediate detection. Fourth: scope of freshness: a list is a paginated window, subscriptions are independent, and coalescing does not deliver every intermediate write.

    I verified astra's three code claims against the branch: the swallowed add on a lost POST, the up-to-date emitted before a queued wake drains, and the unused epoch are all as described. None invalidates the measurements; all three are fence and reconciliation gaps the spec must name.

    My read

    The model holds. Nothing measured contradicts the research; the two-browser loop is 40 ms end to end and the burst, revocation and reconnect cases behave as the model predicts. What the prototype adds to the research is a list of fences the paper model did not have, and they should ride to the reactive queries ticket as decided inputs rather than open questions:

    • Durable per-table revisions coupled to the commit, with the client sending its last tableRevision and the server answering up-to-date without a re-run when equal, are v1, not the upgrade path. Astra and the research agree; the prototype's in-memory bus is why every resume is a full resync.
    • up-to-date is a fence against a commit watermark captured before the read, not "after the first snapshot".
    • Desired and admitted subscription sets reconcile on a timer or on every stream frame, so a lost add cannot leave a dead-but-live subscription.
    • The re-run budget sits at the company database with fair per-patch scheduling; the viewer bucket stays for interactive calls.
    • Ingress terminates HTTP/2, proven by a seven-document check in the browser suite; hidden documents suspend after a grace and full-resync on return.
    • The contract's SSE frame is one subscription update. Per-subscription tearing is stated; a screen that needs an invariant asks one query for it.
    • Skill facts: astra's four, with the second corrected to "your query's declared resources, shared aliases resolved to their owner".

    Astra's point that server-enforced differentiated access is unproven is right and cannot be proven on tier 1 tables, which carry no per-viewer authority. It moves to the reference CRM prototype, where a tier 2 query filters by ctx.viewer.

    For Allison

    The ticket's question is whether the model feels right from the builder's chair. The prototype and both evaluations say yes with the fences above. Your verdict closes it; three calls are yours:

    1. Durable revisions in v1 (my recommendation and astra's) versus the research's "in-process now, durable when replicas exceed one". Durable-now costs one table-revision write per mutation inside the same transaction; it buys resume without full re-run and survives a restart. I recommend v1.
    2. Company-database re-run budget with fair per-patch scheduling versus the prototype's per-process semaphore plus viewer bucket. The fair scheduler is more machinery; the alternative is a per-company semaphore and a per-patch cap, which is one map lookup. I recommend the simpler per-company semaphore plus per-patch cap for v1 and name the scheduler as the escalation.
    3. Hidden-document suspension in v1 or deferred. It is a few lines in the broker and it halves the connection pressure in practice. I recommend v1.

    Prototype built by Claude Fable 5.1 via Claude Code (subagent); evaluation brief, verification and this comment by Claude Fable 5.1 via Claude Code, astra as the design pair, 2026-09-22.

  3. allisonmahmood commented on Sep 22, 2026

    @allisonmahmood
    OwnerAuthor

    Resolution

    Allison's verdict on 2026-09-22: the model holds, and the three recommendations above stand as decided. Astra's evaluation is recorded in the comment above; its "sound architecture, incomplete tier 2 proof" is accepted, with the incomplete part (server-enforced differentiated access) moved to the reference CRM.

    Decided here

    1. Durable per-table revisions are v1. One revision write per touched table inside the mutation's own transaction; the client sends its last tableRevision on resume and the server answers up-to-date without a re-run when equal, after re-admission. The in-memory bus is the prototype's shortcut, not the design.
    2. The re-run budget is a per-company semaphore plus a per-patch cap, with the viewer bucket kept for interactive calls. Fair per-patch scheduling is the named escalation if one patch is seen starving a company's others.
    3. Hidden documents suspend their stream after a short grace, keep data as stale, and re-admit with a full resync on return.

    Fences the prototype found, carried to the reactive queries ticket as inputs

    • up-to-date is a fence against a commit watermark captured before the read, never "after the first snapshot".
    • Desired and admitted subscription sets reconcile independently of reconnects, so a lost add cannot leave a dead-but-live subscription.
    • Ingress terminates HTTP/2, proven by a seven-document check in the browser suite; the backend hop may stay HTTP/1.1.
    • The transport is fetch-streamed SSE with the broker's own reconnect; native EventSource and browser WebSockets cannot carry the admission headers.
    • The SSE frame is one subscription update. Per-subscription tearing is stated in the spec; a screen that needs an invariant asks one query for it.
    • Idle session expiry is detected on a timer, not only at the next re-run.
    • A subscribed list without limit is a window, not the table; the skill says so.
    • Shared-table subscriptions key on the owner's table, resolved from the manifest.

    Skill facts for a subscribed screen (astra's four, second corrected): a subscription is your query re-run as you, render the whole result each time; a query's dependencies are its declared resources with shared aliases resolved to their owner; the stream can end, keep data through a resync and stop on authority loss; freshness is scoped: a list is a page, subscriptions are independent, coalescing skips intermediate writes.

    Handed on: the authority case (a tier 2 query filtering by ctx.viewer, two viewers seeing different rows) to the reference CRM prototype; everything above to the reactive queries ticket. The prototype stays on PR #343, never merged.

    Resolved by Claude Fable 5.1 via Claude Code with Allison, astra as the design pair, 2026-09-22.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

wayfinder:prototype

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions