Skip to content

perf(threads): sync linked history with journal deltas - #265

Merged
nixuuu merged 1 commit into
perf/remote-thread-open-1from
perf/remote-thread-open-2
Nov 6, 2026
Merged

nixuuu merged 1 commit into
perf/remote-thread-open-1from
perf/remote-thread-open-2

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Opening or reconnecting to a mirrored linked thread now reuses its existing owner journal cursor. An eligible caught-up home sends metadata instead of all old tool output. The background mirror publisher uses the same delta selection, so eligible active threads also avoid full snapshots on every invalidation.

Protocol and correctness

Both peers must advertise thread_mirror_delta. WatchThreadRequest.mirror_cursor selects changed item/turn keys and notice seqs from the existing commit-ordered journal in a repeatable-read transaction. The response contains current upserts, tombstones and replacement metadata. The partner merges it into the matching mirror, then emits a normal UI snapshot followed by native live events. No second journal or cursor is introduced.

Background deltas use start/fragments/end frames and the existing predecessor/checkpoint protocol. Incomplete deltas never replace durable history. A per-subscription token fences overlapping reconnects before either checkpoints. Header preflights read a small stored thread header instead of decoding the entire mirror. Migration 0088 adds journal keys, the optional header and the subscription token, following dev's 0086/0087 worktree migrations; applied migrations are untouched.

Full snapshots remain the fallback for journal gaps, another/future epoch or cursor, pre-migration invalidations, fork-boundary/inherited-history changes and missing bases. Older homes and older partners negotiate the original full-snapshot protocol. All protobuf changes are additive; link protocol numbers remain unchanged. Relayed routes and threads carrying moved history conservatively retain full snapshots. Turns with mutable source joins (agent bus, questions, schedules, bots or background tasks) also retain full snapshots: their own turn key cannot describe changes in those joined records. This preserves correctness while further dependency tracking remains outside this stack. Mirrors remain owner-scoped and exclude secrets, schedules, provider configuration and credentials.

Outbox changes with a turn ID invalidate that turn, including the dispatch transition before any worker event. The delta item lookup preserves the additive message completion timestamp introduced concurrently on dev, so reopened work segments keep their timing.

Before/after measurements

Same fixture as #264: two real linked gateways, 500 turns, 3,549 items with long tool output, real BFF/browser. Before: 7,152,330-byte home response, 45.9–50.2 ms warm construction, 53.3–83.1 ms application-level link leg. The quiet implementation run produced 379–381-byte caught-up deltas, 6.45–11.01 ms warm construction, and 0.22–0.43 ms home-yield → decoded partner delivery. The outbox/source-guard recheck on dev 987b6b4f produced 381-byte deltas, 8.07–26.16 ms construction during ordinary warm opens, and 0.31–1.01 ms link delivery. A later held-home run reached 42.34 ms construction (excluding the deliberate hold). Payload reduction remains 99.9947%; framing/TLS bytes are excluded. The link interval includes protobuf encoding, transport chunks, reassembly and decoding, not just wire RTT.

Browser/BFF boundary Before Quiet implementation run Recheck on dev 987b6b4f
Warm linked first content, three opens 434.8 / 448.8 / 453.9 ms 357.9 / 387.0 / 471.3 ms 687.1 / 542.1 / 624.1 ms
Warm local control, three opens 384.5 / 396.3 / 397.8 ms 367.6 / 396.7 / 410.2 ms 653.7 / 484.5 / 473.7 ms
Linked SSE stream created → first message 260.6–268.8 ms 189.9–243.9 ms 339.9–387.7 ms
Linked first message → two animation frames 121.9–128.9 ms 131.8–159.6 ms 132.7–255.8 ms
BFF JSON conversion + stringify + UTF-8 enqueue not fully instrumented mirror 18.4–32.6 ms; live handoff 17.6–28.7 ms BFF implementation unchanged; instrumentation removed

The linked first-content medians were 448.8 ms before, 387.0 ms in the quiet implementation run, and 624.1 ms in the final recheck; local controls were 396.3, 396.7 and 484.5 ms. The final loopback sample is slower, so these shared-host samples do not demonstrate a reliable browser latency win. The deterministic improvement is eliminating history-sized work on the computer link and displaying content without waiting for the home. With the home held for 2 seconds, the quiet mirror rendered at 453.8 ms and retained the visible DOM article with 0 px movement; the final recheck rendered at 762.4 ms and retained the same article with 0.22 px rounding movement. The quiet sync status disappeared without changing toolbar geometry. Final phone checks also showed mirrored content while syncing in light/dark, with no horizontal overflow.

The BFF still emits full UI snapshots, including the local handoff. Local JSON conversion, transfer and timeline preparation remain measurable; this change removes old history from the computer link. A tail-first history API is the proposed follow-up, since the existing feed already virtualizes DOM rows. It needs explicit pagination/fork/anchor semantics across clients and is not folded into this transport change.

