Skip to content

fix(models): scope worker model catalogs to their owner - #426

Merged
nixuuu merged 1 commit into
devfrom
fix/model-catalog-owner
Nov 9, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/model-catalog-owner

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026

Copy link
Copy Markdown
Member

ListModels dla właściciela bez workerów przekazywał pustą listę do magazynu, która oznaczała odczyt wszystkich katalogów. Powiadomienia po zmianach modeli instancji i konfiguracji dostawców również korzystały z tego odczytu.

ModelStore.catalogs wymaga teraz właściciela i filtruje w SQL jego niezarchiwizowane workery oraz workery współdzielone. Jawna pusta lista zwraca zero katalogów; pominięta lista wybiera wszystkie dostępne temu właścicielowi. Wszystkie wywołania odczytu korzystają z właściciela z zaufanego kontekstu gatewaya, także walidacja modeli, instancje subagentów i generowanie tytułów.

Weryfikacja lokalna:

  • Testy bezpieczeństwa na PostgreSQL: 3 testy, 18 asercji. Dwóch właścicieli, jeden bez workerów; obce ID, odczyt bez filtrów, oba rodzaje powiadomień, współdzielone i zarchiwizowane workery.
  • Istniejące testy models-steer i provider-instances: 16 testów, 109 asercji. Oba przebiegi check:tmp zakończyły się bez pozostawionych katalogów tymczasowych.
  • bun run gen:check, bun run typecheck, bun run lint, bun run format:check i build apps/web przeszły. Pełny zestaw testów tej niezależnej poprawki pozostaje bramką CI.

Bez migracji ani zmian kontraktów. PR jest niezależny od stosu optymalizacji bazy danych.

Related: a10749b

@nixuuu
nixuuu merged commit f4f4a23 into dev Nov 9, 2026
9 checks passed
@nixuuu
nixuuu deleted the fix/model-catalog-owner branch November 9, 2026 17:11
nixuuu added a commit that referenced this pull request Nov 9, 2026
### Rebase verification — 2026-11-09

The five-layer stack is rebased onto `dev` at
`2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and
#421–#426. All PRs remain ready for review. The measurements below
describe the original baseline; this section records the current
integration verification.

The attachment route now passes `If-None-Match` through #421's shared
response helper. Gateway authorization/read succeeds before a 304 is
possible; qualified IDs, thumbnail fallback, bounded preview/truncation,
sanitized public failures and `no-store` errors are retained. Mobile
image caching retains public error messages and reconnect retries.
Session startup, replacement pairing, unpair and revocation retain all
four caches: transcript, bot, archived sidebar and images. The
branch/worktree panel, channel identity and sheet gesture changes remain
intact.

Passed on the rebased top branch: `bun install`, `bun run gen:check`,
full `bun run typecheck`, root `bun run lint`, `bun run format:check`
and the production web build. Final focused `check:tmp`: **27 passed, 0
failed, 334 assertions across 7 files**, no temp leftovers (images,
immutable HTTP, transcript/archive/bot caches, two-gateway linked
previews and composer choices). Coverage includes a matching old ETag
returning 404 after ownership changes and 409 while the home is
unavailable, with `no-store` and no ETag; image/archive caches are wiped
together and late callbacks cannot restore them.

EAS CLI **27.4.1**, production profile, before/after the image-cache and
preparation layers and on the final top branch: **unchanged relative to
the latest dev baseline**:

- iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e`
- Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae`

These differ from the original measurement hashes below because #424
already changed native branding/configuration on dev. This stack adds no
native dependency/configuration change. Final production Hermes exports
passed sequentially with one Metro worker: iOS **9,971,620 B**, Android
**9,961,323 B**. These include the newly merged client features; the
earlier performance comparisons below retain their original baseline.
Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict
files reports the same pre-existing `react-hooks/set-state-in-effect`
finding in `useImage.ts` on both this head and unmodified `origin/dev`;
session cleanup has no Expo ESLint findings. The required root oxlint
check passes.

No full local test run was started, as requested for the overloaded
shared machine. The earlier full-run timeout below is historical;
**GitHub CI is the current full-suite merge gate**. No native builds,
EAS builds, OTA publication or UI test suites were added. Previous
on-device profiling gaps remain.

---

Adds a repeatable Bun client CPU harness and a real-time browser
workload using the existing development renderer fixture. Pure mobile
timeline preparation can be imported without loading React Native
modules. A disposable launcher owns its PostgreSQL, gateway and BFF and
cleans them up by identity.

| Metric / capability | Before | After | Method / environment |
|---|---|---|---|
| Deterministic large snapshot | Dev renderer fixture | CLI harness:
1,000 turns, 7,099 items, 14,085,915 protobuf bytes | Bun 1.4.4, Linux
x86_64 |
| CPU measurements | Manual | Warmed median/p95 for reducer, feed,
mobile preparation, markdown and cache | `bun
scripts/bench/client-js.ts` |
| Session workload | Manual visits | Actual 30-minute run, 200 deltas
per visit at 25/s, heap/DOM/long-task samples | Chromium 156, one
1280×800 tab |
| Bundle accounting | Build output only | Deduplicated static JS/CSS
import closure, raw and gzip | `bun scripts/bench/bundle-sizes.ts` |

This is measurement tooling, not a committed UI test suite or an
optimization claim. Results belong in PR descriptions, not repository
files. The renderer fixture measures remount through two animation
frames, not cold thread navigation or browser TTI. Its handler samples
decode protobuf JSON objects and reduce them; they exclude EventSource
and string JSON parsing. The later tooling layer adds measurements over
the real network path.

Mobile fingerprints before/after extraction match on both platforms (EAS
CLI 27.4.1 production): iOS `2a0ef03a2a0fda8e7fad2e3df8609803d2edbda3`,
Android `c5c880ae8d0f5d7bc867fcbaf8f756b2ca56a07d`. Both platform
exports succeeded. Whole-stack verification is recorded on the top PR.

Polish documentation describes measurement commands, limitations,
cleanup and on-device profiling. No application UI copy changes, native
builds, secrets, screenshots or measurement result files are included.
nixuuu added a commit that referenced this pull request Nov 9, 2026
### Rebase verification — 2026-11-09

The five-layer stack is rebased onto `dev` at
`2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and
#421–#426. All PRs remain ready for review. The measurements below
describe the original baseline; this section records the current
integration verification.

The attachment route now passes `If-None-Match` through #421's shared
response helper. Gateway authorization/read succeeds before a 304 is
possible; qualified IDs, thumbnail fallback, bounded preview/truncation,
sanitized public failures and `no-store` errors are retained. Mobile
image caching retains public error messages and reconnect retries.
Session startup, replacement pairing, unpair and revocation retain all
four caches: transcript, bot, archived sidebar and images. The
branch/worktree panel, channel identity and sheet gesture changes remain
intact.

Passed on the rebased top branch: `bun install`, `bun run gen:check`,
full `bun run typecheck`, root `bun run lint`, `bun run format:check`
and the production web build. Final focused `check:tmp`: **27 passed, 0
failed, 334 assertions across 7 files**, no temp leftovers (images,
immutable HTTP, transcript/archive/bot caches, two-gateway linked
previews and composer choices). Coverage includes a matching old ETag
returning 404 after ownership changes and 409 while the home is
unavailable, with `no-store` and no ETag; image/archive caches are wiped
together and late callbacks cannot restore them.

EAS CLI **27.4.1**, production profile, before/after the image-cache and
preparation layers and on the final top branch: **unchanged relative to
the latest dev baseline**:

- iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e`
- Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae`

These differ from the original measurement hashes below because #424
already changed native branding/configuration on dev. This stack adds no
native dependency/configuration change. Final production Hermes exports
passed sequentially with one Metro worker: iOS **9,971,620 B**, Android
**9,961,323 B**. These include the newly merged client features; the
earlier performance comparisons below retain their original baseline.
Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict
files reports the same pre-existing `react-hooks/set-state-in-effect`
finding in `useImage.ts` on both this head and unmodified `origin/dev`;
session cleanup has no Expo ESLint findings. The required root oxlint
check passes.

No full local test run was started, as requested for the overloaded
shared machine. The earlier full-run timeout below is historical;
**GitHub CI is the current full-suite merge gate**. No native builds,
EAS builds, OTA publication or UI test suites were added. Previous
on-device profiling gaps remain.

---

Obrazy mobilne są pobierane dopiero po wejściu do widocznego okna osi
czasu. Powrót do historii lub otwarcie viewerów korzysta z prywatnych,
niezmiennych plików zamiast ponownego RPC i base64.

Cache rozdziela parowania (owner-bound device id + pin), pełne
kwalifikowane identyfikatory komputerów i rzeczywiste warianty
thumbnail/full. Blob lub załącznik bez miniatury dzieli pełny wariant
pomiędzy listą i viewerem, bez powtórnego odczytu. Pliki i katalogi mają
nazwy SHA256; limit dysku to 200 MiB / 2048 wpisów, indeks URI w pamięci
ma budżet 24 MiB ważony bajtami obrazu. To nie ogranicza natywnych
bitmap. Wspólne żądania są anulowane po odejściu ostatniego odbiorcy.
Forget, revocation i ponowne parowanie zamykają cache i usuwają pliki;
spóźniona odpowiedź nie odtwarza danych. Brak nowych modułów natywnych
lub uprawnień galerii.

Załączniki w listach i wysłane chipy używają miniatur; viewer pełnego
wariantu. GetThreadBlob nie udostępnia miniatur: jego podglądy nadal
używają obrazu źródłowego. BFF zachowuje private/immutable, dodaje ETag
SHA256 reprezentacji i 304 po autoryzacji; błędy API mają no-store.
Istniejące loading="lazy" i odrębne URL ?thumbnail/?preview pozostają
zachowane. Zmiana nie ingeruje w routing linked previews 409.

| Metryka | Przed | Po | Metoda / środowisko |
|---|---:|---:|---|
| Żądania: 20 miniatur, dwa przejścia + ponowne otwarcie | 60 | 20 | bun
scripts/bench/image-cache.ts, Bun 1.4.4 Linux; symulowane montowania,
rzeczywisty HTTP + filesystem |
| Bajty odpowiedzi | 983 040 | 327 680 | 20 deterministycznych miniatur
po 16 KiB, ten sam scenariusz |
| Restart cache / ponowne otwarcie, to samo parowanie | 20 / 327 680 B |
0 / 0 B | nowa instancja cache, zachowany prywatny dysk |
| Fingerprint iOS | 2a0ef03a2a0fda8e7fad2e3df8609803d2edbda3 |
identyczny | eas-cli 27.4.1, production, przed/po |
| Fingerprint Android | c5c880ae8d0f5d7bc867fcbaf8f756b2ca56a07d |
identyczny | eas-cli 27.4.1, production, przed/po |
| Bundle Hermes iOS, cały stos względem pierwotnego dev | 9 900 217 B |
9 927 705 B | expo export, produkcyjny JS/assets, bez builda natywnego |
| Bundle Hermes Android, cały stos względem pierwotnego dev | 9 889 662
B | 9 917 398 B | expo export, produkcyjny JS/assets, bez builda
natywnego |

