Skip to content

fix: make turn-start queue wake race-safe - #2866

Closed
ymichael wants to merge 2 commits into
mainfrom
bb/fixer-make-turn-starting-queue-wake-race-safe-thr_myiynn4x7p
Closed

ymichael wants to merge 2 commits into
mainfrom
bb/fixer-make-turn-starting-queue-wake-race-safe-thr_myiynn4x7p

Conversation

@ymichael

@ymichael ymichael commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A follow-up message sent at exactly the wrong moment during turn startup could be added after startup's only queue scan. The turn could then finish without ever seeing the message, leaving it queued forever.

The first fix still allowed archive or soft delete to win after an earlier stale read, which could strand the newly queued row on a thread the idle scan deliberately excludes. It also notified the hub while SQLite still held its writer lock.

What changed

  • Make the active-turn recheck, complete writable-thread check, and startup-wait write one immediate SQLite transaction for ordinary sends, queued retries, and parent system notices.
  • Return explicit outcomes from the shared transaction helper so both callers handle state changes consistently.
  • Buffer queue notifications until the outer transaction commits.
  • Let idle draining recover startup-wait rows when turn settlement wins, with one shared wait-kind list for the JavaScript and SQL predicates.
  • Keep the existing queue claim guard, so recovery cannot dispatch a message twice.

No host-daemon wire contract changed, so no protocol bump is required.

How you verified

  • Added ordered regressions for archive and soft delete winning before ordinary queue admission, plus archive winning during parent-notice preparation.
  • Added a regression proving queue notifications happen after the SQLite transaction.
  • Added a direct SQL idle-scan regression for a turn-starting row.
  • Focused server tests: 15/15 passed.
  • Focused DB tests: 31/31 passed.
  • Turbo typechecks for @bb/server and @bb/db, the server build, and git diff --check passed after rebasing onto current origin/main.
  • The complete GitHub CI matrix is green, including server, packages, integration, app shards, and Linux/macOS package smoke.

Follow-up to #2816.

@slopcop

AGENT GENERATED

@bb-slop-cop

bb-slop-cop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am the Slop Cop. I started the security, quality, architecture, performance, and end-to-end reviews.

I will post one final review after I combine the results.