Verification

  • Both layers on dev 4e622960: bun install, bun run gen:check, bun run typecheck, bun run lint and bun run format:check passed. Generated protobuf code is committed.
  • Top layer: web production build passed; full bun run check:tmp passed with 1471 pass, 158 skip, 0 fail, 9874 assertions across 262 files (425.75 s), and nothing left in its temp directory. Live/provider opt-in cases remain skipped.
  • Focused two-gateway delta suite: 11 pass, 83 assertions; the full run also passes the 19 mirror cases and the linked composer-shell regression. Multi-gateway files ran sequentially, without the benchmark running alongside them.
  • Browser: light/dark, desktop/narrow/phone, short/typical/long titles, held-home mirror visibility and stable article identity/position. Final self-review added outbox invalidation and the conservative joined-source fallback; those cases pass over real gateway links.

The focused 3,000-tool-item suite covers bounded open/publisher transfer, edits and deletions, stale queue/interactions/goal metadata, outbox-only dispatch changes, changing joined question metadata, message completion timestamps in publisher deltas, native live updates after handoff, restart, overlapping consumers, partial deltas, missing bases, gaps, epoch changes, and older homes/partners. The existing two-gateway suite covers fork source reconciliation, owner scoping and secret exclusion. No benchmark scripts, logs or screenshots are committed.

Updated Polish linked-computer, UI API and data-model documentation. This is the top layer of the draft stack; do not merge layers separately.

@nixuuu
nixuuu force-pushed the perf/remote-thread-open-2 branch from 6d086d8 to c38f82a Compare November 6, 2026 09:35
@nixuuu
nixuuu marked this pull request as ready for review November 6, 2026 09:39
@nixuuu
nixuuu merged commit c0676b8 into dev Nov 6, 2026
9 checks passed
@nixuuu
nixuuu deleted the perf/remote-thread-open-2 branch November 6, 2026 09:40
nixuuu added a commit that referenced this pull request Nov 6, 2026
Opening a linked thread used to wait for its entire home snapshot before
showing any content. Online reads now show the local mirror first,
display a quiet “Syncing…” status, and hand over to the home stream.
Threads absent from the mirror retain the previous route.

Unchanged turns and timeline entries retain their identity during
replacement. The status has reserved toolbar space. Composer, approvals,
queue and stop still go to the authoritative, owner-scoped home; the
mirror never authorizes an action. `ThreadUpdate.syncing` is additive
and older clients can ignore it.

### Measurements before implementation

Two real loopback gateways, separate PostgreSQL databases, pinned mTLS,
scripted workers, and a real Vite BFF/browser. The fixture contains
**500 turns and 3,549 items**, including long command output. Warm SPA
navigation was measured at 1280×800; first content means the first SSE
message followed by two animation frames.

The original baseline was recorded at `3c946cd0`. The timed recheck
includes dev's work-fold changes through `987b6b4f`; the published stack
is also rebased onto the worktree changes through `4e622960`. The top PR
records the quiet implementation sample and the timed recheck. Browser
timings are observational shared-host samples, not an isolated speedup
claim.

| Boundary | Before |
| --- | --- |
| Linked first content, three warm opens | 434.8 / 448.8 / 453.9 ms |
| Local first content, same history | 384.5 / 396.3 / 397.8 ms |
| Home snapshot construction, warm | 45.9–50.2 ms |
| Home response protobuf | 7,152,330 bytes |
| Qualified partner response protobuf | 7,221,315 bytes |
| Application-level link leg, repeated full-path run | 53.3–83.1 ms |
| BFF protobuf-to-JSON conversion, repeated run | 5.9–8.9 ms |
| Browser SSE ready → first message | linked 260.6–268.8 ms; local
192.0–208.5 ms |
| First message → two animation frames | linked 121.9–128.9 ms; local
117.6–153.2 ms |
| Linked SSE JSON | 7,856,498 bytes |

The link leg measures home yield → decoded response at the partner,
including protobuf encoding, transport chunks, reassembly and decoding;
it is not a wire-only RTT. BFF conversion excludes
JSON.stringify/UTF-8/socket work; ready-to-message includes the
remaining server/transport work. Only 12–20 virtualized articles were
mounted, so mounting the entire history was not the local bottleneck.

### This stage and the remaining cost

With the home deliberately held for **2 seconds**, the mirror appeared
in **479.2 ms** while the live response was still pending. A later
held-home browser check preserved the visible article's screen offset
(**0 px movement**) and DOM node at handoff; virtual height corrections
changed scrollTop while keeping the reading position.