Rzeczywista przeglądarka Chromium 156, produkcyjny BFF + gateway,
prywatny seed 1000 tur / 500 wątków, 1280×800: 20 PNG 256×256 w dwóch
wiadomościach. Pierwsze przejście pobrało 20 miniatur / 803 816 B treści
(809 816 B Resource Timing transferSize). Drugie przejście: 0 żądań
sieciowych / 0 B; ponowne otwarcie: 0 / 0 B, 20 wpisów z cache. Web już
miał private/immutable, więc nie przypisujemy tej zmianie oszczędności
ponownego transferu w web. To pomiar po zmianie; historycznego before w
browserze dla obrazów nie zarejestrowano. Seed tego przebiegu miał
ręcznie uzupełniony katalog załączników workera; narzędzie w #415 teraz
zgłasza go przy hello.

Browser potwierdził: loading="lazy", ?thumbnail, różne ETag dla
thumbnail/full/preview, 304 z poprawnym If-None-Match i 404 z no-store
bez ETag. Sprawdzono telefon 390×844 w dark i desktop 1280×800 w light;
bez poziomego overflow, obrazy poprawnie zdekodowane. Serwery i browser
zamknięte przed pełnymi testami.

Weryfikacja: install, gen:check, pełny typecheck, root lint,
format:check, web build i eksporty Expo obu platform przeszły. Expo
Doctor: 20/20 kontroli. Końcowe 5 testów cache/HTTP (39 asercji)
obejmuje izolację, restart, LRU, brak pliku po usunięciu przez OS,
retry, współbieżność, ponowne użycie pełnego wariantu i wipe przy późnej
odpowiedzi; przeszły również w pełnym przebiegu. Dodatkowy Expo ESLint
dla zmienionych plików wskazuje istniejące już set-state-in-effect w
useImage; nowe wskazania refs zostały poprawione i sprawdzone ponownie.

Pierwotny końcowy pełny check:tmp zakończył się 1919 pass / 161 skip / 1
fail, 22 240 asercji, 1050.58 s, bez pozostałości temp. Pozostał
niezmieniany test composer-shell „Stop during a shell steer kills its
group and persists the failed delivery” — anulowanie RPC po 10 s.
Wcześniejszy przebieg miał też błędy ask-user i thread-mirror-deltas;
wszystkie trzy pliki przeszły następnie osobno razem (42 pass / 0 fail,
226 asercji, 38.70 s). Nie zmieniano timeoutów ani asercji. W pierwotnym
przekazaniu pełna bramka pozostawała nierozstrzygnięta, a stos był
draftem.

Harness nie mierzy renderera React Native ani RPC. Na urządzeniu
pozostają: widoczność wewnątrz wysokiej tury, szybki scroll/anulowanie,
bitmapy i filesystem Expo, viewer/restart/unpair/revocation; instrukcje
w docs/client-performance.md. Brak buildów natywnych, EAS i publikacji
OTA. Copy audit: bez nowych tekstów UI.
nixuuu added a commit that referenced this pull request Nov 9, 2026
### Rebase verification — 2026-11-09

The five-layer stack is rebased onto `dev` at
`2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and
#421–#426. All PRs remain ready for review. The measurements below
describe the original baseline; this section records the current
integration verification.

The attachment route now passes `If-None-Match` through #421's shared
response helper. Gateway authorization/read succeeds before a 304 is
possible; qualified IDs, thumbnail fallback, bounded preview/truncation,
sanitized public failures and `no-store` errors are retained. Mobile
image caching retains public error messages and reconnect retries.
Session startup, replacement pairing, unpair and revocation retain all
four caches: transcript, bot, archived sidebar and images. The
branch/worktree panel, channel identity and sheet gesture changes remain
intact.

Passed on the rebased top branch: `bun install`, `bun run gen:check`,
full `bun run typecheck`, root `bun run lint`, `bun run format:check`
and the production web build. Final focused `check:tmp`: **27 passed, 0
failed, 334 assertions across 7 files**, no temp leftovers (images,
immutable HTTP, transcript/archive/bot caches, two-gateway linked
previews and composer choices). Coverage includes a matching old ETag
returning 404 after ownership changes and 409 while the home is
unavailable, with `no-store` and no ETag; image/archive caches are wiped
together and late callbacks cannot restore them.

EAS CLI **27.4.1**, production profile, before/after the image-cache and
preparation layers and on the final top branch: **unchanged relative to
the latest dev baseline**:

- iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e`
- Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae`

These differ from the original measurement hashes below because #424
already changed native branding/configuration on dev. This stack adds no
native dependency/configuration change. Final production Hermes exports
passed sequentially with one Metro worker: iOS **9,971,620 B**, Android
**9,961,323 B**. These include the newly merged client features; the
earlier performance comparisons below retain their original baseline.
Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict
files reports the same pre-existing `react-hooks/set-state-in-effect`
finding in `useImage.ts` on both this head and unmodified `origin/dev`;
session cleanup has no Expo ESLint findings. The required root oxlint
check passes.

No full local test run was started, as requested for the overloaded
shared machine. The earlier full-run timeout below is historical;
**GitHub CI is the current full-suite merge gate**. No native builds,
EAS builds, OTA publication or UI test suites were added. Previous
on-device profiling gaps remain.

---

Reuses prepared timeline entries for unchanged turns, makes sibling item
grouping linear, and avoids encoding/writing an identical immutable
snapshot repeatedly. New snapshot revisions still serialize and persist;
failed writes remain retryable, eviction allows a later resave, and
unpair/close fences remain intact.

| Metric | Before | After | Method / environment |
|---|---:|---:|---|
| Prepare 5,000 sibling items, median / p95 | 39.198 / 43.052 ms | 1.954
/ 3.728 ms | Bun 1.4.4, 10 samples after 5 warmups |
| Save the same immutable 14,085,915-byte snapshot, median | 30.218 ms |
<0.001 ms | Warm duplicates; in-memory storage adapter, no disk |
| Save a new immutable snapshot, median | 28.767 ms | 28.841 ms | Same
adapter; serialization still required |
| Cold cache load/decode, median | 21.348 ms | 20.932 ms | New cache per
sample, same encoded bytes; no disk |
| iOS Hermes bundle | 9,900,217 B | 9,901,992 B | Sequential `expo
export --platform ios` |
| Android Hermes bundle | 9,889,662 B | 9,891,426 B | Sequential `expo
export --platform android` |

CPU harness: deterministic 1,000-turn / 7,099-item snapshot on Linux
x86_64, Ryzen 5 5600X, shared 15.5 GiB machine. The before and after
control runs were consecutive while repository checks ran; this is not
an exclusive-CPU lab result. The grouping instrumentation retains
999/1,000 group arrays after one item changes. That is reference
retention, not a measured React render count.

Native fingerprints, EAS CLI 27.4.1, production profile, before = after:
- iOS: `2a0ef03a2a0fda8e7fad2e3df8609803d2edbda3`
- Android: `c5c880ae8d0f5d7bc867fcbaf8f756b2ca56a07d`

Only JS/TS changes; no native build, dependency, EAS build or OTA
publication. The exports establish bundle sizes, not runtime FPS.

Validation: durable bounded mobile cache integration cases passed (4
tests, 34 assertions), including retry, concurrent duplicate saves, disk
eviction/resave and close fencing. Whole-stack checks are recorded on
the top PR. No UI tests or changed UI copy.

Additional Expo ESLint check: 18 errors and 1 warning on both the frozen
baseline and this branch, all in unchanged files (effects/ref rules and
Expo Updates namespace imports). The required root oxlint check is
clean. These existing Expo lint findings were not suppressed or folded
into this performance change.

The table records the isolated preparation change measured before the
image-cache layer was added. Original cumulative final Hermes sizes,
including that layer: iOS 9,927,705 B and Android 9,917,398 B; both
native fingerprints were identical to that baseline. The image-cache
measurements and limitations are in #419. Original full-suite status is
recorded on #416: one unchanged composer-shell timeout remained
unresolved at that handoff.

On-device work remains: React Native commit/render counts, Hermes JS/UI
frame times, real filesystem read/write latency, variable-height
FlatList window tuning, and native bitmap/process memory after repeated
image-viewer visits. `docs/client-performance.md` gives the workload and
profiling procedure. This layer leaves FlatList settings and image
viewer behavior unchanged relative to #419.
nixuuu added a commit that referenced this pull request Nov 9, 2026
### Rebase verification — 2026-11-09

The five-layer stack is rebased onto `dev` at
`2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and
#421–#426. All PRs remain ready for review. The measurements below
describe the original baseline; this section records the current
integration verification.

The attachment route now passes `If-None-Match` through #421's shared
response helper. Gateway authorization/read succeeds before a 304 is
possible; qualified IDs, thumbnail fallback, bounded preview/truncation,
sanitized public failures and `no-store` errors are retained. Mobile
image caching retains public error messages and reconnect retries.
Session startup, replacement pairing, unpair and revocation retain all
four caches: transcript, bot, archived sidebar and images. The
branch/worktree panel, channel identity and sheet gesture changes remain
intact.

Passed on the rebased top branch: `bun install`, `bun run gen:check`,
full `bun run typecheck`, root `bun run lint`, `bun run format:check`
and the production web build. Final focused `check:tmp`: **27 passed, 0
failed, 334 assertions across 7 files**, no temp leftovers (images,
immutable HTTP, transcript/archive/bot caches, two-gateway linked
previews and composer choices). Coverage includes a matching old ETag
returning 404 after ownership changes and 409 while the home is
unavailable, with `no-store` and no ETag; image/archive caches are wiped
together and late callbacks cannot restore them.

EAS CLI **27.4.1**, production profile, before/after the image-cache and
preparation layers and on the final top branch: **unchanged relative to
the latest dev baseline**:

- iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e`
- Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae`

These differ from the original measurement hashes below because #424
already changed native branding/configuration on dev. This stack adds no
native dependency/configuration change. Final production Hermes exports
passed sequentially with one Metro worker: iOS **9,971,620 B**, Android
**9,961,323 B**. These include the newly merged client features; the
earlier performance comparisons below retain their original baseline.
Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict
files reports the same pre-existing `react-hooks/set-state-in-effect`
finding in `useImage.ts` on both this head and unmodified `origin/dev`;
session cleanup has no Expo ESLint findings. The required root oxlint
check passes.

