Skip to content

perf(computers): list linked threads without decoding snapshots - #400

Merged
nixuuu merged 1 commit into
devfrom
fix/linked-incident-386-mirror
Nov 9, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/linked-incident-386-mirror

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Linked thread lists read and protobuf-decoded every complete mirrored history to obtain the small ui.Thread row. Lists and header reads now use the existing atomic metadata projection, with a backfill that makes it mandatory. Healthy aggregate lists use the bounded live-read cache; the mirror remains the loading/offline/failure fallback.

Evidence

  • The home log repeatedly executes SELECT t.snapshot ... computer_mirror_threads ... ORDER BY t.thread_id, followed by connection resets/broken pipes. The supplied client's PostgreSQL log has no matching statement: the expensive direction is the home listing the client's mirrored threads.
  • Call path: sidebar/overview ListThreads → gather → forward → ThreadMirror.threads(). Qualified project lists use the metadata mirror directly. Web and mobile reload on reconnect and linked-read completion; no independent fixed sidebar polling timer was found. Live results refresh after 5 s, reads have a 10 s budget, failed refreshes cool down for 30 s.
  • No SQL read/query deadline is configured on this path. The SQL driver pinned in nightly.108 (4.1.1) rejects backend messages above 16 MiB and fatally closes the socket. The integration test reproduces its parser failure with a 17 MiB snapshot row while metadata listing succeeds. This is consistent with the observed resets; the historical row sizes and client-side SQL errors are unavailable, so their exact cause remains unproven. Synchronous full-history decodes also add event-loop pressure.

Cost

Path Before After How measured
Mirror list, 100 threads × 3 MiB 314,583,794 bytes, 378 ms 9,294 bytes, 4 ms Real PostgreSQL integration fixture, query plus protobuf decode; representative run
Healthy aggregate linked list Re-read the mirror for every call Bounded cached live result; no mirror call Linked-gateway regression test

Migration 0097 extracts the protobuf header inside PostgreSQL, handles reordered fields, then sets thread_metadata NOT NULL. Existing writes already update metadata and snapshot in one transaction. Owner/project/archive/sidebar filtering remains enforced. Cache bounds remain 128 keys/16 MiB and four active reads per peer. Slow metadata lists log duration, count and bytes above 250 ms, without content or hosts.

Validation

Focused metadata/backfill/oversized-row and healthy-cache tests pass. Top-of-stack validation passed: bun install, bun run gen:check, bun run typecheck, bun run lint, bun run format:check, bun run check:tmp, and the web production build. The full test run finished with 1,904 passed, 161 skipped, 0 failed across 339 files (982.19 s), with nothing left in the private disk-backed temp directory. Multi-gateway files ran sequentially. All three stack heads have green CI; the stack is ready for review and has not been merged.

Copy audit §8: no UI text changes.

Fixes: #348
Related: #27
Related: #386

@nixuuu
nixuuu added this pull request to stack #403 November 9, 2026 12:57
@nixuuu
nixuuu marked this pull request as ready for review November 9, 2026 13:32
@nixuuu
nixuuu merged commit 53be952 into dev Nov 9, 2026
13 checks passed
@nixuuu
nixuuu deleted the fix/linked-incident-386-mirror branch November 9, 2026 13:36
nixuuu added a commit that referenced this pull request Nov 9, 2026
Adds an opt-in synthetic PostgreSQL 18 benchmark for gateway stores, an
SQL inventory, sanitized EXPLAIN diagnostics and Polish usage
documentation. It reuses production Effect SQL services without enabling
tracing in the application.

The harness owns its Docker container and private data directory, caps
resources, never accepts an existing database URL and removes its
dataset afterwards. Latency uses the normal pool; a separate pass counts
statements, returned rows and decoded JSON bytes without emitting SQL
values.

## Baseline and measurement

The baseline was remeasured on **dev
c9b57c4**, including #400–#402. This
layer adds measurement only. Earlier measurements against pre-incident
dev are superseded and are not used for this stack's comparisons.

Command: `bun scripts/bench/db.ts --run --explain`. PostgreSQL 18.6, 240
threads, 24 projects, 13 workers, 32 turns per ordinary thread, 2,048 in
the long thread, 4,096-byte texts, 64 background tasks, attachment
metadata, bots/history, schedules and one linked mirror. Two warmups, 20
serial samples, nearest-rank p95; approximately 140 MB of storage.

| Operation | Queries before → baseline | p95 ms before → baseline |
Returned rows before → baseline | Decoded JSON bytes before → baseline |
|---|---:|---:|---:|---:|
| Projects | — → 8 | — → 3.0 | — → 89 | — → 15,709 |
| Sidebar threads | — → 1 | — → 12.8 | — → 240 | — → 847,006 |
| Paged thread open | — → 10 | — → 29.8 | — → 107 | — → 135,392 |
| Title search | — → 1 | — → 1,069.9 | — → 240 | — → 844,938 |
| Import admission (100 items) | — → 111 | — → 27.5 | — → 0 | — → 222 |
| Mirror list | — → 1 | — → 0.19 | — → 1 | — → 546 |

The compact mirror list, bounded turn window, projected UI metadata,
indexed activity and scratch workspace reconciliation already belong to
current dev. This stack does not claim those improvements.

Counts include transaction controls. Rows/bytes are returned to
JavaScript, not all scanned rows, wire bytes or physical I/O. Empty
result arrays contribute two JSON bytes each. EXPLAIN nodes expose
rows/loops and shared/temp buffers; pg_stat_statements supplies server
counters. Shared-host load varies; these timings are observations, not
SLOs.

## Coverage and validation

