Repository navigation
Conversation
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: A delivery truck sent the same “start” card twice. This change keeps the first card and ignores the copy.
I found no actionable issues.
The database now treats (threadId, turnId) as the stable turn identity. It skips only a repeated turn/started event. It still rejects turn content that arrives before a start.
The timeline also tolerates old duplicate data. It keeps the first start and builds one turn. The server can still repair lifecycle effects after an uncertain response.
The security review found no new access or data exposure risk. The performance review found that the lookup uses the existing covering index. A 50,000-row check measured about 4.8 ms for 250 keys.
I scanned the codebase for duplicate logic and a smaller architecture. The database check and timeline fallback cover different failure periods. I found no useful refactor for this change.
The focused database test passed. The two focused server tests passed. The 72 focused timeline tests passed. The browser test received HTTP 200 and one completed turn from a duplicate-start fixture.
All GitHub checks pass. The final GPT-5.6 review gate returned APPROVE.
One old limit remains. A retry can still store duplicate non-start events. This pull request does not add that behavior.
## What was wrong The host daemon delivers event batches at least once. `apps/host-daemon/src/event-sink.ts` keeps the whole queue on any non-permanent post failure and reposts it on the next flush. When the server had already committed the batch but the acknowledgement was lost (gateway 502/504, dropped connection), the repost carried the same `turn/started` with the same provider turn id. `appendDaemonEventsInTransaction` in `packages/db/src/data/events.ts` assigned every insert a fresh event id and sequence and never checked whether a `turn/started` for that `(threadId, turnId)` was already stored, so the replay persisted a second start. `groupEventProjectionTurns` in `packages/thread-view` requires one start per turn and threw `Timeline projection found duplicate turn/started`, so `GET /api/v1/threads/:id/timeline` answered 500 for a thread whose events were intact. Issue: #1839. The linked report URL (https://get-bb.github.io/reports/issues/1839.html) returns 404; this PR reproduces the bug from the issue's own steps. ## What changed - `packages/db/src/data/events.ts`: ingestion now includes `turn/started` inputs in the stored-turn-start lookup and skips a `turn/started` whose `(threadId, turnId)` is already stored (or was already appended earlier in the same batch). This mirrors the terminal-item dedup that already lives in the same transaction. A provider turn starts exactly once (the daemon-side `ThreadEventGrammar` enforces `turnStartsOnce`), so a repeated start is a delivery replay, not a new turn. Skipped starts are not reported in `acceptedEvents`; the daemon already treats a 200 as full delivery, and `shouldApplyEventEffect` in `apps/server/src/internal/events.ts` already re-applies `turn/started` effects for non-inserted events, so a replay still repairs thread status. - `packages/thread-view/src/group-event-projection-turns.ts`: a second `turn/started` for a turn already in the projection is ignored instead of throwing, so histories persisted before this change stay readable. The first start is canonical. - No wire change. `HOST_DAEMON_PROTOCOL_VERSION` is unchanged: the request and response shapes of `/session/events` are the same; only which inputs are inserted differs. Other replayed event types keep their current behavior (a replayed `turn/completed` is still stored twice; projection already tolerates that). This is not a general exactly-once delivery change. Relation to #1560: that PR takes the same approach but is based on `a83c12946` and now conflicts with `main` (the terminal-item dedup landed in the same function). This PR applies the fix on current `main`, keeps the `turn/started`-in-batch-twice case covered, and extends the existing replay route test to assert both the stored event types and the timeline route. ## How you verified New or updated tests, each run with the source files checked out from `origin/main` (fail) and on this branch (pass): - `packages/db/test/data/events.test.ts` - `skips turn/started when a daemon replays an already-committed batch` — before: `AssertionError: expected { …(3) } to deeply equal { acceptedEvents: [ { …(2) } ], …(2) }` (replay inserted index 0 as sequence 3 and the completion as 4) - `skips a turn/started repeated inside one daemon batch` — before: `AssertionError: expected [ +0, 1 ] to deeply equal [ +0 ]` - `apps/server/test/internal/internal-events-tool-calls.test.ts` - `keeps a thread idle when a started/completed batch is posted again` now asserts stored types are `["turn/started", "turn/completed", "turn/completed"]` and that the timeline route returns 200 — before: `AssertionError: expected [ 'turn/started', …(3) ] to deeply equal [ 'turn/started', …(2) ]` - `apps/server/test/public/public-thread-data.test.ts` - `returns a timeline when a stored history holds a duplicate turn/started from a daemon replay` — before: `AssertionError: expected 500 to be 200` - `packages/thread-view/test/build-thread-timeline.test.ts` - `renders one turn when daemon retry history contains duplicate turn starts` — before: `Error: Timeline projection found duplicate turn/started for turn-1` Commands: - `pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/thread-view --filter=@bb/server` — pass - `pnpm exec turbo run test --filter=@bb/db --filter=@bb/thread-view --force` — 408 and 380 tests pass - `pnpm exec turbo run test --filter=@bb/server --filter=@bb/client-core --filter=@bb/cli --force` — client-core 238 pass; server and cli hit 5s vitest timeouts under a load average above 40 on this shared machine, so I re-ran the timed-out server files in isolation: 383 pass, with the one remaining failure being the known local umask 0002 mismatch in `internal-skill-trees.test.ts` (0644 vs 0664), unrelated to this change Manual check: a lost acknowledgement between daemon and server cannot be forced through the dev app without a fault-injecting proxy, so the route-level test that posts the identical batch twice through the real `/session/events` route and then reads the timeline is the faithful equivalent. Fixes #1839 > AGENT GENERATED: by Claude Opus 5 ## Independent verification Verified on a fresh worktree at `d7de9e5c3` (branch `bb/fix-1839-duplicate-turn-started`; `origin/main` = `c9aef7514` is an ancestor; GitHub reports `MERGEABLE`). Own root-cause read before reading this PR: `apps/host-daemon/src/event-sink.ts` `deliverBatch` returns 0 on any non-permanent post failure, so a batch the server committed but whose response was lost is reposted verbatim; on main `collectDaemonTurnStartLookupKeys` skipped `turn/started` inputs and `resolveDaemonTurnStartDisposition` returned `append` for every `turn/started`, so the replay stored a second start; `groupEventProjectionTurns` threw on it. The fix is at the right layer (server-owned ingestion policy in `@bb/db`; no daemon or wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump is needed). `shouldApplyEventEffect` in `apps/server/src/internal/events.ts` already re-applies `turn/started` effects for non-inserted inputs, so thread status is still repaired on replay. The daemon grammar (`turnStartsOnce`) and the per-assembler random turn-id prefix (`delta-assembler.ts` `mintTurnId`) mean a repeated `(threadId, turnId)` start is a replay, not a new turn. Fail-before (`git checkout origin/main -- packages/db/src/data/events.ts packages/thread-view/src/group-event-projection-turns.ts`, tests from the branch): - `@bb/db` `skips turn/started when a daemon replays an already-committed batch`: `AssertionError: expected { …(3) } to deeply equal { acceptedEvents: [ { …(2) } ], …(2) }` - `@bb/db` `skips a turn/started repeated inside one daemon batch`: `AssertionError: expected [ +0, 1 ] to deeply equal [ +0 ]` - `@bb/thread-view` `renders one turn when daemon retry history contains duplicate turn starts`: `Error: Timeline projection found duplicate turn/started for turn-1` - `@bb/server` `keeps a thread idle when a started/completed batch is posted again`: `AssertionError: expected [ 'turn/started', …(3) ] to deeply equal [ 'turn/started', …(2) ]` - `@bb/server` `returns a timeline when a stored history holds a duplicate turn/started from a daemon replay`: `AssertionError: expected 500 to be 200` Pass-after (`git checkout HEAD -- <same files>`): all five pass. Commands: - `pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/thread-view --filter=@bb/server --filter=@bb/client-core`: pass - `pnpm exec turbo run test --filter=@bb/db --filter=@bb/thread-view --filter=@bb/client-core --force`: 408 / 380 / 238 pass - `pnpm exec turbo run test --filter=@bb/server --force`: 1819 pass, 1 fail (`internal-skill-trees.test.ts` mode 420 vs 436, the known local umask 0002 mismatch; passes in CI) Repro on the fixed branch: the issue's own reproduction (two stored `turn/started` rows for one `(threadId, turnId)`, then `GET /api/v1/threads/:id/timeline`) is exactly the `public-thread-data` route test; it returns 500 with main's sources and 200 on this branch. The replay path through the real `/session/events` route stores `[turn/started, turn/completed, turn/completed]` and the timeline returns 200. A lost daemon-to-server acknowledgement cannot be forced on a live dev instance without a fault-injecting proxy, so no dev instance was started. CI: all test jobs, Package Smoke, and "Build, typecheck, and lint" pass. The `Checks` job is red only on its last step, `Check Actions cache usage`, which timed out connecting to `api.github.com` (infra, unrelated). Residual risks: a skipped duplicate start is not logged (the orphan-snapshot skip is); replayed non-start events such as `turn/completed` are still stored twice, as on main, and projection tolerates that. > AGENT GENERATED: by Claude Opus 5 Co-authored-by: Claude <[email protected]>
|
This is an automated message. We have closed this pull request because it has been open for more than two weeks. |
Summary
turn/startedevents after daemon delivery retriesRoot cause
The host-to-server event channel is intentionally at-least-once, but daemon event ingestion was not idempotent for
turn/started:turn/startedwithout checking the semantic identity(threadId, turnId).The observed incident matched this mechanism: repeated gateway 502/504 responses were followed by repeated lifecycle rows with the same stable turn and item IDs at later server sequences. That proves the daemon replayed an already-accepted batch; the provider did not create distinct turns.
Fix boundary
This PR restores the invariant at both relevant boundaries:
(threadId, turnId)as the identity ofturn/startedand skips a replay when that start is already storedThis is deliberately not a general exactly-once event-delivery redesign. Other replayed event types retain their existing behavior. General batch idempotency would require a stable daemon delivery identity and a broader persistence contract; it is not necessary to stop duplicate turn starts from making timelines unreadable.
Reproduce the bug locally
This repro uses only synthetic test data. It does not require access to a production database, user account, or affected thread.
From a checkout of this PR:
The regression fixture inserts two
turn/startedrows with the same turn ID, then requests the public timeline route. The unfixed parent commit fails with:Clean up the disposable worktree:
Verify the fix
On this PR's head:
Expected result: the route returns 200, the test passes, and the timeline contains one canonical turn.
Behavior after this PR
turn/startedevents are ignored at ingestion, preventing new projection-breaking histories.Verification
a83c12946: route regression fails withexpected 500 to be 200@bb/thread-viewtimeline test file: 72 passed@bb/dbevents test file: 79 passed@bb/serverpublic thread data test file: 75 passed@bb/serverinternal event/tool-call test file: 25 passed@bb/db,@bb/thread-view, and@bb/serverpassedFixes #1839
BB-Thread-ID: thr_tq4bctwps7