No full local test run was started, as requested for the overloaded
shared machine. The earlier full-run timeout below is historical;
**GitHub CI is the current full-suite merge gate**. No native builds,
EAS builds, OTA publication or UI test suites were added. Previous
on-device profiling gaps remain.

---

Adds synthetic seeded data and a scripted worker so client measurements
can use a real gateway/BFF/EventSource path without inference or an
existing developer stack. The worker only produces synthetic answers;
credentials stay in process memory. Scripts clean up their own
servers/container and require a disk-backed TMPDIR.

| Metric / coverage | Before | After | Method / environment |
|---|---|---|---|
| Private database dataset | Empty | 500 threads; one with 1,000 turns
and 7,099 items | New disposable PostgreSQL only |
| Very long single answer | Moderate fixture answers | Last answer
repeated 64 times; configurable 1–100 in dev fixture | `answerRepeat=64`
|
| Streaming producer | In-process synthetic updates | 200 deltas at 25/s
over worker → gateway → BFF → SSE | Scripted worker, no CLI/model |
| Snapshot handler coverage | JSON-object decoder/reducer | Actual
EventSource arrival + string JSON parse + protobuf decode + state apply
| `probeThreadSnapshot(id,20)` |
| Navigation coverage | Renderer remount | SPA thread paint/focus-ready
proxy | `probeThreadNavigation(path)` |
| Bundle attribution | SvelteKit node numbers | Route names, all
layouts, shell and deduplicated JS/CSS closure | Generated SvelteKit
manifests |

`probeThreadStream(id)` sends a message and is intended exclusively for
the disposable synthetic thread. Both probes request incremental SSE,
ignore heartbeat frames when waiting for the first snapshot, and stream
completion follows the submitted turn's terminal state (including
coalesced updates). The seed gives threads a provider session identity
so submitted turns can start. BFF coalescing reduces the number of
delivered messages. Handler timing excludes rendering; the normal thread
page can remain subscribed to inspect the same stream. A sampled run
delivered 49 coalesced delta messages in 8.10 seconds, with handler
median / p95 of 0.2 / 0.3 ms on Chromium 156, Linux x86_64, 1280×800. It
generated 200 producer deltas at 25/s without inference.

This layer adds measurement coverage, not a production performance
claim. Navigation paint/focus readiness is not browser TTI. Cold FCP
depends on build/cache state. Native render counts, native UI frames,
filesystem latency and image bitmap memory still require an on-device
profile. No UI test suite was added. Polish `docs/client-performance.md`
documents commands and limits; whole-stack verification and measured
browser results are recorded on the top PR.

Fresh-launch verification after the tooling correction: a newly created
disposable database and production BFF accepted one synthetic message,
delivered 45 coalesced `itemDelta` events plus `itemCompleted` /
`turnFinished`, and persisted the turn as completed. No manual database
updates were needed. The bounded SSE capture intentionally stopped at
its 15-second curl deadline after completion; that deadline is not a
stream failure.
nixuuu added a commit that referenced this pull request Nov 9, 2026
### Rebase verification — 2026-11-09

The five-layer stack is rebased onto `dev` at
`2580ed75cdfc162e98e125b7c4d0b24eb81901b7`, including #418 and
#421–#426. All PRs remain ready for review. The measurements below
describe the original baseline; this section records the current
integration verification.

The attachment route now passes `If-None-Match` through #421's shared
response helper. Gateway authorization/read succeeds before a 304 is
possible; qualified IDs, thumbnail fallback, bounded preview/truncation,
sanitized public failures and `no-store` errors are retained. Mobile
image caching retains public error messages and reconnect retries.
Session startup, replacement pairing, unpair and revocation retain all
four caches: transcript, bot, archived sidebar and images. The
branch/worktree panel, channel identity and sheet gesture changes remain
intact.

Passed on the rebased top branch: `bun install`, `bun run gen:check`,
full `bun run typecheck`, root `bun run lint`, `bun run format:check`
and the production web build. Final focused `check:tmp`: **27 passed, 0
failed, 334 assertions across 7 files**, no temp leftovers (images,
immutable HTTP, transcript/archive/bot caches, two-gateway linked
previews and composer choices). Coverage includes a matching old ETag
returning 404 after ownership changes and 409 while the home is
unavailable, with `no-store` and no ETag; image/archive caches are wiped
together and late callbacks cannot restore them.

EAS CLI **27.4.1**, production profile, before/after the image-cache and
preparation layers and on the final top branch: **unchanged relative to
the latest dev baseline**:

- iOS: `bf3156a1bd878e10c0b0be25d4c194a837fb1b7e`
- Android: `d638e5f7b7fa87f54ccc0715c5fe150b8c0ad3ae`

These differ from the original measurement hashes below because #424
already changed native branding/configuration on dev. This stack adds no
native dependency/configuration change. Final production Hermes exports
passed sequentially with one Metro worker: iOS **9,971,620 B**, Android
**9,961,323 B**. These include the newly merged client features; the
earlier performance comparisons below retain their original baseline.
Expo Doctor: **20/20**. An additional Expo ESLint check of the conflict
files reports the same pre-existing `react-hooks/set-state-in-effect`
finding in `useImage.ts` on both this head and unmodified `origin/dev`;
session cleanup has no Expo ESLint findings. The required root oxlint
check passes.

No full local test run was started, as requested for the overloaded
shared machine. The earlier full-run timeout below is historical;
**GitHub CI is the current full-suite merge gate**. No native builds,
EAS builds, OTA publication or UI test suites were added. Previous
on-device profiling gaps remain.

---

Reduces allocations while retaining unchanged feed rows and loads the
bot settings editor only when it is first opened. Provider discovery and
the dynamic import run concurrently; the existing loading/error dialog,
generation fence and close animation remain in place. Web and the
Electron renderer share this build.

| Metric | Before | After | Method / environment |
|---|---:|---:|---|
| FeedBuilder unchanged 1,000-turn history, median / p95 | 25.829 /
37.331 ms | 16.725 / 31.636 ms | 30 Bun samples after 5 warmups; shared
machine with checks running |
| Initial shell JS, raw / gzip | 1,049,359 / 376,536 B | 978,327 /
348,632 B | Production static import closure |
| Thread route JS, raw / gzip | 1,602,296 / 565,283 B | 1,567,887 /
552,802 B | `/threads/[threadId]`, shell + layouts + page, deduplicated
|
| General settings JS, raw / gzip | 1,078,406 / 389,672 B | 1,007,374 /
361,768 B | `/settings/general`, same accounting |
| Bot conversation JS, raw / gzip | 1,230,361 / 443,477 B | 1,201,264 /
433,818 B | `/bots/[botId]`, same accounting |
| Initial shell CSS, raw / gzip | 241,576 / 39,106 B | 240,383 / 38,685
B | Production static import closure |
| Renderer remount, two-frame proxy | 20.3 ms | 17.8 ms | One warmed run
per revision, isolated 1,000-turn fixture |
| Streaming update + render/layout, mean / p95 | 18.58 / 24.6 ms | 12.89
/ 17.3 ms | Same fixture and deterministic 200 updates; not network
latency |
| Scroll frame mean / max | 16.67 / 16.8 ms | 16.66 / 16.8 ms | 80
scroll steps; zero frames over threshold in either run |
| Production cold first paint / FCP | 128 / 300 ms | 128 / 264 ms |
Single sample per origin, cold HTTP cache, 500-thread sidebar |
| Production first feed + focus-ready observation | 1,044.9 ms | 668 ms
| Tool-attachment upper bound, single sample; not precise TTI |
| Real SSE delta handler, median / p95 | 0.2 / 0.3 ms | 0.3 / 0.4 ms |
One ~8.2-second turn, 200 producer deltas at 25/s, JSON.parse + decode +
reducer only |

Environment: Bun 1.4.4, Linux x86_64, Ryzen 5 5600X, shared 15.5 GiB
memory, Chromium 156 at 1280×800. JS data: 1,000 turns, 7,099 items,
14,085,915 protobuf bytes. CPU comparisons use identical deterministic
input; no exclusive-CPU claim. Dynamic imports and highlighter grammars
are excluded from initial static closure totals.

The browser samples are descriptive measurements on a shared machine,
not statistically significant navigation or SSE speedup claims. BFF
coalescing delivered 49 delta messages before and 36 after in the
sampled network turns. The SSE reducer was not optimized here. Initial
real snapshots were 24-turn pages, not all 1,000 turns; their sampled
payloads differ after synthetic turns, so no snapshot speedup is
claimed.

Visual verification: real seeded thread with a 64× long answer, desktop
1280×800 and phone 390×844, light and dark, streaming, anchored
composer, lazy bot editor initial open/close/reopen and error display.
No horizontal document overflow observed. A visible completed answer
retained exactly the same viewport y coordinate (-465.664 px) throughout
a subsequent 8.2-second streamed turn while reading history. The fixture
stayed at zero bottom gap after streaming. Motion code and tokens are
unchanged; reduced-motion emulation was not available through the shared
browser tool and was not runtime-verified.

The existing timeline virtualizer limits mounted articles, but a single
huge answer still creates all its Markdown DOM and the 500-row sidebar
eventually mounts in full (26,215 total elements in the settled seeded
production page). The isolated fixture's mounted element count was 164
before / 114 after at sampled positions; variable visible rows make this
unsuitable as a DOM-reduction claim. These are remaining candidates, not
fixed problems in this PR.

Original validation: `bun install`, `gen:check`, full `typecheck`, root
`lint`, `format:check`, production web build and both Expo exports
passed. The original final full `check:tmp` finished with 1,919 pass /
161 skip / 1 fail, 22,240 assertions, 1,050.58 seconds, no temp
leftovers. The unchanged composer-shell test “Stop during a shell steer
kills its group and persists the failed delivery” hit a 10-second RPC
cancellation in both original final full runs; its focused retry passed.
At that handoff, the full gate was unresolved and the stack was draft.
No timeout, assertion or backend changes were made to obtain a pass. No
UI test suite was added.