Seventeen operations cover project/thread lists, full and paged opens,
queue/steer, mark seen, title search, tasks, bot history, updates,
mirrors and import admission/read. These are store operations, not full
RPC benchmarks. Update fixtures currently return no update rows, and the
mirror fixture has one mirror. The inventory finds 2,095
statement/fragment locations including migrations; this is not a
completed manual audit of every SQL statement.

Default baseline, intermediate layers and top benchmarks completed with
EXPLAIN; owned containers/datasets are removed. Benchmark output and
logs are not committed. All required top-branch checks passed: bun
install, gen:check, typecheck, lint, format:check, foreground check:tmp
and the web build. The full run passed 1,914 tests, skipped 161
opt-in/platform tests and failed none across 342 files; check:tmp
reported nothing left in its temp directory. Focused current-dev checks
also passed. Full validation details are in #407.

Next coverage should add concurrent mixed load, populated update
fixtures, many large mirrors, side-thread previews and attachment/import
payload scaling. No UI text changed; copy audit does not apply. Keep the
entire stack as drafts.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Fresh import admission and library rows use typed JSON batches instead
of one INSERT per item. Each batch targets at most 128 records or
approximately 512 KiB; one already-validated large record may exceed the
byte target. Bigint byte counts remain exact decimal strings.

All batches share the existing run lock and transaction. Append imports
retain their per-thread validation/locking path. This stack is based on
**dev c9b57c4** and preserves
#400–#402. Project reconciliation, history-ID pagination, activity
indexing and mirror metadata listing are inherited from dev, with no
duplicate implementations here. The new index migration is **0100**
after dev's 0097–0099.

## Measurement

Before: read layer (#406). After: this stack's top. `bun
scripts/bench/db.ts --run --explain`, PostgreSQL 18.6, identical
synthetic 240-thread/2,048-turn/4,096-byte dataset, two warmups, 20
serial samples, nearest-rank p95. All stack layers were remeasured after
the incident stack merged; old pre-incident comparisons are superseded.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| Import admission (100 items) | 111 → 12 | 20.5 → 22.0 | 0 → 0 | 222 →
24 |
| Import reads | 2 → 2 | 9.8 → 35.2 | 2,323 → 2,323 | 704,170 → 704,170
|

Import admission p50 was 16.7/8.2 ms. The slower read sample is
explicitly retained: its SQL, rows, decoded bytes and shared-block
counts are unchanged. A separate `--operation imports` repeat gave
admission p50/p95 7.5/8.9 ms and read p50/p95 8.5/10.1 ms, with the same
query/row/byte counts. Read server execution was 7.71 ms before, 18.90
in the full after run, and 7.94 in the repeat. Latency remains noisy
under shared-host load; the repeat does not replace the table, and no
stable read-latency improvement is claimed. Query reduction is the
stronger evidence.

Counts include transaction controls. Bytes are decoded returned JSON,
not bytes written, wire traffic or disk I/O; empty arrays contribute two
bytes per query. This is a store-level benchmark, not a production
RPC/event-loop SLO.

Compared with current dev c9b57c4, the complete stack changes
title-search p95 from 1,069.9 to 91.2 ms and decoded bytes from 844,938
to 98,080; paged-open p95 is 29.8/22.5 ms with 107 rows on both sides;
repeated mark seen is 2/1 statements. Projects remain 8 statements and
mirror lists remain 546 metadata bytes: those improvements already
belong to the incident stack.

## Validation

- Import tests passed: 300 items and 300 library rows survive restart
with order, owner, JSON and bigint >2^53 intact; a late-batch conflict
rolls back the run and every earlier batch (2 tests, 904 assertions).
- Current-dev focused schema/index/upgrade, history, mentions,
read-marker and #401 read-cost suites passed sequentially. No
multi-gateway test files ran concurrently.
- All required current-dev top-branch checks passed: bun install, bun
run gen:check, bun run typecheck, bun run lint, bun run format:check,
foreground bun run check:tmp and the web build. The full run passed
1,914 tests, skipped 161 opt-in/platform tests and failed none across
342 files (22,862 assertions, 984 seconds). check:tmp reported nothing
left in its temp directory. After the checks, a single blank-line lint
correction was folded into the index layer and descendants were rebased;
no runtime code changed. Lint and formatting passed with that
correction, and the working tree is clean.

## Remaining database work

The 2,095-location static inventory is not a completed manual audit of
every SQL statement. Next work should finish cold/admin/query-generator
coverage, expand update/mirror/side-thread fixtures, measure concurrent
desktop/server load and pool/timeouts, and quantify JSONB/bytea/write
amplification. Prepared statements remain enabled (100 per connection;
pool default 10).

Concrete candidates are repeated progress aggregates in
`imports/store.ts`, unbounded pending-command decoding in
`store/outbox.ts`, and workspace preparation awaited while a schedule
transaction holds its row lock in `store/bus-schedules.ts`. Preserve
import totals, command ordering and schedule fencing when changing them.
Safe pruning needs durable watermarks/tombstones and restart tests; no
age-based deletion is introduced. Large index builds require a
maintenance window, and large legacy snapshots/restored windows remain a
limitation.

Polish docs describe harness usage, indexes, import batching and
retention constraints. No UI text changed; copy audit does not apply.
Keep all four PRs as drafts.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Adds opt-in channel counters and a repeatable two-gateway restart
scenario, with no payload, identifier or secret retention. Disabled
metrics do no CPU sampling or extra instrumentation serialization.
Polish docs describe the measurement boundaries. Later stack layers
extend the workload and add isolated-process CPU profiling.

### Measurement

Measurement baseline: `dev` **4dfb2f85** (#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 **04a871be**;
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 added a commit that referenced this pull request Nov 9, 2026
)

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` **4dfb2f85** (#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 **04a871be**;
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 added a commit that referenced this pull request Nov 9, 2026
)

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` **4dfb2f85** (#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 **04a871be**;
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.
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