Skip to content

Skip replayed turn/started events at daemon ingestion - #2126

Merged
SawyerHood merged 1 commit into
mainfrom
bb/fix-1839-duplicate-turn-started
Aug 21, 2026
Merged

SawyerHood merged 1 commit into
mainfrom
bb/fix-1839-duplicate-turn-started

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

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

The host daemon delivers event batches at least once: when the server
commits a batch but the acknowledgement is lost (gateway 502/504 or a
dropped connection), the daemon reposts the same events. Ingestion
assigned every insert a fresh id and sequence and never checked whether
a turn/started for the same (threadId, turnId) was already stored, so a
replay persisted a second start. Timeline projection requires one start
per turn and threw, and the public timeline route answered 500 for a
thread whose data was intact.

A provider turn starts exactly once (the daemon-side event grammar
enforces it), so a turn/started whose key is already stored is a replay.
Ingestion now skips it, mirroring the existing terminal-item dedup in
the same transaction. Projection keeps the first start as canonical so
histories written before this change stay readable.

Fixes #1839

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood marked this pull request as ready for review August 21, 2026 02:15
@bb-slop-cop

bb-slop-cop Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, duplication, and end-to-end behavior. Three focused agents will review the diff in parallel. I will post one final review after I test and synthesize their findings.

@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 stops a repeated daemon delivery from saving a second start marker for the same turn. It also lets older affected timelines open by ignoring later repeated start markers.

I found no actionable security, correctness, performance, or architecture issue.

What I checked:

  • Security: The lookup key includes both the thread ID and turn ID. The route validates daemon sessions and thread ownership.
  • Correctness: The transaction covers stored duplicates and duplicates inside one batch. The server still applies replay effects that can repair thread state.
  • Legacy data: Timeline projection keeps the first start as the canonical start. Later turn events still use the same turn record.
  • Performance: The lookup uses the existing covering index and 250-key batches. A 250-key lookup averaged 7.608 ms on 50,000 event rows.
  • Architecture: The database prevents new duplicate starts. The timeline layer repairs old stored histories.
  • Protocol: The request and response shapes did not change. A successful daemon post already drains the full submitted batch.
  • Duplication: PR #1560 implements the same fix and conflicts with current main. Close or replace that PR after this PR lands.

Verification:

  • The database suite passed 85 tests.
  • The thread-view suite passed 73 tests.
  • The two focused server files passed 104 tests.
  • Turbo type checks passed for the database, thread-view, and server packages.
  • All current GitHub CI checks passed.
  • The branch dev app loaded through doobie with no browser console errors.
  • The exact lost-response fault needs a proxy. The real route replay tests cover the same database and timeline path.

Three focused reviews and one GPT-5.6 synthesis review found no actionable issue. I left no inline comments.

@SawyerHood
SawyerHood merged commit d20638b into main Aug 21, 2026
22 of 23 checks passed
@SawyerHood
SawyerHood deleted the bb/fix-1839-duplicate-turn-started branch August 21, 2026 03:06
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

The codebase carried a lot of code that nothing reached: symbols and
files with no consumer, options that no caller passes, branches the
types make impossible, feature flags that graduated but kept their `if`
guards, pass-through wrappers that only forward arguments, barrel files
that re-export hundreds of names nobody imports through them, and the
same small helper copied into many files. This code has no effect on
behavior, but every reader must still parse it.

## What changed

Net −16k lines across 1,732 files. No behavior change. Four commits, two
per pass:

1. **Remove dead code, pass-through wrappers, and stale barrels** —
unused symbols and files, dead branches, unused params/options,
single-use wrappers inlined, dead barrel lines, tests and stories that
existed only for deleted code. Drops the unused `cronstrue` dependency
from `apps/app`.
2. **Drop export from module-private symbols** — ~900 declarations that
were exported but only used inside their own file.
3. **Remove more dead code, duplicate helpers, and unused options** —
second pass over the same ground plus repo-wide sweeps for duplicate
helpers and legacy/compat paths. Folds byte-identical helper copies into
one shared module where the consumer already depends on it (e.g.
`describeError` ×11, `createDeferred` ×15 → `@bb/test-helpers`,
`DelayedLoading` ×4 → `@bb/shared-ui`). Removes unused
`ws`/`@types/ws`/`tsx` devDependencies from `apps/connect` and an unused
`@radix-ui/react-slot` from `apps/web`.
4. **Drop export from more module-private symbols** — ~700 more.

Out of scope on purpose: `@get-bb/plugin-sdk` and `@bb/sdk` exports
(public API), CLI commands and flags, server routes, DB schema and
migrations, generated code, wire payload shapes between the server and
host daemon (`HOST_DAEMON_PROTOCOL_VERSION` is unchanged), and parsers
for persisted or legacy data.

Every removal was found by one agent, adversarially verified by a second
agent that searched the whole repo (including strings, configs, docs,
`.ladle`, and stories) for any remaining reference, and then applied by
a third. 41 proposals were rejected at verification or apply time, and I
reverted 2 more by hand.

## How you verified

- `pnpm exec turbo run typecheck` — 74/74 packages pass
- `pnpm exec turbo run lint` — passes
- `pnpm exec turbo run build` for `@bb/app`, `@bb/server`,
`@bb/host-daemon`, `@bb/cli`, and all `plugins/*` — passes
- `pnpm exec turbo run test` — all packages pass except
`internal-skill-trees.test.ts`, which fails identically on `main` on
this machine (local umask 0002; passes in CI)
- Rebased onto `main` after #2125, #2132, #2128, #2126, #2112 landed;
re-ran typecheck, lint, and tests for the touched packages

Fixes #

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
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

1 participant