| Actual 30-minute session | Before | After | Method / limitation |
|---|---:|---:|---|
| Duration | 1,801.418 s | 1,801.638 s | Same 1,000-turn fixture, 25
producer updates/s within each visit |
| Completed cycles / updates | 204 / 40,800 | 187 / 37,400 | Shared
host; the full test suite ran during the after-session |
| Handler median / p95 | 1.3 / 2.6 ms | 2.1 / 3.7 ms | Protobuf
JSON-object decode + reducer; excludes network/render |
| Long tasks / total duration | 1,444 / 131.895 s | 3,894 / 305.815 s |
Includes reset, stream and scroll; unequal concurrent load |
| Chromium heap counter, first → last | 109 → 364 MB | 342 → 462 MB |
Coarse/cached counter; no forced GC, different starting heaps |
| DOM first / last / range | 688 / 563 / 533–752 | 554 / 686 / 516–725 |
Entire isolated fixture page |

The long run was worse under its recorded conditions; it is not evidence
of a performance win. The concurrent suite took 1,580 seconds versus
1,029 seconds in the earlier successful run, confirming substantially
different observed runtime conditions without proving the cause of
either result. Heap counter growth cannot establish retained memory or
the absence of leaks; a DevTools memory profile with controlled GC
remains necessary. No memory improvement is claimed.

A subsequent short control without the full suite, using the same
1,000-turn fixture (after first, then before), recorded:

| Short session metric | Before | After | Method / limitation |
|---|---:|---:|---|
| Duration / cycles / updates | 126.187 s / 13 / 2,600 | 124.428 s / 14
/ 2,800 | One ~2-minute sample each; no own test suite, shared host |
| Long tasks / total duration | 174 / 16.882 s | 32 / 6.642 s | About
13.4 vs 2.3 long tasks/cycle; no exclusive-CPU claim |
| Handler median / p95 | 0.7 / 1.5 ms | 2.1 / 3.4 ms | Reducer timing
remains worse in this sample; no handler win claimed |

The short control did not reproduce the long-task regression and does
not establish long-session memory stability. A controlled CPU/memory
profile remains open before claiming an overall long-session
improvement. The paired Bun harness and bundle accounting are the
primary evidence for this change.

Failure follow-up: unchanged ask-user, composer-shell and
thread-mirror-deltas files passed together (42 tests, 226 assertions, 0
failures, clean temp directory, 38.70 seconds). The subsequent full run
passed ask-user and mirror cases but repeated the composer-shell
timeout. This does not establish the cause or make the full gate green.

The final stack includes the focused image-cache layer #419. Browser
validation on that final stack: 20 real thumbnails, 803,816 body bytes
on first pass, zero additional network requests/body bytes on a second
pass or reopening the thread. Existing web immutable caching already
provided repeat reuse; no additional web transfer improvement is
claimed. ETag/304, distinct variants and no-store 404 were observed.
Mobile final Hermes bundles are iOS 9,927,705 B / Android 9,917,398 B,
with unchanged production fingerprints. Final route bundle accounting is
identical to the table above.

The five focused cache and immutable HTTP checks passed (39 assertions),
including in the final full run. Expo Doctor passed 20/20 checks. All
owned benchmark servers and browser tabs were closed before the final
full checks.

Copy audit: no changed application UI text. No UI test suite was added.
Polish documentation records row equality, lazy loading and the
measurement method. This does not change FlatList tuning, markdown
parsing, native image memory, Electron main-process caches or
synchronization semantics.
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.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Import progress previously rescanned each run's items separately for
multiple aggregates. It now computes counts and exact bigint byte totals
together after selecting at most 50 owner-scoped runs. The runner checks
only run state before admitting the next item, and calculates full
totals when finishing.

## Measurement

Two warmups, 20 serial samples. Fixture: 50 completed imports with 2,000
items each.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| Import progress | 1 → 1 | 399.88 → 53.70 | 50 → 50 | 26,601 → 26,601 |

The initial mixed-load run reduced progress p95 from 2,982.12 to 335.72
ms and elapsed workload from 18.09 to 3.83 s; this was an exploratory
run, before the streaming correctness assertion was added. It is not a
verified streaming comparison. Later concurrent harness runs verify the
running turn's complete contents and are documented on the overview
layer.

## SQL audit

| Statements / path | Verdict |
|---|---|
| imports/store.ts: runs + progress aggregates | Replaced repeated
correlated scans with one lateral aggregate per selected run; owner and
run selection precede the expensive scan; exact decimal sums preserved.
|
| imports/store.ts: item UI projection | Source snapshots, append base
and resume cursors excluded from UI rows; internal operations retain the
complete record. |
| imports/runs.ts: runState | Indexed owner + run-id point read replaces
progress aggregation in admission loop. |
| imports/runner.ts: next item / completion | Cancellation is rechecked
before admitting another item; totals remain exact at completion. |
| scripts/bench/concurrent.ts | Independent polling, ingest and mirror
workload; no production instrumentation. |
| scripts/bench/seed.ts | Optional agentTail defaults to zero,
preserving all callers after #418 throughout the stack. |

Import batching/restart tests cover order, owner isolation, large bigint
totals and rollback.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## Shared CI test corrections

This bottom layer also carries two existing linked-computer integration
test synchronization corrections, so every PR in the stack receives
them. The slow-read test waits for actual GetComputerUpdates admission
before timing the stale-state transition. The repeated-blackhole test
waits for both transport readiness and persisted overview presence while
continuing to assert committed-row retention and local-list latency. No
production timeout, polling, mirror or retention behavior is relaxed.

Detailed original-head/dev comparison and diagnostic evidence are
recorded in #439 and #443. The timeout trace showed approximately 10
seconds waiting for an RPC slot plus the 10-second RPC timeout on both
the original layer-10 head and dev at diagnosis. A temporary 100 ms
presence-write delay reproduced #443's exact assertion on both dev and
the original layer-14 head; the corrected wait passed under that same
delay. Diagnostic instrumentation is not committed. These are
pre-existing test races, so they do not receive promotion-holding
Fixes/Refs links.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Pending-command reads previously decoded the entire active outbox.
Delivery now uses ordered keyset pages of at most 2,048 commands and
approximately 512 KiB, allowing one oversized command to make progress.
The consumer preserves per-command TTL checks and ordering. Restartable,
opt-in concurrent index tasks are added separately from transactional
schema migrations.

## Measurement and approved TTL change

Three rounds, two warmups and 20 samples per round, alternating
legacy/current reads. Fixture: 4,096 pending commands with real protobuf
IDs plus 16,384 completed commands.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| First command page, final TTL variant | 1 → 1 | 11.31 → 6.03 | 4,096 →
2,048 | 3,350,566 → 1,472,592 |
| Complete read, final TTL variant | 1 → 3 | 9.25 → 9.47 | 4,096 → 4,096
| 3,350,566 → 2,945,065 |

**Approved by the user:** filtering TTL in SQL is required so expired
commands are never prefetched. The 9.25 → 9.47 ms full-read difference
is within noise and remains below the original 10.32 ms baseline. No
further tuning is requested for this path. The epoch-float variant
(full-read p95 10.88 ms versus 8.88 ms in its paired legacy run) was
rejected and is absent.

Earlier 64-command paging required 65 queries and 37.45 ms for a
complete read; that implementation was rejected in favor of the final
larger bounded pages. The table is the final runtime/legacy comparison,
not an isolated claim for every intervening index revision.

## SQL audit

| Statements / path | Verdict |
|---|---|
| store/outbox.ts: enqueue / commandDone | Single-row durable writes
retained; IDs and completion markers survive retries. |
| store/outbox.ts: pendingCommands | SQL TTL predicate, narrow columns,
stable (created_at,id) cursor, row and payload budgets; no full-queue JS
decoding. |
| core/core-commands.ts | Iterates pages, checks TTL again before
delivery, advances cursor even when a command expires after prefetch. |
| 0103_queue_read_indexes.sql | Performance-only index task; subsequent
lifecycle layer replaces its temporary redelivery index after the
replacement is valid. |
| migrations/index-tasks.ts | Reserved session, nonblocking
advisory-lock acquisition, definition and indisvalid checks, restart of
invalid index; concurrent DDL never enters transaction. |
| migrations/index.ts / gateway migration entrypoints | Schema migration
commits before tasks; opt in with CANOPY_DATABASE_INDEX_MODE=concurrent.
Existing legacy transactional migrations are not converted. |

Migration tests cover repeated/concurrent migrators, writes during a
concurrent build, failed/invalid tasks, changed definitions and
transaction rejection. Command tests cover restart, same-time ordering,
byte budget and expiry after prefetch. Default desktop builds remain
blocking. Large legacy migrations still need their documented
maintenance window.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Schedule workspace preparation no longer holds the schedule row lock or
a database connection while awaiting worker I/O. The final transaction
rechecks the lease, version, occurrence and placement before inserting
the thread, command and scheduled turn. The scheduler claims one
occurrence immediately before handling it instead of leasing 50 ahead of
a potentially slow operation.

## Measurement

Two warmups, 20 samples; edit starts after workspace preparation begins,
with 50 ms synthetic external I/O. Edit latency includes row-lock wait.

| Operation | Queries / rows / bytes | p95 ms before → after |
Lock-related result |
|---|---|---:|---|
| Concurrent schedule edit | Not counted by this contention harness; no
query reduction claimed | 72.89 → 8.35 | Queued despite the concurrent
edit: 20 → 0 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| bus-schedules.ts: claimDueSchedules | FOR UPDATE SKIP LOCKED remains
atomic; stable next_run_at,id order; normal loop claims one row. |
| schedule-workspace.ts: preparation reads | Read-only lookup and
external preparation happen outside the firing transaction. |
| bus-schedules.ts: fireSchedule fence | Locks the claimed schedule only
after preparation; rejects replacement lease/version/occurrence. |
| schedule-workspace.ts: placementAvailable | Revalidates worker,
project and workspace before committing the prepared placement. |
| bus-schedules.ts: turn, schedule_run, command and schedule writes |
Existing atomic enqueue/occurrence durability preserved. |
| schedule-workspace.ts: preparation failure retry | Shortens only the
same lease through a fenced update; never shortens a replacement lease.
|

Restart, idempotent occurrence, offline reconnect, pause during
preparation and archived placement tests cover the changed boundaries.
The lease is 180 s; preparation failures retain the occurrence and retry
promptly.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Obsolete mirror data and reconstructible payloads are pruned by an
owner-scoped durable maintenance job instead of an unbounded foreground
delete during checkpoint installation. The job uses bounded batches, a
durable due time, SKIP LOCKED, a 100 ms lock timeout and a 1 s statement
timeout.

## Measurement

Two warmups, 20 samples; 4,096 obsolete mirror snapshots with 4 KiB
logical content.

| Operation | Queries | p95 ms before → after | Rows / bytes |
|---|---:|---:|---|
| Foreground checkpoint cleanup → first complete maintenance batch | 16
for new full maintenance transaction; old count not recorded | 13.48 →
8.63 | Foreground deleted rows 4,096 → 0; batch limit 256; 258 returned
rows / 13,742 decoded bytes |
| Complete bounded backlog drain | Multiple committed batches | new
164.61 | All 4,096 snapshots removed |

