Skip to content

perf(streams): coalesce linked deltas and bound subscriber buffers - #411

Merged
nixuuu merged 1 commit into
perf/sync-2from
perf/sync-3
Nov 9, 2026
Merged

nixuuu merged 1 commit into
perf/sync-2from
perf/sync-3

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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: dev 4dfb2f8 (#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.

Process Active CPU median s before → after Active CPU mean s before → after Idle CPU median s before → after
Home gateway 4.977 → 4.741 4.847 → 5.177 0.226 → 0.215
Viewer gateway 2.569 → 1.786 2.480 → 1.934 0.121 → 0.090
BFF 0.659 → 0.586 0.665 → 0.596 0.031 → 0.027
Sum per run 8.247 → 7.114 (−13.7%) 7.993 → 7.707 (−3.6%) 0.373 → 0.333

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_DIR runs all three children with bun --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:

Process dev s Stack before CPU changes s Final stack s
Home 5.030 5.854 5.389
Viewer 2.636 2.289 2.187
BFF 0.835 0.729 0.701
Total 8.501 8.873 8.277

On the home gateway, all sampled native writeBuffered stacks 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.

Scenario Messages before → after Bytes before → after Encode / decode CPU ms before → after Consistency ms before → after
Linked thread watches 4802 → 2139 875617 → 462443 49.703 / 60.282 → 24.867 / 31.764 36.03 → 39.58
BFF SSE 270 → 255 161904 → 152542 8.891 / n/a → 11.426 / n/a Not separately measured
Pinned phone 1583 → 696 364396 → 186690 Native codec CPU unmeasured Included in watch convergence
Active mirror 545 → 489 630964 → 636102 13.073 / 12.033 → 12.408 / 11.137 Not separately measured
Mirror restart/offline change 43 → 9 17290 → 15755 0.441 / 0.423 → 0.222 / 0.298 5056.27 → 5063.60

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_PROTOCOL are 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 04a871be after #418, #426 and the client performance stack merged; final top head e00a8f74. The only conflict was the generated UI protobuf descriptor: bun run gen preserves both last_user_turn_choices and 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:check and the web build pass. Focused integration runs: 69 pass, 0 fail across seven files, each run separately through bun run check:tmp with 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.

@nixuuu
nixuuu added this pull request to stack #412 November 9, 2026 13:09
@nixuuu
nixuuu force-pushed the perf/sync-3 branch 3 times, most recently from 08c258f to ce5a841 Compare November 9, 2026 14:58
@nixuuu
nixuuu marked this pull request as ready for review November 9, 2026 15:01
@nixuuu
nixuuu merged commit ee595e1 into dev Nov 9, 2026
10 checks passed
@nixuuu
nixuuu deleted the perf/sync-3 branch November 9, 2026 17:43
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
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