Repository navigation
perf(threads): validate messages before taking the thread lock - #690
Merged
Merged
Conversation
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
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.
This was referenced Nov 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
SendMessageran every check (thread state, attachments, quotes, mentions, model, permission mode) inside the transaction that holdsFOR UPDATEon the thread row and a pooled connection. The send path now has three steps:NotFound.FOR UPDATEon the thread (a narrow column read, notthreadSelect), 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 itsStartTurn, or/goal, committed together with the receipt.ActionContextand recorded by the existingCommandResulthandlers 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/pumpalready defer to after the commit, and linked sends are forwarded byrouted()beforemessageReceipt. With a worker that answersStartTurnafter 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 =
dev76b5561, 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 UPDATEuntil the end of the transaction body), p50 / p95 ms:CreateThread¹ Old: 0/35 of these turns were dispatched in the admission (the thread was still
creating, so the turn waited forthread_readyand a later pump). New: 35/35. The ~1.5 ms of checks before the lock letsthread_readyland first, soStartTurnis 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 UPDATEissued 0 ms after the send), wait p50 / p95 ms: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: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
threadSelectre-read under the lock is gone.Guarantees and concurrency
turns/turn_steersbyclient_request_id) before the checks and again under the lock. Covered by concurrent identical sends and concurrent identical/goal.steerTarget, queue ordinal). Tests: 6 concurrent sends give ordinals 1–6 with exactly oneStartTurn; 3 concurrent steers all join the running turn.StartTurnin 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.StartTurnis idempotent byturn_id).composer-draftstests pass).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 writeimport_items). Audit of every other input the checks read:UPDATE … WHERE thread_id IS NULLduring admission, under the lock.I kept an explicit key rather than a whole-row version (
xmin): ingest bumpsthreads.last_seqon 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.tsnow find the blocked sender bypg_blocking_pidsinstead 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.dev, the slow-check and race tests fail (lock timeout / the race blocks on the held lock), so they catch the old behaviour.message-receiptsandcomposer-draftstests pass unchanged.Copy audit
No UI text changes. Error messages are unchanged.
Related: #664
Checks (local)
bun install,gen:check,typecheck,lint,format:checkand the web build are clean.check:tmp: 2967 pass, 175 skip, 2 fail. Nothing was left in the temp dir. The 2 failures werethread-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 andmessage-receiptsthen pass. The full suite was not re-run after that commit; CI covers it.