Drain measurement advances the durable due time between batches;
production yields between scheduled attempts. This trades total drain
time for bounded foreground cost and never claims physical disk shrink.

## SQL audit and retention policy

| Statements / path | Verdict |
|---|---|
| maintenance/prune.ts: claim and reschedule | Durable per-owner row
coordinates instances; progress and eligibility commit with each batch.
|
| worker_commands compaction | Completed/failed thread commands older
than 7 days lose payload only; IDs/status/results stay; harness commands
excluded. |
| bot_harness_events deletion | Terminal turn older than 7 days, same
ingestion lock, only at/below durable worker/journal/bot ACK. Projection
and dedup cursor remain. |
| computer_thread_changes | Keep latest 10,000 revisions; old resume
cursor falls back to full snapshot. |
| mirror generations | Delete only non-current, abandoned/expired
registered generations, with subscription/state fence; never active
staging/current generation. |
| config_history / OAuth states / source previews | Existing 90-day
history policy; expired OAuth states after 7 days; expired source
previews. Bounded, owner-scoped. |
| 0104–0105 migrations | Durable maintenance/generation metadata and
performance indexes; expected migration list updated. |

No age-only deletion of user timelines, transcript events/items, import
history, audit logs, command dedup keys or move redirects. See
docs/database-retention.md for exact policy and unbounded tables
intentionally retained. Integration tests cover restart, ACK fences,
owner isolation, active generations and bounded drain.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Polling reads now have explicit pages, and repeated reference resolution
uses grouped queries. Notification previews are projected in SQL before
content reaches JavaScript.

## Measurement

Two warmups, 20 samples. Fixture: 32 targets, 256 notifications, 24
secrets, 10,013 workers.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bus facts, 32 targets | 36 → 5 | 5.82 → 1.50 | 34 → 34 | 40,282 →
10,268 |
| Notification first page | 513 → 1 | 94.31 → 0.65 | 768 → 50 | 535,041
→ 26,901 |
| Complete 256-notification read | 513 → 7 | 94.31 → 2.27 | 768 → 256 |
535,041 → 137,736 |
| Worker config, 24 secrets | 25 → 2 | 3.93 → 0.99 | 25 → 25 | 10,909 →
11,954 |
| Worker credential miss | 1 → 1 | 0.89 → 0.14 | 0 → 0 | 2 → 2 |

Secret resolution returns a few more metadata bytes to eliminate 24
round trips; latency improves.

## SQL audit

| Statements / path | Verdict |
|---|---|
| store/bus-calls.ts: facts | One grouped header lookup for requested
targets; existing domain authorization enforces owner/tree before
execution. No target-by-target SELECT. |
| UUID lookup aliases | Grouped results retain the exact requested UUID
keys, including uppercase spelling. Integration coverage verifies that
the owner authorization still rejects a foreign thread. |
| bus-deliveries.ts / core-agent-bus-deliveries.ts | Notification pages
50, fallbacks 64, durable status and keyset cursor; one latest answer
per target turn. |
| bots/store-wakeups.ts / store-queue.ts | Bounded 32-row watch/wakeup
polls; grouped answer text, no tool payload decoding. |
| worker-config-store.ts | Grouped encrypted secret references;
ciphertext stays server-side. |
| workers-store.ts / desktop-updates/store.ts | Credential-hash index
and UUID comparison without casting indexed UUID column to text. |
| worktrees.ts: branch context | First and three latest prompts via
ordered index, excluding middle history. |
| 0106_polling_indexes.sql | Partial polling and credential indexes use
online-capable tasks. |

Owner, restart, same-time cursor, queue fairness and large-history tests
protect the changed reads.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
The concurrent benchmark now writes into a genuinely running streaming
turn and verifies its complete text/status after the workload. It can
exercise several independent SQL pools while reserving administrative
capacity below PostgreSQL's 40-connection desktop limit.

**No production overview optimization ships in this layer.** The
proposed read-only scratch-placement fast path was reverted at the
user's request after repeated measurements showed worse latency on
streaming ingest and other paths. Production project reads and their
tests are identical to the preceding layer.

## Measurement and SQL audit

| Statements / path | Before → after / verdict |
|---|---|
| projects-store.ts | No production changes; existing 8-statement steady
reconciliation, owner lock and placement/path checks retained. No new
latency improvement claimed. |
| concurrent.ts: polling | Projects, paged history, import progress and
pending commands run through actual stores, with eight polling clients
and 40 iterations. |
| concurrent.ts: streaming | Eight-event batches into a separate running
turn; complete text, item status and turn status verified after every
workload. |
| pg_stat_activity / pg_blocking_pids | Separate monitoring connection
samples about every 10 ms; counters are sampled waits/blockers, not
exact lock-wait duration. |
| pool probe / statement timeout | Scoped checkout includes connection
setup; explicit timeout cancellation rolls back its transaction and SET
LOCAL does not leak. |

Pool-capacity exploration on the 40-connection server: capacities
4,10,30 and three independent pools of 10 gave acquisition p95
71.61,10.87,0.25,7.42 ms; peak connections 4,10,11,13. Three pools had
page/ingest p95 638.72/580.30 ms and event-loop p95 54.76 ms. These are
capacity observations, not permission to raise production defaults. The
harness runs SQL pools rather than several real gateway processes.

## Remaining

Profile scratch-project reconciliation further before proposing the fast
path again. Three new before/experimental-after rounds used identical
fixture and harness code, changing only the production project-read
implementation, in order before/after, after/before, before/after. Each
workload had eight clients, pool 10, max_connections=40, 40 client
iterations, streaming ingest and mirror writes. There were zero
operation failures; streaming contents and timeout rollback passed in
all six workloads.

Values below are per-round nearest-rank p95 in milliseconds. The last
column is the median of those three p95 values, **not a pooled p95**.

| Operation | Before rounds | Rejected fast-path rounds | Median before
→ rejected |
|---|---|---|---:|
| Overview | 327.07 / 99.50 / 82.07 | 80.35 / 69.96 / 69.34 | 99.50 →
69.96 |
| History page | 307.16 / 191.10 / 185.11 | 224.76 / 188.81 / 303.22 |
191.10 → 224.76 |
| Streaming ingest | 408.60 / 199.93 / 105.08 | 287.82 / 104.04 / 416.63
| 199.93 → 287.82 |
| Import progress | 386.48 / 372.93 / 386.24 | 410.29 / 383.81 / 401.24
| 386.24 → 401.24 |
| Commands | 129.29 / 83.74 / 82.61 | 87.00 / 82.55 / 84.92 | 83.74 →
84.92 |
| Mirror write | 152.80 / 89.02 / 83.01 | 98.34 / 83.18 / 80.68 | 89.02
→ 83.18 |
| Pool acquisition | 17.18 / 60.47 / 5.14 | 20.23 / 10.37 / 12.49 |
17.18 → 12.49 |
| Event-loop delay | 25.35 / 2.60 / 1.10 | 4.80 / 0.71 / 12.98 | 2.60 →
4.80 |

Sampled waits/blockers were 160/188,40/46,33/32 before and 0/0 in all
experimental-after rounds. Peak connections/active connections were
10/10 throughout. The shared machine shows substantial variance; the
measurements do not establish the cause of the regression. In
particular, faster overview and fewer locks do not justify
streaming-ingest p95 increasing from 199.93 to 287.82 ms. The user
explicitly rejected that trade-off. No regression exception is claimed;
the fast path and its behavior-specific test were removed before final
validation.

An earlier single comparison gave overview 92.99 → 78.34, page 190.58 →
196.57 and mirror 86.05 → 91.46 ms. Those observations are retained as
context and superseded for acceptance by the repeated rejection above.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40). Latency runs without tracing; pool and lock
observations are separate probes. Store measurements exclude transport
and external CLI work. Raw results, hosts and datasets are not
committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining SQL-audit gaps are recorded in the top
PR. CI remains the full gate. Polish documentation is updated; no UI
text changes, so the copy audit does not apply.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Large snapshot protobuf conversion now yields to the I/O phase between
~4 ms slices, after materializing and closing the consistent read
transaction. The complete timeline and original ordering remain intact.

## Measurement

Same 32,768 synthetic protobuf item rows, three rounds, two warmups and
20 samples per mode/round; alternating mode order. Decode only, no SQL
or transport.

| Operation | Queries / rows / bytes | p95 ms before → after | Timer-gap
p95 before → after |
|---|---|---:|---:|
| Snapshot decode, final chunk-mapping implementation | 0 / 32,768 /
identical input (bytes not separately counted) | 52.93 → 46.52 | 53.67 →
9.05 ms |

Earlier per-row cooperative decoding regressed 38.11 → 51.13 ms, and a
preallocated-array experiment gave 36.66 → 36.82 ms. Those
implementations were rejected. The committed implementation maps small
chunks and reduces timer starvation without the measured p95 regression.

## SQL / request-path audit

| Statements / path | Verdict |
|---|---|
| thread-snapshot.ts: turn/item/notice/interactions reads | SQL range
and payload are unchanged. Full legacy/restored windows remain complete.
|
| repeatable-read cursor snapshot | All rows materialized before leaving
transaction; cooperative decode does not extend the owned read
transaction. |
| snapshot-decode.ts | Real I/O-phase yield, not a microtask; mapping
preserves item/notice sequence. |
| single huge item / driver JSON / transport serialization | Still
synchronous; not claimed solved by slicing between rows. Requires a
separate codec/fragmentation contract. |

Existing fork/history/mirror/restart read-cost suites verify unchanged
contents. No new trivial helper test is added.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Diagnostic plan capture now includes writes and locked SELECTs without
changing their original effects: EXPLAIN runs on the same owned
connection, inside a rollback/savepoint, before the original statement.
The maintenance selector skips terminal harness turns whose remaining
events have no acknowledged pruneable rows, avoiding starvation behind
an unacknowledged oldest turn.

## Measurement

| Path | Queries / p95 / rows / bytes | Verdict |
|---|---|---|
| Production without diagnostic opt-in | No tracing added; no
instrumentation latency claim | Same ordinary SQL path |
| Diagnostic EXPLAIN mode | Deliberately adds execution + rollback;
excluded from latency samples | Reports sanitized
nodes/buffers/fingerprints, errors and skipped effects |
| Unacknowledged prune candidate | Latency not benchmarked separately |
Correctness/fairness fence; integration test proves eligible later turn
can progress |

## SQL audit

