Skip to content

perf(threads): validate messages before taking the thread lock - #690

Merged
nixuuu merged 3 commits into
devfrom
perf/thread-send-short-transactions
Nov 14, 2026
Merged

nixuuu merged 3 commits into
devfrom
perf/thread-send-short-transactions

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

What

SendMessage ran every check (thread state, attachments, quotes, mentions, model, permission mode) inside the transaction that holds FOR UPDATE on the thread row and a pooled connection. The send path now has three steps:

  1. Checks without a lock: read-only. A failed check still replays a stored receipt first, so a retry to a thread archived since admission returns its admission, and another owner still gets NotFound.
  2. Short admission transaction: FOR UPDATE on the thread (a narrow column read, not threadSelect), then one separate state statement (its snapshot follows the lock, so it sees other tables committed while it waited): the receipt, plus every input the checks read that a writer changes under this thread's lock. That is archived/deleted, rewind, worker, cwd, provider/profile, model, pull_request_revision (PR citations), import mode and import in progress. Native dedupe also runs again here. If anything changed, the checks run again under the lock. Then the steer, the queued turn plus its StartTurn, or /goal, committed together with the receipt.
  3. Delivery after commit: unchanged. Worker commands, pump and publishing are deferred by ActionContext and recorded by the existing CommandResult handlers in their own short transactions.

Docs: docs/threads.md § "Przyjęcie wiadomości".

The premise, measured

Worker and linked round trips were not inside the transaction. coreDispatch/coreDeliver/pump already defer to after the commit, and linked sends are forwarded by routed() before messageReceipt. With a worker that answers StartTurn after 500 ms, the old transaction still took ~5 ms. What the lock covered was the check reads. They are fast normally, but any slow one blocked every write to the thread, and every concurrent send waited behind it holding a connection. So this PR moves the checks out and keeps the admission atomic. No new intermediate durable state was needed: step 2 is still one transaction, and step 3 was already outbox-based.

Numbers

Local Postgres via the test gateway, scripted worker, same host, old = dev 76b5561, new = this branch. 30–40 sends per row after 5 warm-ups. The host was shared with other agents, so the p95s are noisy.

Thread row lock hold per send (from FOR UPDATE until the end of the transaction body), p50 / p95 ms:

case old new
steer into a running turn 3.99 / 7.31 2.89 / 4.14
queue behind a running turn 3.16 / 7.85 2.18 / 5.26
first message to an idle (ready) thread 4.38 / 6.44 3.95 / 10.41
first message right after CreateThread 3.84 / 8.58 5.22 / 11.48 ¹

¹ Old: 0/35 of these turns were dispatched in the admission (the thread was still creating, so the turn waited for thread_ready and a later pump). New: 35/35. The ~1.5 ms of checks before the lock lets thread_ready land first, so StartTurn is built under the lock and the turn starts without waiting for the pump. More work under the lock, earlier start.

Another write to the same thread (SELECT … FOR UPDATE issued 0 ms after the send), wait p50 / p95 ms:

case old new
idle 3.48 / 4.84 0.76 / 1.00
steer 5.28 / 8.76 0.70 / 1.56
queue 4.21 / 9.96 0.68 / 1.42

Pool usage with slow checks: N sends to one thread with their checks held open (the attachment-limits read paused), then another write to the thread with lock_timeout=1s:

paused sends old: connections in a transaction old: other write new: connections in a transaction new: other write
1 2 lock timeout (1 s) 0 ok, 2.1 ms
4 5 lock timeout 0 ok, 1.8 ms
8 9 lock timeout 0 ok, 2.3 ms

Old: only the first send reached its checks; the others queued on the lock. New: all N check in parallel.

Slow linked sends: on the sending computer nothing changes (it never held a transaction across the forward; the drafts path already verifies this). On the home computer, the linked-send test shows 4 concurrent paused sends hold 0 connections on either computer, and the home thread stays writable.

Send latency, p50 / p95 ms: steer 5.09 / 8.55 → 5.11 / 9.93; queue 4.66 / 10.15 → 4.72 / 10.40; idle ready thread 6.23 / 8.69 → 6.51 / 14.04. A burst of 8 concurrent sends to one running thread: wall time p50 33.3 → 26.7 ms. Single-send latency is unchanged within noise. The steps add one indexed lock query, but the full threadSelect re-read under the lock is gone.

Guarantees and concurrency

  • Idempotency: receipt under the lock in its own statement, plus native dedupe (turns/turn_steers by client_request_id) before the checks and again under the lock. Covered by concurrent identical sends and concurrent identical /goal.
  • Order and "turn already running": decided under the lock (steerTarget, queue ordinal). Tests: 6 concurrent sends give ordinals 1–6 with exactly one StartTurn; 3 concurrent steers all join the running turn.
  • Archive, delete or rewind committed while the checks run: admission sees the changed state under the lock, validates again, and refuses. One test per case.
  • Crash safety: admission, StartTurn in the outbox and the receipt commit in one transaction. A failed receipt write leaves no turn and no command, and a retry admits once. A gateway restart between admission and delivery delivers the turn exactly once, and the same request replays the same turn.
  • Worker reconnect: unchanged outbox redelivery (StartTurn is idempotent by turn_id).
  • Drafts reconcile: unchanged. Receipts and native rows are written as before (composer-drafts tests pass).
  • Callers with their own transaction (bot actions, linked agent calls) still run every step inside it.

