Skip to content

perf(db): batch import admission writes - #407

Merged
nixuuu merged 1 commit into
perf/db-3-thread-readsfrom
perf/db-4-batch-writes
Nov 9, 2026
Merged

nixuuu merged 1 commit into
perf/db-3-thread-readsfrom
perf/db-4-batch-writes

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Fresh import admission and library rows use typed JSON batches instead of one INSERT per item. Each batch targets at most 128 records or approximately 512 KiB; one already-validated large record may exceed the byte target. Bigint byte counts remain exact decimal strings.

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

Measurement

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

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

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

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

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

Validation

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

Remaining database work

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

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

Polish docs describe harness usage, indexes, import batching and retention constraints. No UI text changed; copy audit does not apply. Keep all four PRs as drafts.

@nixuuu
nixuuu added this pull request to stack #408 November 9, 2026 13:05
@nixuuu
nixuuu force-pushed the perf/db-4-batch-writes branch from 82d71e6 to 0084e96 Compare November 9, 2026 13:18
@nixuuu
nixuuu force-pushed the perf/db-4-batch-writes branch 2 times, most recently from 452293f to 78a160c Compare November 9, 2026 13:46
@nixuuu nixuuu changed the title perf(db): batch import admission and scratch provisioning perf(db): batch import admission writes Nov 9, 2026
@nixuuu
nixuuu force-pushed the perf/db-4-batch-writes branch from 78a160c to 98a9c04 Compare November 9, 2026 14:02
@nixuuu
nixuuu marked this pull request as ready for review November 9, 2026 14:04
@nixuuu
nixuuu merged commit 4dfb2f8 into dev Nov 9, 2026
20 of 25 checks passed
@nixuuu
nixuuu deleted the perf/db-4-batch-writes branch November 9, 2026 14:16
nixuuu added a commit that referenced this pull request Nov 9, 2026
Adds an opt-in synthetic PostgreSQL 18 benchmark for gateway stores, an
SQL inventory, sanitized EXPLAIN diagnostics and Polish usage
documentation. It reuses production Effect SQL services without enabling
tracing in the application.

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

## Baseline and measurement

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

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

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

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

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

## Coverage and validation

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

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

Next coverage should add concurrent mixed load, populated update
fixtures, many large mirrors, side-thread previews and attachment/import
payload scaling. No UI text changed; copy audit does not apply. Keep the
entire stack as drafts.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Adds **0100_history_read_indexes** for unseen turns, selected-turn
items, latest side-thread answers and notices. It preserves
transcript/durability rows and adds no retention policy.

This builds on dev **c9b57c42**. Existing migrations 0097–0099 remain
unchanged. The activity index already supplied by 0098 is reused, with
no duplicate index. Migration registry, expected schema list, index
tests and Polish documentation are updated.

## Measurement

Before: current-dev benchmark layer (#404). After: this index layer
only. Both use `bun scripts/bench/db.ts --run --explain`, PostgreSQL
18.6, identical 240-thread/2,048-turn/4,096-byte fixtures, two warmups
and 20 serial samples.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| Sidebar threads | 1 → 1 | 12.8 → 9.7 | 240 → 240 | 847,006 → 847,006 |
| Full thread open | 7 → 7 | 56.4 → 55.0 | 4,162 → 4,162 | 11,544,594 →
11,544,594 |
| Paged thread open | 10 → 10 | 29.8 → 25.8 | 107 → 107 | 135,392 →
135,392 |
| Earlier history page | 10 → 10 | 26.9 → 23.0 | 107 → 107 | 135,392 →
135,392 |

EXPLAIN captures the new unseen, per-turn item and notice indexes in
these reads. The latest-answer index targets the existing side-thread
preview query; the default fixture has no side threads, so this table
makes no isolated latency claim for that index. All new indexes are
checked for validity/idempotent migration. Shared-host latency varies;
returned JSON bytes are not wire/disk I/O or scanned-row counts. Counts
include transaction controls.

## Rollout and validation

- Migration/schema/populated-upgrade checks passed (26 tests). The
existing 0098 migration flushes deferred constraint events before index
DDL in a multi-migration upgrade; this layer does not change that
policy.
- The transactional migrator cannot use `CREATE INDEX CONCURRENTLY`.
These index builds block table writes; large server databases need a
maintenance window. Online index migration support remains separate
work.
- Indexes add storage and write cost. Number 0100 is highest dev
migration + 1; renumber if another migration lands before this one.
- Current-dev focused integration checks and every required top-branch
check passed. Foreground check:tmp: 1,914 pass, 161 skip, 0 fail across
342 files, with nothing left in its temp directory. Install, gen:check,
typecheck, lint, format:check and web build also passed; details are in
#407.

No UI text changed; copy audit does not apply. Keep every PR in the
stack as a draft.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Title search ranks narrow headers first, then fetches the existing
projected UI metadata for at most 50 matches. Repeated mark-seen
requests combine owner validation and monotonic checkpoint persistence
in one statement. The history item read applies fork/page predicates
before sorting content.

This preserves dev c9b57c4's bounded turn-ID window, background-task
visibility, metadata projections and activity index. It does not replace
the history-window or project-list implementations from #401. Full
snapshots and explicit target/from-turn windows retain their existing
range; both search reads remain owner/visibility scoped.

## Measurement

Before: index layer (#405). After: this read layer. Identical `bun
scripts/bench/db.ts --run --explain` runs: PostgreSQL 18.6, 240 threads,
2,048-turn long thread, 4,096-byte texts, two warmups, 20 serial
samples.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| Paged thread open | 10 → 10 | 25.8 → 22.0 | 107 → 107 | 135,392 →
135,392 |
| Earlier history page | 10 → 10 | 23.0 → 22.5 | 107 → 107 | 135,392 →
135,392 |
| Title search | 1 → 2 | 1,162.7 → 97.3 | 240 → 260 | 844,938 → 98,080 |
| Mark seen (repeated checkpoint) | 2 → 1 | 1.6 → 1.6 | 1 → 1 | 49 → 32
|

Search returns additional narrow candidate rows while avoiding rich
metadata and UI conversion for nonmatches. Candidate title headers still
span the owner's active threads to preserve fuzzy ranking. The existing
activity index supplies one row per candidate.

The paged item query's representative EXPLAIN execution fell from 3.371
to 0.934 ms; top-level shared hits were 377/367 and both returned 84
item rows. Total page row/byte counts are already bounded by #401 and
remain unchanged here. EXPLAIN is separate from latency samples. Counts
include transaction controls; bytes are decoded JSON, not wire or disk
I/O. Shared-host latency varies and is not an SLO.

## Validation and limits

Focused migration, history/background/fork/restart/linked passthrough,
search ranking/owner/archive/exclusion, read-marker and existing #401
read-cost tests passed on current dev. All required top-branch checks
passed: install, gen:check, typecheck, lint, format:check, web build and
foreground check:tmp (1,914 pass, 161 skip, 0 fail across 342 files,
with nothing left in its temp directory). Details are in #407.

Full snapshots, explicit restored windows and persistent background-task
rows can still be large. No mirror schema/listing, sync protocol,
project reconciliation or new retention changes are included. Polish
docs explain the read behavior. No UI text changed; copy audit does not
apply. Keep the entire stack as drafts.
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