Three warm loopback linked opens measured **486.1 / 505.3 / 992.9 ms**
(median 505.3 ms); local controls were **371.1 / 417.8 / 1558.3 ms**.
Shared-machine spikes were substantial. Mirror-first alone is therefore
not a demonstrated loopback speedup. It removes the dependency on the
home's response; the next stack layer removes full history transfer and
repeated full-mirror header decoding. The live handoff still carries the
same 7.15 MB home snapshot at this stage, and the first mirrored SSE
JSON is 7,856,513 bytes.

For local long threads, propose a separate tail-first history API with
an older-history cursor and stable scroll anchors. Existing DOM
windowing already works. This stack does not add partial-history
semantics across web, desktop and mobile, or trim durable mirrors.

### Verification

- Required stage gates: bun install, gen:check, typecheck, lint and
format:check passed, including after rebasing onto dev.
- Two-gateway mirror suite: 19 passing tests, including a blocked home,
live handoff, a missing mirror, owner scoping, secret exclusion, gaps,
reconnect and restart. Linked composer-shell regression: 1 passing test,
6 assertions; it waits for the authoritative handoff rather than
assuming the mirror is current.
- Real browser: light/dark and desktop/phone checks are recorded with
the completed stack; no UI test suite was added.
- Copy audit (`docs/copy.md` §8): before, the skeleton and “Connecting…”
stayed until home history arrived; after, local content is visible with
“Syncing…” until handoff. This is a neutral, temporary progress status;
reserved space avoids movement, beneath the computer badge on phones and
beside the actions on desktop. No new action or error copy. It uses text
rather than colour alone. Existing home validation and offline
explanations remain authoritative. Checked light/dark at 390, 768 and
1280 px, with short, typical and long thread titles; no horizontal
overflow or disappearing title.

Polish linked-computer documentation describes the read path. Full delta
results and the final stack verification are in #265. This is the bottom
layer of a draft stack; do not merge layers separately.
nixuuu added a commit that referenced this pull request Nov 6, 2026
Opening a UI watch can now resume from the snapshot already held by the
client. Additive `incremental` and `cursor` request fields opt into the
existing owner journal; full snapshots carry an atomic checkpoint.
Projected item/turn upserts, tombstones and replacement metadata
reconstruct the current state without transferring unchanged history.

An unknown, expired, future or other-epoch checkpoint, journal gap, fork
reset or moved history falls back to full state. Live events update the
client copy without advancing its atomic checkpoint, so reconnect
replays projected changes idempotently. Owner authorization remains in
the gateway. No migration is needed.

For remote threads, a warm UI cursor passes through to the home. A cold
UI retains local mirror-first behavior. Older clients omit the opt-in
and keep full snapshots; older gateways ignore the new fields and return
snapshots without a cursor. Linked-computer capability negotiation
remains unchanged. Related: #264, #265.

Measurements use two synthetic threads, each with 500 completed turns
and 3,001 timeline items, including roughly 1.9 KB tool outputs. The
stack's client layers measured these changes against a real gateway,
scripted worker, isolated Postgres and actual browser/Android app:

| Read | Before | After |
| --- | ---: | ---: |
| Browser first content, median of 3 switches | 300.2 ms | 110.3 ms |
| Browser initial SSE JSON payload | 6,952,035–6,952,159 B | 791–801 B |
| Android first content, median of 3 switches on Fold | 3,119.1 ms
full-watch control | 653.6 ms warm cache |
| Native protobuf update received by Android | 6,233,091–6,233,101 B |
513–523 B delta |

Browser warm content appeared before the live response. These are
development-mode measurements on shared hardware; payload figures
exclude transport/framing overhead. Client-specific Android results and
device qualification are recorded in the mobile layer.

Verification: additive proto generated with `bun run gen`; `gen:check`,
install, typecheck, lint and formatting passed on every layer.
Top-of-stack `check:tmp`: 1,490 passed, 159 skipped, zero failures; web
build and Expo lint passed. Real gateway UI integration coverage
exercises caught-up reads, upserts/deletions versus full state, old
clients, invalid/future/other-epoch cursors, gaps, restart and owner
isolation. Existing two-gateway tests also exercise warm UI reads of
remote threads. The stack stays draft and must not be merged
individually.
nixuuu added a commit that referenced this pull request Nov 9, 2026
…386)

## Change

A linked thread could remain on its last snapshot while its computer
link and BFF SSE heartbeats stayed healthy. Peer watches had no
application-level deadline. Live thread events also accepted sequence
gaps. Restarting the receiving gateway recreated these streams, but a
healthy transport alone could not repair them. Watches now validate
durable revisions, resubscribe automatically, and surface a
stale/unavailable state if recovery fails.

### Trace and evidence

