Skip to content

perf(db): index worktree activity and expired command reads - #439

Merged
nixuuu merged 1 commit into
perf/db2-9-config-storesfrom
perf/db2-10-lifecycle
Nov 9, 2026
Merged

nixuuu merged 1 commit into
perf/db2-9-config-storesfrom
perf/db2-10-lifecycle

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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
nixuuu added this pull request to stack #448 November 9, 2026 18:23
@nixuuu
nixuuu marked this pull request as ready for review November 9, 2026 18:30
@nixuuu
nixuuu force-pushed the perf/db2-10-lifecycle branch from e7e27bb to b8ce408 Compare November 9, 2026 20:02
@nixuuu
nixuuu merged commit 37d9c29 into dev Nov 9, 2026
10 checks passed
@nixuuu
nixuuu deleted the perf/db2-10-lifecycle branch November 9, 2026 20:31
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
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