Repository navigation
perf(streams): coalesce linked deltas and bound subscriber buffers - #411
Merged
Merged
Conversation
nixuuu
force-pushed
the
perf/sync-3
branch
3 times, most recently
from
November 9, 2026 14:58
08c258f to
ce5a841
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 11, 2026
Large mirror catch-up could fill the shared link's fail-fast output queue even though the producer yielded to I/O. Overflow aborted the dialer's HTTP/2 session, failed every multiplexed call with `Unavailable`, and forced the same bootstrap through reconnect backoff. A same-version two-gateway regression reproduces this with a roughly 98 MB timeline. This matches the reported GOAWAY/code-14 loop; the original incident logs did not retain the overflow reason. RPC producers now await bounded transport capacity in both directions, with slots reserved for control frames. Cancellation and link closure release waiting writers. Large persisted mirrors and incremental-delta bases are read in 4 MiB SQL chunks, avoiding the database driver's 16 MiB result-row limit without raising it. Client and listener diagnostics record GOAWAY codes/initiators, safe failure categories and transfer byte/frame counts without addresses, tokens, content or raw debug data. This urgent compatibility fix preserves the existing wire format. The separately planned incremental protocol will replace whole-thread bootstrap projections with acknowledged sequence ranges. Thread-scoped client recovery and progress UI follow separately. Validation: - Same-version large-mirror regression: durable catch-up, complete item history, incremental update, probe isolation, unary RPC and one subscription throughout. - Gateway integration files passed serially: thread mirrors (20), mirror deltas (12), linked liveness (14), relay (10), network liveness/GOAWAY (3), plus the large-mirror regression (1). - `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run lint`, `bun run format:check`, and the web production build passed. - Full `TMPDIR=/var/tmp bun run check:tmp` passed: 2,369 tests passed, 165 skipped, zero failures; nothing left in the temp dir. - Production EAS fingerprints are unchanged on both iOS and Android (`[email protected]`). - Copy audit: no UI copy changes. Mobile/native files and dependencies are unchanged. Fixes: #411
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.
Negotiates 40 ms linked text coalescing with additive sequence ranges and retains individual events for older peers. Bounds subscriber/link/SSE queues so a stalled reader fails independently and resumes through durable checkpoints. Mirror repeated fields pack into approximately 32 KiB fragments; response producers yield to I/O during large bootstraps.
Removes repeated text encoding and per-delta timer creation, skips heavy revision work on an unchanged durable head, and adds a three-process profiling fixture. Encoding reuse is limited to immutable text events/batches; mutable configuration and snapshots stay uncached. Polish docs describe cursors, revisions, profiling and backpressure.
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.