| Statements / path | Verdict |
|---|---|
| plan-capture.ts: SELECT/INSERT/UPDATE/DELETE/WITH | EXPLAIN ANALYZE
BUFFERS before original execution with preserved FK/lock context. |
| transaction/savepoint handling | Failed diagnostic plan rolls back its
savepoint and leaves original transaction usable; nested writes execute
exactly once. |
| session and sequence effects | Advisory locks, notifications, sequence
mutation, cancellation and session setters skipped explicitly. |
| SQL inventory/evidence matching | Candidate templates, not
executed-call-site proof; dynamic fragments and cold paths can remain
unmatched. |
| maintenance/prune.ts: terminal harness candidate | Requires no
remaining events or at least one durable acknowledged event before
claiming the oldest turn. |

A historical inventory run found 2,171 statement/fragment locations, 380
with template evidence from 386 unique fingerprints, 83 unmatched plans
and zero plan errors. **This is not complete SQL audit coverage**, and
source line numbers can shift after edits/rebase. New final-revision
coverage must be distinguished from this diagnostic snapshot. DDL and
transaction control have no EXPLAIN plan. Test fixtures do not establish
large-dataset performance.

The pre-rebase diagnostic repeat on head `3381f50b` used the standard
240-thread / 2,048-long-turn / 4,096-byte fixture plus the queue/import
fixture: 22 operations, 80 plans, 58 unique fingerprints, zero plan
errors and zero skipped plans. Template matching found 64 candidate
locations in that revision's inventory of 2,177 locations; 16 plans had
no source match. The 2,113 locations without evidence from this repeat
are not declared reviewed. One diagnostic iteration and two warmups were
used to refresh plans, **not to establish before/after p95**. Database
storage was approximately 201 MiB. The post-rebase static inventory
still contains 2,177 locations across 311 files; plan matches were not
reassigned across revisions. Historical and current source-location
counts are not combined.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Connector lists now fetch metadata and resolve worker/bot grants in two
grouped reads. Instance lists filter ownership in SQL before decoding
configuration, and instance assignment inserts workers with unnest
instead of one INSERT each. Import admission checks read run state
without recomputing totals.

## Measurement

Two warmups, 20 samples; 32 connector catalogs and 32 foreign instance
configurations, each 64 KiB; 13 assigned workers; one 2,000-item import.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Connectors list | 65 → 3 | 20.64 → 1.94 | 96 → 96 | 2,116,943 → 19,217
|
| Owner instance list | 4 → 4 | 7.71 → 1.43 | 49 → 17 | 2,115,729 →
3,130 |
| Assign instance to workers | 15 → 3 | 41.25 → 36.30 | 13 → 13 | 1,847
→ 1,823 |
| Import runner admission | 1 → 1 | 1.23 → 0.31 | 1 → 1 | 533 → 101 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| connectors/accounts.ts list + grants | Metadata projection, owner
scope and grouped grants; execution still fetches actual tool catalog
after authorization. |
| store/instance-queries.ts instance/proxy/config/count reads | Owner or
explicitly shared instance applied in SQL, not after blob decode. |
| store/instance-queries.ts assignWorkers | One unnest insert with
existing transaction/validation. |
| store/worker-config-store.ts secret reference insert | Grouped
insertion retains transactional configuration revision. |
| connectors/store-oauth-state.ts | Owner-scoped lookup retained in
token-state transitions. |
| imports/runs.ts / runner.ts | Keyed run-state check; terminal counters
computed at completion. |

Internal cross-owner configuration reconciliation is deliberately
separate from owner-visible list reads. Focused connector/config/import
and owner tests cover behavior.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Worktree activity checks use partial indexes for active turns and
background items instead of walking long completed histories. Secret UI
reads exclude ciphertext. The redelivery index supports both active and
expired-prefix command reads without duplicating the composer-choices
index.

## Measurement

Two warmups, 20 samples; long worktree history, 16,384 expired commands
before 64 active ones, 64 secrets with 8 KiB ciphertext.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Worktree inventory | 1 → 1 | 14.37 → 6.21 | 1 → 1 | 759 → 759 |
| Commands past expired prefix | 1 → 1 | 10.24 → 1.36 | 64 → 64 | 32,513
→ 32,513 |
| Secret metadata | 1 → 1 | 6.70 → 0.54 | 64 → 64 | 5,725,057 → 14,529 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| worktree-lifecycle.ts / worktrees.ts: active-turn EXISTS | Partial
active-turn index; completed history excluded. |
| worktree activity: background items | Existing status/type semantics
retained; matching partial index. |
| thread-secrets.ts: threadSecrets / secretResult | Narrow metadata
projection; secret values never enter UI/history. |
| outbox.ts: pending command page | Narrow columns and SQL TTL;
supported by replacement index. |
| 0107_lifecycle_read_indexes.sql | Online-capable performance indexes;
old outbox indexes retired only after valid replacement. |

The final outbox TTL-in-SQL p95 9.25 → 9.47 ms is the user's explicitly
approved correctness/noise exception; details and rejected epoch-float
experiment are on the queue/index layer. Worktree lifecycle and
command-expiry tests cover guards and replay.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## CI timeout investigation

On the original layer-10 head `e7e27bb7`, the isolated slow-read case
passed 10/10 times. Repeating the complete file 10 times passed 70/70
tests in 765.48 seconds, with clean temp-directory checks. The isolated
case also passed 10/10 times on dev `119b373a`.

A temporary diagnostic on the layer-10 head established the deadline
race after the preceding reconnect case: the stalled GetComputerUpdates
RPC reached the peer at 10,023 ms, while its cache became stale at
20,006 ms from the beginning of the test's wait. The test's 20-second
budget included admission behind other bounded background reads and the
RPC's own 10-second timeout. The CI assertion failed at 20,012 ms. The
permanent test correction waits for the actual new RPC before starting
the stale-state deadline; cooldown, local-read latency, reachability and
recovery assertions remain active. It is applied at the bottom of the
stack so every layer receives it.

PeerReads, connection tracking, handshake handling and linked update
reads are unchanged between this layer and dev. The linked fixture does
not start the maintenance job. This investigation found a test deadline
race, not evidence of a lifecycle/retention production regression. No
production timeout or polling limit is relaxed.

The same temporary diagnostic on dev at diagnosis `618cbd15` observed
RPC admission at 10,017 ms and stale state at 20,015 ms; the complete
file passed 7/7 tests in 78.33 seconds. Both instrumented runs exhibit
the same pre-existing scheduling boundary. Diagnostic logging is not
part of the committed tests.

After the fix and rebase, the complete timeout file passed **21/21 tests
across three full-file rounds in 230.24 seconds**, with a clean temp
directory. The 20-second stale-state bound starts after actual RPC
admission; the outer test timeout covers the separate bounded admission,
timeout, cooldown and recovery phases.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Skill assignment now reuses current immutable artifacts already loaded
in the owner's library snapshot. Historical pinned versions are fetched
as plain rows in a grouped query. Worker settings read version/hash
metadata once for all skills.

## Profile and measurement

The first reported run regressed snapshot p95 **175.8 → 229.9 ms**
despite 426 → 11 queries and ~10 MB → 1.08 MB. That result was rejected.
Profiling then separated normal latency, process CPU, driver wall time
and PostgreSQL EXPLAIN; other own benchmarks/tests/builds were stopped
for paired final runs.

Final three-round comparison: 32 skills, two 16 KiB versions, 13
workers, 16 historical pins. Two warmups and 20 samples per round.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Skills snapshot | 426 → 11 | 136.62 → 20.16 | 463 → 63 | 9,970,938 →
1,078,459 |
| Worker environment settings | 480 → 18 | 124.84 → 27.99 | 543 → 127 |
9,978,614 → 1,087,944 |

Snapshot round p95 before: 120.21 / 109.63 / 144.77 ms; after: 20.88 /
13.26 / 12.48 ms. Worker settings: 130.72 / 101.26 / 121.97 → 50.60 /
14.12 / 16.85 ms. Snapshot CPU including warmups across rounds: 4,412.08
→ 552.39 ms.

Findings: reuse eliminates repeated artifact reads and protobuf decode
for every skill/worker combination. Historical reads return plain rows;
no new large server-side JSON aggregate is introduced. Representative
PostgreSQL execution: current-library read 0.639 ms, historical batch
0.129 ms, version metadata 0.088 ms. Final snapshot driver wall: current
32-skill read 2.51 ms, historical batch 1.04 ms. A cold diagnostic
connection consumed 7.94 ms on its first operation; diagnostic totals
include instrumentation and must not be subtracted from uninstrumented
p95 to infer JS time. The initial regression does not establish a single
slow SQL/JS cause; it remains recorded as an adverse shared-host
observation, superseded for acceptance by the isolated paired
measurements.

## SQL audit

| Statements / path | Verdict |
|---|---|
| skill-database.ts: skillVersions | Owner-scoped grouped historical
pins, exact bigint version strings; current snapshot artifacts reused. |
| skill-assignment.ts: desiredSkills | No SELECT per current
skill/worker; mapping preserves destination collision/size validation. |
| worker-settings.ts: version metadata / overrides | One metadata read
for selected skill IDs, no artifact transfer for hash-only display. |
| source-database.ts: preview cleanup | Existing scoped preview behavior
retained. |
| library snapshot SQL | Full files remain available for preview and
environment reconciliation; no clipping or owner-crossing cache. |

Restart, historical pin and assignment integration coverage is retained.
No regression approval is needed for the final measured implementation.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Secret delivery now claims at most 64 items and durably advances a
fairness cursor. Reconnect replay resets at most 256 rows per
transaction and survives restart. Expiry also uses bounded 256-row SKIP
LOCKED batches.

## Measurement

Three rounds, two warmups and 20 samples each; baseline/current
alternate each sample on one private database with 1,024 saved synthetic
secrets. State is restored outside timing; stable mode VACUUMs
reset/expiry fixtures outside timing.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Poll | 3 → 1 | 8.03 → 3.44 | 1,024 → 64 | 959,493 → 61,441 |
| First reconnect reset batch | 4 → 7 | 30.66 → 13.10 | 1,024 → 321 |
959,495 → 73,244 |
| First expiry batch | 1 → 1 | 83.35 → 34.46 | 1,024 → 256 | 460,801 →
115,201 |

This compares a bounded first batch with the old full operation; it is
not a claim of faster complete replay/expiry drain. Earlier separate
runs had adverse reset p95 (37.35 → 119.80 ms) and were retained during
profiling; atomic claim/cursor work plus interleaved measurements
produced the final comparison above. Churn mode without VACUUM is
available to expose update/index bloat.

## SQL audit