Review fix: inputs outside the thread row

PR citations were not revalidated after a concurrent unlink. The key now includes pull_request_revision, which every link, unlink and repository-account change bumps. It also includes whether an import is in progress (import transactions lock the thread but write import_items). Audit of every other input the checks read:

  • Attachments: bound by a conditional UPDATE … WHERE thread_id IS NULL during admission, under the lock.
  • Quote-source threads, mention targets, model catalogs, worker capabilities, the full-access check: their writers never locked this thread's row, so the send's ordering against them is the same as before.

I kept an explicit key rather than a whole-row version (xmin): ingest bumps threads.last_seq on every event batch, so steers during a running turn would revalidate under the lock almost every time.

New test: github-citations.test.ts › an unlink that commits while a checked citation waits for admission refuses the message. It fails on the previous head (the message was accepted) and passes now.

The lock-ordering tests in thread-range-send-locks.test.ts now find the blocked sender by pg_blocking_pids instead of its SQL text.

Tests

  • tests/integration/message-admission.test.ts: slow checks hold no lock or connection; archive/delete/rewind races; concurrent queue/steer ordering; concurrent /goal; receipt failure rollback; restart between admission and delivery.
  • tests/integration/message-admission-linked.test.ts: 4 slow linked sends A→B; no held connection on A or B; the home thread stays writable.
  • Against dev, the slow-check and race tests fail (lock timeout / the race blocks on the held lock), so they catch the old behaviour.
  • Existing message-receipts and composer-drafts tests pass unchanged.

Copy audit

No UI text changes. Error messages are unchanged.

Related: #664

Checks (local)

bun install, gen:check, typecheck, lint, format:check and the web build are clean. check:tmp: 2967 pass, 175 skip, 2 fail. Nothing was left in the temp dir. The 2 failures were thread-range-send-locks.test.ts, which finds the blocked sender by the lock query's SQL text (AND owner_user_id=). The second commit restores that query shape; both tests and message-receipts then pass. The full suite was not re-run after that commit; CI covers it.

SendMessage ran every check (attachments, quotes, mentions, model,
thread state) inside the transaction that holds the thread row lock
and a pooled connection. Checks now run first without a lock. One
short transaction then locks the thread, re-checks the receipt and the
thread state the checks depended on (validating again under the lock
if anything changed), and commits the admission with its receipt.
Worker delivery and the pump still follow the commit.

Related: #664
Admission compared only the thread columns, so a pull request unlinked
while a send waited for the lock let a cached citation through. The
key now includes pull_request_revision and whether an import is in
progress, and the state is read in its own statement after the lock so
it sees other tables committed meanwhile. Lock-order tests find the
blocked sender by pg_blocking_pids instead of its SQL text.
@nixuuu
nixuuu merged commit e7b11f4 into dev Nov 14, 2026
10 checks passed
@nixuuu
nixuuu deleted the perf/thread-send-short-transactions branch November 14, 2026 05:28
nixuuu added a commit that referenced this pull request Nov 14, 2026
When a connector notice arrives before the provider echoes a message,
the web/desktop feed replaces the turn-input placeholder at the echo's
later sequence position. Its entire work fold can then appear above the
user's message, including messages with attachments.

Place the echoed input immediately after its turn's start, before its
work. Keep the echo's item identity and the sequence positions of
steers, background work and notices. The same derivation repairs
existing saved histories after reload. Inputs containing only
attachments or quotes also retain their placeholder while their echo is
unavailable.

Gateway inspection confirmed that admission already persists the input
and binds attachments atomically before dispatch; the draft path uses
that same admission. Event `seq` correctly records arrival order and
remains unchanged. Mobile already renders the persisted turn input
before its body and excludes the initial echo from that body.

The bug reproduces on current dev, including #673, #687, #689, #690 and
the merged drafts stack. #670 introduced the connector acknowledgement
before Codex `turn/start`, exposing the timeline's assumption that the
input echo was the first element. #672 retained that assumption.

Fixes: #670

Validation:

- Added PostgreSQL/gRPC gateway regression: upload a PNG and Markdown
file, send the message, publish an early connector notice and
commentary, then publish the input echo. The test failed on the original
dev feed (input row 3, work row 1).
- Covers echoes with and without client IDs, placeholder replacement,
open/closed work folds, steer chronology, completion, a fresh sequenced
history subscription, and the mobile turn/body derivation. Both new
cases and 27 existing feed checks pass under `check:tmp`; nothing
remains in the test temp directory.
- `nice` install, `gen:check`, typecheck, lint, `format:check` and web
build pass with temp files under `/var/tmp`. Full suite left to CI
because the shared 12-CPU host reached load 12.41 during verification.
- No browser/device visual run; the change affects timeline derivation,
with no component, styling or UI-copy changes. Copy audit: no changed UI
text.
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