return waitOn({ kind: "turn-starting" }, null);
const outcome = deps.db.transaction(
(tx) => {
const lockedThread = getThread(tx, thread.id);

@bb-slop-cop bb-slop-cop Bot Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This transaction can queue work after an archive or soft delete.

The earlier writable check can race with either action. Both actions can keep the thread status as active.

This read then accepts the thread, and line 344 creates a queue row. The idle scan excludes archived and deleted threads.

The accepted row can remain forever. Please reject non-null archivedAt and deletedAt values inside this transaction.

Please add an ordered race test for each state.

if (
!thread ||
thread.status !== "active" ||
thread.deletedAt !== null ||

@bb-slop-cop bb-slop-cop Bot Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The parent-message transaction still accepts archived threads.

This check rejects a deleted thread, but it does not reject a non-null archivedAt value.

An archive can occur after the first parent read. This transaction can then create a row that the idle scan never selects.

Please reject archived threads here and cover this order in a test.

return waitOn({ kind: "thread-busy" }, null);
}
if (getActiveTurnId({ db: tx }, thread.id) !== null) return null;
return waitOn({ kind: "turn-starting" }, null);

@bb-slop-cop bb-slop-cop Bot Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The queue notification runs while SQLite holds the writer lock.

waitOn() creates or updates the row. It then calls hub.notifyThread() before this outer transaction commits.

The hub performs synchronous validation, socket writes, and listener calls. This work extends the writer lock for all database writes.

Please return the queue result from the locked section. Send notifications after the outer commit.

Plugin handlers do not cause this issue because the plugin service defers them.

@bb-slop-cop bb-slop-cop Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

Plain English summary

This PR fixes a timing fault in the message queue. A message can arrive while the server starts a new turn.

The new database check orders the message and turn writes. The idle scan can also recover a missed wake.

Findings

  1. Blocking: the new checks still accept archived and soft-deleted threads.

    Archive and soft delete can leave the status as active. The transaction can then accept a new turn-starting row.

    The idle scan excludes both states, so the accepted row can remain forever. Both transaction paths need complete writable checks.

  2. Moderate: the dispatch transaction sends a hub notification while it holds SQLite's writer lock.

    The hub performs synchronous socket and listener work. The code should send the notification after the outer commit.

  3. Test gap: the database test covers the JavaScript claim predicate, but it does not cover the changed SQL idle-scan predicate.

    Please add a direct test for listIdleThreadsWithQueuedMessages() with a turn-starting row.

  4. Architecture: two paths repeat the same thread-state and active-turn checks, but their writable checks already differ.

    One transaction helper with explicit results would prevent this drift. A shared wait-kind list would align the JavaScript and SQL predicates.

Checks

  • The focused server tests passed: 12 tests.
  • The focused database tests passed: 30 tests.
  • The server and database type checks passed.
  • git diff --check passed.
  • The security review found no issue.
  • A Doobie browser smoke test passed against the development app after its first build.

The focused tests use mocked stale reads. They do not run a real two-connection race.

I did not reproduce the timing fault through the browser because the browser cannot control this database order.

This PR needs changes before merge. I posted this as a comment and did not set a GitHub review state.

@ymichael
ymichael force-pushed the bb/fixer-make-turn-starting-queue-wake-race-safe-thr_myiynn4x7p branch from 1dd80a1 to 5c3fc7d Compare September 1, 2026 23:37
@ymichael

ymichael commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@slopcop Review findings are addressed at 5c3fc7d, including the ordered archive/delete regressions, post-commit notification assertion, direct SQL idle-scan test, and shared transaction helper. CI is green.

@bb-slop-cop

bb-slop-cop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am the SlopCop. I started a security, code quality, performance, architecture, and product-path review of this pull request.

? getActiveTurnId({ db: tx }, args.threadId) === null
? { kind: "turn-starting" as const }
: null
: args.fallbackWaitingOn;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The fallback also handles an error state.

The thread can change from active to error between the first check and this transaction. This path then writes a thread-busy wait. The idle sweep excludes error threads, so the row can remain indefinitely. An explicit steer also loses its required error response. A steer-if-active request loses its recovery start.

Return thread-changed for each non-active state. Then repeat dispatch with the current thread and a bounded retry. Add ordered race tests for both modes.

or(
isNull(queuedThreadMessages.waitingOn),
sql`json_extract(${queuedThreadMessages.waitingOn}, '$.kind') = 'thread-busy'`,
...IDLE_DRAINABLE_WAIT_KINDS.map(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This loop extracts the same JSON value once for each wait kind.

The queue sweep runs every ten seconds. A 200,000-row check increased from 17.36 ms to 25.44 ms with this form. One IN expression measured 19.31 ms.

Use one json_extract expression with IN and IDLE_DRAINABLE_WAIT_KINDS. This is a small, non-blocking improvement.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

Plain English summary: This change closes a race during a new turn. A follow-up could enter the queue after the wake scan. Nothing would then wake that message. The change checks the current thread state and updates the queue in one database transaction. It also lets the idle sweep recover turn-starting rows.

I found one blocking correctness issue and one small performance issue.

  • P1: An active thread can change to error before the locked check. The helper writes a thread-busy wait for that error state. The idle sweep excludes error threads, so the message can remain indefinitely. This also changes the behavior of steer and steer-if-active. The inline comment gives the required fix and test cases.

  • P3: The idle sweep repeats json_extract for each allowed wait kind. One IN expression avoids that repeated work. The inline comment includes the benchmark results.

The security review found no issue. The architecture search found no new duplicate queue path. One duplicate queue-changed notice already exists on main, so this pull request did not create it.

Validation completed:

  • The focused server test passed all 15 tests.
  • The focused database test passed all 31 tests.
  • Turbo type checks passed for @bb/server and @bb/db.
  • git diff --check passed.
  • All GitHub checks passed or skipped as expected.
  • A live dev test created a Codex thread and sent an immediate steer. The thread reached idle with zero queued messages. Doobie showed the SECOND response in the product UI.

The live test covers the normal path. It does not cover the active to error race.

ymichael added a commit that referenced this pull request Sep 2, 2026
## Human comments

## What was wrong

Queued-message readiness was decided independently by startup events,
idle sweeps, plugin/timer drains, failed-row handling, and manual Stop
handling. Each fix could pass alone while their predicates disagreed
when composed: a settled `turn-starting` row could be discovered but
rejected, a failed grouped sibling could ride with a healthy row, and a
stale runtime event or in-flight hook could cross a manual Stop. Startup
admission also trusted a stale active thread after it changed to error,
which could strand a row or change `steer` semantics.

## What changed

- Made startup admission atomic: it either queues against the
still-active startup or retries once from the current thread state.
- Centralized automatic whole-group readiness across plugin, time,
`thread-busy`, and `turn-starting` waits.
- Replaced the positional `sendNow`/optional-callback claim API with an
explicit `automatic` versus `explicit-send` policy.
- Enforced failed-row exclusion and manual-Stop pause inside the group
claim transaction. Explicit Send now remains the override; independent
scheduled, plugin-held, and system-notice rows remain drainable.
- Required a post-Stop client request before a later root turn can clear
the pause, and rechecked the pause at final dispatch consumption.
- Used one SQL `IN` predicate for idle-drainable wait kinds.

This supersedes #2866 and #2867 and includes the failed-group and
Stop-boundary follow-ups. There is no host-daemon wire, schema, CLI,
SDK, migration, or documentation contract change.

## How you verified

- Added deterministic regressions for the settled-startup lost wake,
mixed-wait groups, failed grouped siblings, stale post-Stop starts,
hook-held Stop races, and active-to-error startup admission for both
`steer` modes.
- Focused Turbo server matrix: 70/70 passed.
- Focused Turbo DB/query-plan matrix: 68/68 passed.
- Standalone production-path Stop race harness: both races passed.
- Full DB suite: 444/444 passed.
- Full server suite: 2,131 passed; 10 unrelated `install-machine-script`
tests failed because their fake host daemon did not connect.
- `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db`
passed.
- `pnpm exec turbo run build --filter=@bb/server` passed.
- `git diff --check` passed.

> AGENT GENERATED
@ymichael

ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #2884, which combines this startup-race fix with unified group readiness, failed-group admission, manual-Stop boundaries, and the active-to-error review follow-up. #2884 passed the complete CI matrix and has been merged.

@ymichael ymichael closed this Sep 2, 2026
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