| Statements / path | Verdict |
|---|---|
| secret-deliveries.ts: claim CTE | Cursor and row claim commit in one
statement, SKIP LOCKED, wrap-around fairness; acknowledged state remains
authoritative. |
| resetBatch + worker_secret_replays | Durable cursor, 256-row sweep,
transaction only when replay needs several statements. |
| thread-secrets.ts: secretResult | Replay cursor prevents old receipt
from appearing applied while reconnect reset has not reached it. |
| secretReceipt | Worker/thread/request/revision fence retained. |
| expireSecrets | Owner-scoped 256-row batch; wipes ciphertext before
delivery of removal. |
| 0108–0109 migrations | Durable replay/delivery cursors and performance
indexes; expected list updated. |

Durability/owner tests cover more than one batch, late ACKs, replay
continuation after reopening, fair polling and expiry.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Routine dispatch no longer locks up to 100 bots before slowly enqueueing
each one's routines. It locks one bot per transaction, checks all of its
routines' busy state in one read, and atomically enqueues/advances that
bot before moving on.

## Measurement

Two warmups, 20 samples; 16 bots × 4 routines. Separate contention pass
adds 5 ms enqueue delay and edits the last bot after dispatch starts.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Routine dispatch | 675 → 531 | 395.34 → 324.96 | 272 → 272 | 123,048 →
51,330 |
| Concurrent last-bot edit | Included above; not separately counted |
685.43 → 18.12 | Unchanged mutation | Not separately counted |

## SQL audit

| Statements / path | Verdict |
|---|---|
| bots/routines.ts: due bot claim | One bot lock per transaction, SKIP
LOCKED, bounded dispatch loop. |
| routine busy lookup | One grouped check per bot; no repeated busy
SELECT per routine. |
| bot header reads | Instructions/payload excluded when only dispatch
metadata is needed. |
| enqueue + routine next occurrence | Same transaction and idempotent
occurrence semantics retained. |
| bot lease / routine updates | No lock held on later bots during
earlier enqueue work. |

Routine gRPC and restart tests cover concurrency and occurrence
durability.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

The rebase includes #449's image/draft enqueue behavior. This layer
reuses a narrow `BotTurnKey` type for its three ID-only projections,
keeping botEnqueue within the lint size limit after the combined
changes. This is a type-only adjustment; SQL and runtime behavior are
unchanged.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Move previews used a complete exported bot conversation just to list
reconnectable account names. The preview now fetches only the required
metadata. Move dependency inspection resolves bot/thread headers in two
owner-scoped grouped reads.

## Measurement

Two warmups, 20 samples. One bot has 2,048 additional 4 KiB messages; 32
connectors; inspection covers 16 bots and 8 threads.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bot move preview | 6 → 6 | 272.35 → 4.25 | 4 → 35 | 10,255,669 → 2,345
|
| Inspect 24 dependencies | 24 → 2 | 6.35 → 1.93 | 24 → 24 | 1,624 →
1,602 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| moves-preview.ts: bot preview | Connection-name metadata only; no
conversation export/decode. |
| moves-preview.ts: inspect | Batched bot/thread/project headers; owner
predicate includes side threads. |
| move source/target durability | Export and transfer behavior
unchanged; not measured as a preview optimization. |
| computers/redirects.ts | Separate audit/optimization on the final
redirect layer; not claimed covered by preview changes. |

Real service without transport; inspection response is synthetic. Full
move gRPC tests cover transfer/restart/owner behavior; transport
serialization is not measured.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## CI mirror-list investigation

The original layer-14 head `200edb16` passed the unchanged
repeated-blackhole case 10/10 times (108.06 seconds, clean temp
directory). Dev `618cbd15` at diagnosis passed its ordinary run too. In
CI, every committed worker/project/thread retention assertion passed
before the failing assertion: `awayReason(peer)` was still undefined.

Connection tracking removes the ready transport before awaiting the SQL
presence update. The test waited only for transport disappearance and
then assumed the overview's persisted presence had already changed. A
temporary 100 ms delay before persisting `unreachable` reproduced the
exact assertion on **both dev and layer 14** (4,897 ms and 4,875 ms
respectively). Waiting for both transport readiness and the overview's
actual presence made that same delayed experiment pass (11.53 seconds).
The temporary injected delay is not committed.

The permanent test correction, placed on the bottom layer so every PR
receives it, polls the real overview presence on both disconnect and
recovery. Every poll still checks committed workers, projects, threads
and the 500 ms local-list bound. The linked fixture does not run the
pruning job; active mirror generations remain excluded from pruning. No
production mirror, lease, presence or retention behavior is changed by
this correction. The existing retention/mirror integration tests remain
part of the focused revalidation.

The corrected repeated-blackhole case passed **10/10 rounds in 110.24
seconds**, with a clean temp directory. Focused retention (5), durable
mirrors (20), mirror listing (3), migration/index (28) and bot
composer/routine (17) tests also passed. These focused runs used top
head `1c4f213f`, before the subsequent dev refreshes; the final
top-branch full run is recorded in #447.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Configuration blob retry checks now find missing hashes in SQL before
decoding all configuration fields. Repeated hash references are
deduplicated before validation. Reapplication selects only live waiting
records or records naming newly received content.

## Measurement

Three rounds, two warmups and 20 samples each; 129 configuration records
sharing 64 missing versions, including one waiting record.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Missing-blob lookup | 2 → 1 | 15.15 → 9.46 | 129 → 64 | 1,855,729 →
4,865 |
| Recheck waiting library | 71 → 8 | 144.21 → 12.97 | 130 → 2 |
1,855,994 → 14,568 |

Earlier per-reference validation variants were profiled/rejected;
deduplicating before hash validation avoids repeated work. Transfer is
outside measurement.

## SQL audit

| Statements / path | Verdict |
|---|---|
| environment-blobs.ts | Owner scope, deduplicated/validated hashes,
existence checks across all three library tables; no full config blob
result. |
| environment-sync.ts | Filters waiting or matching-content records in
SQL; marketplace precedes plugin; partial tombstones with fields remain
live. |
| environment-support.ts | Batch hash-presence check avoids
missing-artifact reads per version. |
| content materialization | Existing owner-local content is still hash
verified before use. |

Integration tests cover another owner's hash, malformed/missing content,
shared content across library kinds, tombstones and waiting
dependencies.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Bot MCP listings now read narrow metadata and group grants. Bot model
catalogs filter owner/provider/instance in SQL before decoding profiles,
and configuration validation reads only owned/shared instance model
metadata.

## Measurement

Three rounds, two warmups and 20 samples each; 32 MCP catalogs × 64 KiB;
13 owned and 32 foreign worker catalogs with two irrelevant 64 KiB
profiles and one small matching profile.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bot MCP servers | 65 → 3 | 16.50 → 1.23 | 64 → 64 | 2,113,679 → 16,082
|
| Bot model lookup | 2 → 2 | 17.80 → 0.98 | 46 → 14 | 5,911,811 → 1,258
|

## SQL audit

| Statements / path | Verdict |
|---|---|
| bots/store-access.ts: MCP server list + grants | Metadata projection
and two grouped grants; execution retains authorized full catalog. |
| bots/store-config.ts: catalogs | Worker owner/shared scope and
provider/instance filter precede protobuf decoding; array order
retained. |
| botValidate instance lookup | Requires owner or shared instance and
projects custom_models only. |
| bots/store-bots.ts | Threads the acting owner through catalog lookup.
|

Owner integration coverage includes foreign worker models and foreign
instances; explicitly shared workers remain supported. The independent
ModelStore.catalogs security fix already merged as #426; this layer does
not replace it.

Related: #426

Related: a76a0c1

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Local ConfigSync recording now writes changed rows in batches instead of
allocating a revision and upserting each record separately.
Project/environment and worker lookup maps replace repeated JS array
scans. The same owner clock lock and transaction still cover domain
rows, secrets, tombstones and configuration versions.

## Measurement

Three rounds, two warmups and 20 samples each. ConfigSync.start with 128
instruction documents × 4 KiB, 24 projects and 13 workers. Cold
bootstrap clears only the owner's sync state outside timing; steady
restart retains it.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Cold bootstrap | 400 → 69 | 74.64 → 23.71 | 418 → 248 | 615,045 →
579,364 |
| Steady restart | 60 → 60 | 21.55 → 14.09 | 419 → 419 | 1,304,645 →
1,304,724 |

Small clock-string byte differences are expected; bytes count returned
JSON, not writes. Final round p95: bootstrap 25.17 / 21.71 / 21.85 ms;
restart 15.06 / 12.71 / 14.06 ms.

## SQL audit

| Statements / path | Verdict |
|---|---|
| record-batches.ts: clock UPDATE + config_items UPSERT | One CTE per
≤128 rows / ~512 KiB; exact bigint revision range allocated in SQL and
input order retained. |
| project-writer.ts | Defers changed rows until finish inside existing
transaction; uses local-id map. |
| provider-records.ts / connector-records.ts | Batches only row
persistence; encryption, secret pruning and tombstone/history behavior
retained. |
| worker-records.ts | Bounded persistence and global-id map; caller
retains clock lock. |
| json-batches.ts / import callers | Reuses existing bounded helper
through shared path; import behavior unchanged. |

A focused run exposed JSON.stringify on a database-returned bigint
revision. The final batch explicitly serializes only required values;
SQL owns revisions. The loaded-row regression, revisions above 2^53,
owner isolation, reopening, late-batch rollback, tombstones and
immutable home are tested. **53 focused ConfigSync tests passed** across
seven files.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Move redirect handshake learning performed one local-object lookup, one
durable write and one reference update per notice. It now groups
local-object reads, persists at most 128 distinct IDs per statement and
updates distinct target references together. Identical replay uses the
restored map and does no SQL.

## Measurement

Three rounds, two warmups and 20 samples each; 256 notices, half bots
and half threads, no live local targets. Reset and map loading are
outside timing. Real Redirects service, no transport.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Learn 256 new redirects | 768 → 5 | 2,095.52 → 9.66 | 256 → 256 |
89,984 → 88,712 |
| Repeat handshake | 256 → 0 | 22.54 → 0.22 | 0 → 0 | 512 → 0 |

The first lookup-only experiment still had new-redirect p95 2,133.23 ms
and 514 queries, so it was rejected. EXPLAIN showed tiny individual
lookups/writes (roughly 0.01–0.42 ms); 256 separately committed inserts
dominated the service path. The accepted version groups durable writes
as well. No claim is made for large populated reference tables; the
performance fixture's reference table is empty.

## SQL audit

