Skip to content

perf(streams): share durable revision probes across thread watches - #410

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

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

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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-2 head, 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 no interruptTurn command 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 on 176f1799: 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: 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-2 branch 2 times, most recently from 39cc351 to 35d9f62 Compare November 9, 2026 13:54
@nixuuu nixuuu changed the title perf(computers): scope linked watch revisions to thread dependencies perf(streams): share durable revision probes across thread watches Nov 9, 2026
@nixuuu
nixuuu marked this pull request as ready for review November 9, 2026 15:01
@nixuuu
nixuuu merged commit 065768b into dev Nov 9, 2026
10 checks passed
@nixuuu
nixuuu deleted the perf/sync-2 branch November 9, 2026 17:43
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
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