Skip to content

Handle retried turn starts in timelines - #1560

Closed
brsbl wants to merge 2 commits into
mainfrom
bb/fix-duplicate-turn-timeline-thr_tq4bctwps7
Closed

brsbl wants to merge 2 commits into
mainfrom
bb/fix-duplicate-turn-timeline-thr_tq4bctwps7

Conversation

@brsbl

@brsbl brsbl commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • tolerate legacy timeline histories containing duplicate turn/started events after daemon delivery retries
  • prevent future retries from persisting the same turn start twice
  • cover the ingestion, projection, and public timeline route paths with regressions

Root cause

The host-to-server event channel is intentionally at-least-once, but daemon event ingestion was not idempotent for turn/started:

  1. The server writes a daemon event batch inside an immediate database transaction.
  2. The transaction can commit before the HTTP request finishes its post-commit effects and returns an acknowledgement.
  3. If the daemon receives an ambiguous network failure or retryable 5xx after that commit, its event sink keeps the entire in-memory queue and posts it again on the next flush.
  4. Daemon event envelopes have no stable delivery ID. The server assigns a new event ID and sequence to every insert, and the previous ingestion path always appended turn/started without checking the semantic identity (threadId, turnId).
  5. The retry therefore persisted another start for the same provider turn.
  6. Timeline projection requires exactly one start per turn and threw on the duplicate, causing the public timeline route to return 500 even though thread metadata, events, and final output remained stored.

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:

  • ingestion treats (threadId, turnId) as the identity of turn/started and skips a replay when that start is already stored
  • projection keeps the first start as canonical so histories written before this fix remain readable

This 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:

repo_dir=$(git rev-parse --show-toplevel)
repro_dir=/tmp/bb-timeline-pr-repro-1560
base_sha=a83c12946
fixed_sha=f4b6cbba7

git worktree add --detach "${repro_dir}" "${base_sha}"
git diff "${base_sha}" "${fixed_sha}" \
  -- apps/server/test/public/public-thread-data.test.ts |
  git -C "${repro_dir}" apply -

cd "${repro_dir}"
pnpm install --frozen-lockfile
pnpm exec turbo run test \
  --filter=@bb/server \
  --only \
  --force \
  -- \
  --run test/public/public-thread-data.test.ts \
  -t "returns a timeline when persisted daemon retry history has duplicate turn starts"

The regression fixture inserts two turn/started rows with the same turn ID, then requests the public timeline route. The unfixed parent commit fails with:

AssertionError: expected 500 to be 200

Clean up the disposable worktree:

cd "${repo_dir}"
git worktree remove --force "${repro_dir}"

Verify the fix

On this PR's head:

pnpm exec turbo run test \
  --filter=@bb/server \
  --only \
  --force \
  -- \
  --run test/public/public-thread-data.test.ts \
  -t "returns a timeline when persisted daemon retry history has duplicate turn starts"

Expected result: the route returns 200, the test passes, and the timeline contains one canonical turn.

Behavior after this PR

  • Existing duplicate-start histories remain readable.
  • Reposted turn/started events are ignored at ingestion, preventing new projection-breaking histories.
  • Other replayed event types retain their existing behavior.

Verification

  • Red repro on a83c12946: route regression fails with expected 500 to be 200
  • @bb/thread-view timeline test file: 72 passed
  • @bb/db events test file: 79 passed
  • @bb/server public thread data test file: 75 passed
  • @bb/server internal event/tool-call test file: 25 passed
  • Turbo typecheck: @bb/db, @bb/thread-view, and @bb/server passed
  • CI: all required checks passed
  • Independent architecture and code reviews: CORRECT
  • Visual QA: not applicable; this changes event ingestion/projection and no UI code

Fixes #1839

BB-Thread-ID: thr_tq4bctwps7

AGENT GENERATED: by GPT-5

@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

I am the Slop Cop. I am reviewing this pull request now.

I will check security, code quality, architecture, performance, tests, and the real timeline behavior.

@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

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.

SawyerHood added a commit that referenced this pull request Aug 21, 2026
## 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]>
@SawyerHood

Copy link
Copy Markdown
Collaborator

This is an automated message. We have closed this pull request because it has been open for more than two weeks.

@SawyerHood SawyerHood closed this Aug 27, 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.

Retried turn starts can make stored timelines unreadable

2 participants