| Statements / path | Verdict |
|---|---|
| redirects.ts: load | Owner primary-key prefix; full durable redirect
map retained because old IDs still need routing. No age-based deletion.
|
| redirects.ts: local bot/thread lookup | At most two grouped,
owner-scoped UUID lookups; invalid IDs rejected before SQL; uppercase
UUIDs cannot bypass local protection. |
| redirect-records.ts: batch UPSERT | Atomic statement, ≤128 distinct
IDs, timestamp fence retained; returned order follows input. Duplicate
IDs split batches and recheck committed state. |
| redirects.ts: single record | Original one-statement write retained
for isolated notifications. |
| redirect-records.ts: reference UPDATE |
Owner/target/former-home/direction fence; distinct IDs grouped.
Duplicate IDs and a failed bulk reference update preserve ordered
best-effort per-item recovery. |
| redirects.ts: map/rewrite/list | In-memory routing unchanged; no
history/durability pruning. |

Move suite passed seven tests; additional owner/durability tests verify
two owners, local bots/threads, spoofed senders, stale/equal-time
notices, restart and reference isolation. A final regression check also
verifies that uppercase UUIDs retain single-notice deduplication and
routing after reload. No sync transport/client-stream/computer-link
changes overlap the other delegate.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## Remaining across the stack

This is a **ready stack with an incomplete statement-level SQL audit**.
At the previous publication, the static inventory contained **2,177
statement/fragment locations across 311 files**. It includes DDL,
transaction controls, triggers and overlapping/dynamic fragments, so it
is not a count of distinct executable application queries. The
historical diagnostic snapshot on the plan-capture layer matched 380 of
2,171 locations to plan templates; those numbers are not
current-revision or complete large-dataset coverage.

A pre-rebase diagnostic pass on head `3381f50b` ran 22 standard
benchmark operations with `--explain-writes --iterations 1`: 80 plans,
58 unique fingerprints, zero plan errors, zero skipped plans, 64
candidate source locations matched and 16 plans unmatched. There are
2,113 locations without evidence from that revision's pass, including
DDL/controls/dynamic fragments. The fixture used 240 threads, a
2,048-turn long thread, 4 KiB content, large import/command queues and
approximately 201 MiB of database storage. That publication's
post-rebase static inventory had 2,177 locations across 311 files; it
was not refreshed for the latest dev base, and plan matches were not
reassigned across revisions. This refresh does not replace paired
latency evidence or prove execution of every matching call site;
historical and current line matches are not combined.

| Area | Coverage and limitation |
|---|---|
| Imports and polling stores | Progress/admission, notifications, bus
reference reads, worker configuration, worktree activity and secret
metadata have focused fixtures, plans and before/after tables on their
layers. Cold/admin branches and dynamic query variants still need
exhaustive statement-level review and large-dataset evidence. |
| Outbox and secret queues | Bounded reads/claims, TTL, cursor fairness,
replay/reset, timeout, expiry, restart and owner behavior checked. The
outbox's 9.25 → 9.47 ms correctness exception is explicitly
user-approved. |
| Schedules and routines | External preparation moved outside schedule
lock; claims/fencing, concurrent edits, occurrence durability and
grouped routine busy checks measured and tested. |
| Retention | Bounded durable pruning covers eligible mirror
journals/generations, acknowledged terminal harness events, obsolete
command payloads, config history, previews and OAuth state. History,
deduplication keys, user transcripts, import/audit history and necessary
cursors remain intentionally unbounded; further deletion needs an
archival contract. |
| Online indexes | New performance indexes support opt-in concurrent
builds with definition/validity/restart checks. Older transactional
index migrations retain the documented maintenance-window requirement. |
| Concurrent load | Verified running-turn deltas, mirror commits, pool
saturation, sampled locks and statement-timeout rollback. Several SQL
pools are not an end-to-end test of several real gateway processes. |
| Event-loop safety | Cooperative complete-snapshot decoding and reduced
blob reads measured. A single huge item, driver JSON decoding and
transport serialization can still block synchronously. |
| Skills, configuration and moves | Skill pin/version batching,
retry-hash filtering, bot metadata/catalogs, local ConfigSync batches
and move previews/redirects have focused measurements and SQL verdict
tables. Populated large move-reference tables still need a separate
workload. |

The overview scratch-lock fast path was **removed before publication**
because the user's repeated-load criterion rejected its streaming-ingest
regression. The concurrency/overview layer retains the benchmark and all
three before/experimental-after rounds in its Remaining section. No
approval is inferred for that rejected change.

## CI repair and revalidation

Rebased top head: `de19ad424da6601523792908dc1fdef2030c608c`, source
tree `15f769e5b291fdec6665c40170b505e969197fda`, based on dev
`6e5a37188f41381d3d94153d34fa328359d29fe4` (including #429, #449, #450,
#451, #452 and #453). All 18 layers remain **ready**, as requested by
the maintainer. The seven DB2 migrations are now **0103–0109**, in the
layers that introduce them. SQL file contents are byte-identical
renames; schema expectations and Polish docs are updated. The base's
`0102_bot_composer` is preserved, no DB2 index overlaps its
tables/indexes or `turns_composer_choices`, and the retention policy
explicitly preserves bot composer drafts and attachments.

Both CI failures were test synchronization races that also occur on dev,
not demonstrated production regressions in the performance layers. The
slow-read test included roughly 10 seconds of RPC admission wait in its
20-second timeout assertion; the repeated-blackhole test read overview
presence before the asynchronous presence write committed. The corrected
waits live on the bottom layer so every PR receives them. Full
original-head/dev diagnostics, including a controlled 100 ms
presence-write delay that reproduces the exact #443 assertion on both,
are documented in #439 and #443. No diagnostic instrumentation is
committed and no production timeout, mirror, lease or retention behavior
is relaxed. The #442 enqueue type alias keeps the combined #449/routine
changes within the function size limit without changing SQL/runtime
behavior.

Focused validation on prior top `1c4f213f`: **104 pass, 0 fail**,
including three complete timeout-file rounds (21 tests), ten
repeated-blackhole rounds, migration/index tests (28), retention (5),
durable mirrors (20), mirror listing (3) and bot composer/routines (17).
Every temp-directory check passed. Subsequent dev refreshes include
gateway/configuration, protocol, mobile and web changes; this focused
result is historical, and the final top-head full run is recorded
separately below.

On prior head `3baeb92f`, all local gates passed, including a complete
foreground `bun run check:tmp`: **2,022 tests, 163 skips, 0 failures,
24,835 assertions across 367 files in 1,018.18 seconds**, with nothing
left in the checked temp directory.

On final head `de19ad424da6601523792908dc1fdef2030c608c`, `bun install`,
`bun run gen:check`, full `bun run typecheck` (including scripts/tools),
`bun run lint`, `bun run format:check` and the web build all passed. The
complete foreground `bun run check:tmp` passed **2,035 tests, 163 skips,
0 failures, 25,556 assertions across 370 files in 995.54 seconds**. The
temp-directory check passed. Both previously failing scenarios passed in
this run: repeated blackholes in 9,964.81 ms and slow live reads in
32,017.39 ms. The working tree is clean.

Paired latency measurements in the individual layers were not rerun
during this CI repair. Their original methods and limitations remain
documented. Local validation does not replace the full CI gate on
**every** current stack head. CI status after the lease-protected
restack push is recorded separately below, especially for #434, #435,
#442 and #445.

## Current-head CI publication snapshot

After the atomic push with explicit per-branch force-with-lease checks,
all 18 current heads have a CI workflow run (queued or in progress).
None is missing CI, including #434, #435, #442 and #445. The aggregate
`Typecheck, tests, builds` must still pass on every layer before merge;
this snapshot does not claim green CI. All PRs remain ready
(`isDraft=false`), with no approving review recorded. Snapshot:
2026-11-09, approximately 20:05 UTC.

| PR | Head branch | Head SHA | CI workflow |
|---|---|---|---|
| [#430](#430) |
`perf/db2-1-imports` | `6dc7ed8b0f0c795e3d1bb4daaa87805fb68541ec` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689394107)
|
| [#431](#431) |
`perf/db2-2-online-indexes` | `36841847211f8470492b65efc0599453eddea607`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689380806)
|
| [#432](#432) |
`perf/db2-3-schedules` | `f9ba88510c460e5d17dfca76acd96720bf9193f2` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689472854) |
| [#433](#433) |
`perf/db2-4-retention` | `e1c0676cdbfffd6c6bba003a0b3c5b42ef9842e1` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689479073) |
| [#434](#434) |
`perf/db2-5-bounded-reads` | `9ad42f78c85d99f8d3a09fda11ce7fd8de00dbad`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689351696)
|
| [#435](#435) |
`perf/db2-6-overview` | `73cb9fa3bc1a52c1c2c2682562550af51e7b6cf7` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689419982) |
| [#436](#436) |
`perf/db2-7-snapshot-decoding` |
`94185a553b84bdb16cc248bc6e76f74d7f0e1a21` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689406661)
|
| [#437](#437) |
`perf/db2-8-audit-plans` | `dceeb2dcf860aecc4cd988f2036a655d2839d15b` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689403516) |
| [#438](#438) |
`perf/db2-9-config-stores` | `4b8583f43937dea79e4f0a08ac27bd52c3b6970c`
| [queued](https://github.com/itsoltech/canopy/actions/runs/42689486310)
|
| [#439](#439) |
`perf/db2-10-lifecycle` | `b8ce40857b2d878961a014b16b90ad723eb80d4b` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689475177) |
| [#440](#440) |
`perf/db2-11-skill-reads` | `105f47aa7e18ae81850a4ccf1d8b9c0e1a3a790e` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689467700) |
| [#441](#441) |
`perf/db2-12-secret-queues` | `935f16adfa0c8f1d4cf56508851a665cea218ba9`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689394660)
|
| [#442](#442) |
`perf/db2-13-routines` | `4896642250c8962e593d451f0ff5780ef61aee4f` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689403870)
|
| [#443](#443) |
`perf/db2-14-move-previews` | `3e086ff0a89af5a5ead37c02386fddde294ab551`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689374643)
|
| [#444](#444) |
`perf/db2-15-config-blobs` | `59f015d96c6a3cbcc26ba2cf77a7dd350bdd3449`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689369835)
|
| [#445](#445) |
`perf/db2-16-bot-config` | `f612a949d3a833fb320f72805a92d63f3398c96f` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689434187) |
| [#446](#446) |
`perf/db2-17-config-records` |
`2ba4ff15d9d516dba1161d9e25bda66d48be366c` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689485086) |
| [#447](#447) |
`perf/db2-18-redirects` | `de19ad424da6601523792908dc1fdef2030c608c` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689419268) |
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