Repository navigation
perf(streams): share durable revision probes across thread watches - #410
Merged
Merged
Conversation
nixuuu
force-pushed
the
perf/sync-2
branch
2 times, most recently
from
November 9, 2026 13:54
39cc351 to
35d9f62
Compare
nixuuu
marked this pull request as ready for review
November 9, 2026 15:01
nixuuu
added a commit
that referenced
this pull request
Nov 10, 2026
The native cursor-handoff test can overlap the five-second durable revision probe while its turn runs. Probe deadlines align to wall-clock intervals, so this can happen even during a short test. The gateway supervisor correctly opens a new `WatchThread` when the revision advances, but the test counted that new RPC's initial snapshot against the original subscription's native-event assertion. CI attempt 1 shows `reason: "revision"` immediately before the failure: https://github.com/itsoltech/canopy/actions/runs/42855632346/attempts/1. Observe a single home `WatchThread` over the real gateway link, wait for its initial delta against the committed mirror cursor, and then require both a completed turn and an advanced `watch_cursor`. Liveness and coalescing stay enabled. Keep the native-event assertion and the prohibition on any further snapshot or delta, including across that revision heartbeat. The existing mirror-first/UI-checkpoint tests and the separate liveness suite retain coverage of routed reads and automatic recovery. Document this distinction in `docs/linked-computers.md`. This is a test race with intentional recovery, with no production or protocol change. PR #484 fixed the separate ended-stream readiness race in this file. PR #509's bot-list cache invalidations do not enter this thread revision path; the shared probe in #410 compares durable revisions against snapshot checkpoints even when native events arrived successfully. ## Verification - Unchanged baseline: **30/30 sequential full-file runs passed**, 360 tests, zero failures or skips, with private temp cleanup passing every time. The natural flake did not reproduce locally. - Finished change: **30/30 sequential full-file runs passed**, another 360 tests, zero failures or skips, with private temp cleanup passing every time. Every native-handoff test waited for the normal revision heartbeat; no sleeps or timing overrides remain. - Controlled reproduction with a temporary 1 ms home revision probe: the original test failed at the reported no-extra-snapshot/delta assertion after `reason: "revision"`; the revised test passed with the same fast probe and liveness/coalescing enabled. The timing override was removed. - Mutation check: temporarily duplicating the home stream's initial delta made the revised test fail at the retained no-extra-snapshot/delta assertion while still receiving native events. The mutation was removed. - `bun install`, `bun run format`, `bun run typecheck`, `bun run lint`, `bun run format:check`, and `git diff --check` passed. Self-review covered the test boundary, cursor acknowledgement, native-event coverage, revision heartbeat, cancellation, and unchanged recovery behavior. No UI copy changed. All repeated file runs used `TMPDIR=/var/tmp bun run check:tmp tests/integration/thread-mirror-deltas.test.ts`, one test process at a time. Broader unfiltered tests, generation checks, and the web build were not run under the workspace's focused verification limits. Based on latest `dev` at task start, `7317c3bc6`. Related: #484 Related: #410 Related: #509
This was referenced Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Local and linked thread watches share #402's durable revision mechanism through one owner/runtime coordinator. Watches due together share a journal read. Each watch separately tracks its scanned position and relevant revision, preserving quiet-thread stability after unrelated changes and pruning already-scanned rows. Gaps, epoch changes, inherited history and external dependencies retain conservative recovery.
No parallel revision protocol or new revision capability is added. The final layer adds the unchanged-head query fast path. No schema or retention changes.
Related: #402
Layer 2 liveness test repair
CI run 42639923694 exposed timing assumptions in this layer's integration fixture, not a production protocol defect. On the original
perf/sync-2head, the file passed alone, then failed in 4/10 separate sequential runs with Bun restricted to one CPU: three event-gap failures and one transient mirror-status failure.The mirror seed arrives before the authoritative home watch is ready. The fixture now waits for a non-syncing snapshot/delta before injecting faults. The event-gap test holds revision frames until it has dropped a real event and delivered a successor, then requires a newer full snapshot and completion of the specific turn. The idle-mirror test holds recovery frames until it observes unreachable over a healthy physical link, releases them, and verifies reconnection without changing the committed cursor or generation. Stall/legacy tests wait for the actual resubscription before releasing their injected fault. The background-checkpoint test holds its fault until cursor invalidation, then waits for the new generation to commit rather than equating a current title with a completed reset.
The physical link heartbeat is separate from application liveness: its fixture interval is now 1 s, so a 400 ms transport expiry cannot preempt the 1 s application lease under full-suite scheduling pressure. Application heartbeat/expiry remain 100/1000 ms. No fixed sleeps, application timeout increases, production changes, schema changes or compatibility changes are added by this repair.
The wider gate also exposed a shell-test precondition race. The native harness probe can arrive before durable
turn_started; diagnostic reads after the failure showed a running turn but nointerruptTurncommand had been admitted. The test now waits for the gateway's durable running state before steering and pressing Stop, preserving its process-group and persisted-interruption assertions. The reproducing four-file sequence passes 35/35. Temporary diagnostic SQL/logging was removed. Stop during dispatched-but-not-yet-running admission remains a separate boundary to investigate; this repair does not change that production behavior.Layer-2 verification: the final liveness fixture passes alone (14 tests, 98 assertions) and in 10/10 separate sequential one-CPU runs before the latest dev rebase (140 tests, no temporary leftovers). The complete shard 4 then passes on the repaired layer 2: 455 pass / 44 skip / 0 fail. After rebasing onto
2ffb6f04, it passes again on176f1799: 437 pass / 41 skip / 0 fail, 478 tests across 85 files, 241.67 s, no test-owned temporary leftovers. Shard membership changes with newly inherited test files. This includes all 14 liveness tests and the shell-stop case. Earlier failed local runs were retained for diagnosis, not counted as green evidence; no unrelated timeouts were increased. Fresh CI is required on every pushed layer.Measurement
Measurement baseline:
dev4dfb2f8 (#400–407), as profiled before the later #421–425 merges. The tables compare that implementation with the completed stack, not each layer in isolation. Both variants use the identical top-branch fixture and counter definitions. Three sequential unprofiled runs per variant and fixture; no concurrent multi-gateway files. The current stack is rebased onto 04a871b; performance was not remeasured for this restack or the newly inherited dev changes.The workload streams 1500 text deltas at 20 ms intervals, tool results and background progress, with six remote views, a pinned phone client, both overviews and the production BFF transport/SSE/coalescer. It then restarts the home gateway on its existing database, changes data offline and catches up the mirror. This is a protocol fixture with scripted workers, without a browser, native phone runtime or full SvelteKit request stack.
CPU by process
Run
CANOPY_SYNC_METRICS=1 CANOPY_SYNC_PROCESSES=1 bun run check:tmp tests/integration/sync-process-performance.test.ts. Each gateway and the BFF execute in a separate Bun process. Gateway CPU includes its scripted worker. The controller, watch readers, phone client and PostgreSQL are excluded. Active CPU covers approximately 30 s; idle CPU covers a separate 10.2 s window after the turn.All active CPU totals: baseline 8.247 / 8.371 / 7.362 s; stack 7.114 / 9.381 / 6.625 s. The high stack run includes 6.431 s on the home gateway. Home median falls 4.7%, while its mean rises 6.8%; this small shared-machine sample does not establish a home CPU improvement or statistical significance. Total CPU meets the dev baseline by both median and mean. Event-loop p99 medians in ms are home 0.889 → 1.976, viewer 0.869 → 1.632, BFF 0.578 → 1.485; maximum observed home delay is 13.10 → 39.75 ms. No event-loop latency improvement is claimed.
The original combined-process fixture independently gives CPU median 6.461 → 5.926 s (−8.3%), mean 6.509 → 6.224 s (−4.4%); all samples are 6.461/6.314/6.752 → 5.262/7.484/5.926 s. It includes the controller and clients, so its totals must not be compared directly with the three-process sum.
Profiles and CPU changes
CANOPY_SYNC_PROFILE_DIRruns all three children withbun --cpu-prof --cpu-prof-md. Profiles were collected on dev, the rebased stack before CPU changes and the final stack. Interval CPU in those single profiled runs:On the home gateway, all sampled native
writeBufferedstacks lead through@effect/sql-pg; Effect/SQL execution and protobuf creation/serialization are also hot. Direct revision-coordinator samples are small. Home native-writer sample counts change 666 → 999 → 700; coalescer samples 0 → 27 → 11. These profiles include startup/teardown and locate work, rather than allocate exact activity CPU seconds. Markdown self-time includes waiting gaps and is not used as CPU evidence. The high unprofiled outlier cannot be attributed to one function from a different profiled run.The final layer removes avoidable work introduced by buffer accounting/coalescing: immutable text events reuse encoded bytes across Hub accounting, publisher accounting and linked sends; identical coalesced ranges share an owned batch; one timer serves an entire batch. Mutable snapshots/configuration messages are never cached. When the durable owner head is unchanged, the revision query skips fork-chain recursion and turn/bus dependency reads. A cheap durable clock plus authorized-thread read remains necessary for missed-fan-out and epoch recovery. No ingest batching, database maintenance or schema changes are included.
Traffic and consistency
Run
CANOPY_SYNC_METRICS=1 CANOPY_SYNC_BENCH=1 bun run check:tmp tests/integration/sync-performance.test.ts. Values below are medians of the original combined-process fixture. Count only the encode direction for traffic; linked codec CPU excludes framing/TLS and PostgreSQL. Cache lookup CPU is measured at the linked encode hook; initial queue-accounting serialization occurs outside that hook and is included in process CPU.Linked watches: 158.4 → 70.5 messages/s, 28.9 → 14.9 kB/s, −55.5% messages and −47.2% bytes. Phone: −56.0% messages, −48.8% bytes. Watch medians retain 48 heartbeats, 18 checkpoint deltas and zero full snapshots during activity; those heartbeats share 12 owner/runtime probe queries. Catch-up retains one full projection in both implementations, packed into 43 → 9 fragments. Active mirror bytes and BFF encoding CPU do not improve consistently.
The isolated-process fixture independently measures title convergence 35.61 → 35.61 ms, reconnect 3394 → 3449 ms. Its BFF SSE median bytes are 162661 → 168556; checkpoint/flush timing differs between fixtures. There is no general BFF byte or reconnect latency claim. Profiles, logs and measurement results are kept outside the repository.
Compatibility and verification
Negotiated tests cover new/new, legacy subscriber/new home, new subscriber/legacy home, and a paused subscriber overflowing while a healthy subscriber receives complete text on the same link. Resume supplies a durable delta. Local/linked liveness covers unrelated-thread activity, already-scanned pruning, retained-journal gaps, missed fan-out, sequence/base gaps, stalls, older peers and stale mirrors. Legacy capability sets simulate old peers; historic binaries are not tested.
The frozen update proto and
WORKER_LINK_PROTOCOLare unchanged. Proto additions and generated code are committed. No mobile source or native dependency changes; fingerprints were not changed or regenerated. No UI tests.All layers remain ready for review. Restacked onto dev
04a871beafter #418, #426 and the client performance stack merged; final top heade00a8f74. The only conflict was the generated UI protobuf descriptor:bun run genpreserves bothlast_user_turn_choicesand the negotiated coalescing fields. Layers 1 and 2 are unchanged by range-diff; layer 3 differs only in the regenerated descriptor.On this top head,
bun install,bun run gen:check,bun run typecheck,bun run lint,bun run format:checkand the web build pass. Focused integration runs: 69 pass, 0 fail across seven files, each run separately throughbun run check:tmpwith a private disk-backed TMPDIR and no test-owned leftovers: linked liveness 14, local liveness 1, sync negotiation/backpressure 4, composer shell 18, composer choices 4, thread mirrors 20, bounded thread reads 8. These include both previously failing liveness cases, new/legacy negotiation, stalled-subscriber isolation, durable resume and #418's composer choices. No full local suite was started for this restack, as requested; fresh CI on every layer is the merge gate. Earlier green checks and historical performance results are not evidence for these rebased heads.Copy audit: no product UI copy or controls changed; failures use existing reconnect/error flows.
Remaining measurements
Repeat the home CPU/outlier and event-loop measurements on target hardware; measure large histories and slow/lossy networks before compression or negotiated credits. Physical-device CPU, historic binary pairs and full BFF HTTP serving remain unmeasured. Update-center polling needs an invalidation feed before removal. Journal retention and staging-generation leases belong to the separate database work; this stack adds no durable retention watermark. All layers remain ready for review at the maintainer's request; merge the stack atomically only after every layer's checks pass.