- `REMOTE_THREADS` forwards a qualified thread ID through the pinned
computer link to the home's owner-scoped `WatchThread`. Each client
watch owns an independent remote call. The home subscribes to Hub before
reading its snapshot. Re-opening already creates a fresh watch; no
shared client consumer-count leak was found.
- `THREAD_MIRROR` separately maintains one background subscription per
peer. Committed snapshots/cursors live in the owner-scoped mirror
tables; staged reset generations remain invisible until commit. The
runtime's existing subscription entry could remain occupied indefinitely
by an open stream without progress. Existing mirror predecessor,
delta-base, epoch, generation and subscription fences already rejected
inconsistent updates; they lacked a deadline for missing final frames.
- Web and desktop receive the forwarded watch over the BFF's
linked-subscription HTTP/2 pool and SSE. Four BFF pools isolate
local/linked unary calls and subscriptions. SSE heartbeats prove BFF
reachability; they do not prove upstream thread freshness. The browser
cache keeps an atomic checkpoint and reopens through the gateway.
`linked-snapshot` retains aggregate linked rows and applies presence
separately; it does not deduplicate thread watches.
- #348's peer HTTP/2 PING (15-second interval, 10-second pong budget),
link heartbeats, circuit breaker and reconnect handling remain intact.
Transport loss terminates calls and reconnect resumes from committed
cursors. These checks cannot detect lost application fan-out while the
transport still responds.
- The new gateway-to-gateway tests failed before the fix for live-watch
stalls, accepted event gaps, a mirror missing its final checkpoint, and
an older peer without heartbeat recovery. Re-opening already passed.
#350 fixed an earlier Hub cleanup race consistent with the report, but
the inaccessible affected app's cause cannot be established from the
available logs. A home event-loop pause alone does not erase the durable
journal; the tests additionally suppress fan-out while changing durable
metadata.

### Recovery

- Negotiate `thread_watch_liveness`. The home sends an independent
durable revision heartbeat every 5 seconds. A changed revision
revalidates the snapshot checkpoint, using existing deltas for
incremental clients. The owner-wide revision can conservatively
revalidate another open thread too.
- Missing initial snapshots/heartbeats expire after 15 seconds. An
established live watch enters the existing syncing state and retries
once with an empty cursor. A failed repair returns a computer-scoped
unavailable error to the existing client reconnect path. Live event gaps
and invalid delta bases also force a full snapshot. Sequence checks run
before BFF text-delta coalescing, which intentionally skips sequence
numbers. Loaded history boundaries are retained.
- Mirror heartbeats must match the receiver's committed cursor and
arrive outside partial projections. A gap or 15-second stall clears the
cursor and restarts from a full generation on the next link tick (within
5 seconds). The last committed generation remains readable. A sync
failure projects the existing unreachable state; a commit or matching
checkpoint heartbeat clears it. Ordinary transport loss retains the
checkpoint for resume.
- Older peers are revalidated every 30 seconds without requiring new
frames: reopen the live read from its supported checkpoint, and refresh
the mirror generation. Only reads are retried. Bounds assume the
receiving event loop can run.
- Subscribe/end/resubscribe diagnostics use debug; unexpected stalls,
gaps, probe failures and stream failures use warn. Both sides log IDs
and safe protocol metadata only, without hosts, names, thread content,
credentials or raw errors.

All protobuf changes are additive. The frozen update protocol, worker
link compatibility, schema and mobile/web source are unchanged. The
Polish linked-computers document now describes the liveness and recovery
rules.

## Verification

- `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check`, and `bun run --filter @canopy/web build`
passed.
- New gateway-to-gateway suite: 11 passed. Covers open stalls, missing
heartbeat frames, event gaps, invalid bases, missed metadata fan-out,
re-opening with a stale mirror, lost mirror checkpoints,
unreachable/recovered status, idle reconnect confirmation, and an older
home without new frames.
- Existing mirror suites ran one file at a time: 19 durable mirror tests
and 12 incremental mirror tests passed, including restart, fencing,
owner scoping and legacy negotiation. The existing linked-list retention
test also passed in isolation after distinguishing ordinary transport
loss from application-stream failure.
- Full `bun run check:tmp --timeout 20000`: **1,865 passed, 161 skipped,
0 failed across 330 files** (982.07 seconds), with nothing left in the
test temp directory. This includes all 11 new liveness tests and the
existing linked-list retention regression. Multi-gateway files ran
sequentially.
- The preceding full attempt had one updater handover test fail with
`ENOSPC` on the shared temp filesystem (1,864 passed, 161 skipped).
Repeating the full gate with a disk-backed private `TMPDIR` passed,
including that test; no updater code was changed.
- No UI tests added. No web or mobile source changes; no browser/device
run was required. Packaged apps and the originally affected computer
were not exercised.

Copy audit: uses existing Syncing/reconnect/unreachable states and the
existing computer unavailable reason; no new frontend copy.

Related: #348
Related: #350
Related: #265
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant