Repository navigation
Skip replayed turn/started events at daemon ingestion - #2126
Conversation
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]>
|
🚨 SLOP COP 🚨 · 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. |
There was a problem hiding this comment.
🚨 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.
## 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]>
What was wrong
The host daemon delivers event batches at least once.
apps/host-daemon/src/event-sink.tskeeps 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 sameturn/startedwith the same provider turn id.appendDaemonEventsInTransactioninpackages/db/src/data/events.tsassigned every insert a fresh event id and sequence and never checked whether aturn/startedfor that(threadId, turnId)was already stored, so the replay persisted a second start.groupEventProjectionTurnsinpackages/thread-viewrequires one start per turn and threwTimeline projection found duplicate turn/started, soGET /api/v1/threads/:id/timelineanswered 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 includesturn/startedinputs in the stored-turn-start lookup and skips aturn/startedwhose(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-sideThreadEventGrammarenforcesturnStartsOnce), so a repeated start is a delivery replay, not a new turn. Skipped starts are not reported inacceptedEvents; the daemon already treats a 200 as full delivery, andshouldApplyEventEffectinapps/server/src/internal/events.tsalready re-appliesturn/startedeffects for non-inserted events, so a replay still repairs thread status.packages/thread-view/src/group-event-projection-turns.ts: a secondturn/startedfor a turn already in the projection is ignored instead of throwing, so histories persisted before this change stay readable. The first start is canonical.HOST_DAEMON_PROTOCOL_VERSIONis unchanged: the request and response shapes of/session/eventsare the same; only which inputs are inserted differs.Other replayed event types keep their current behavior (a replayed
turn/completedis 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
a83c12946and now conflicts withmain(the terminal-item dedup landed in the same function). This PR applies the fix on currentmain, keeps theturn/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.tsskips 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.tskeeps a thread idle when a started/completed batch is posted againnow 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.tsreturns a timeline when a stored history holds a duplicate turn/started from a daemon replay— before:AssertionError: expected 500 to be 200packages/thread-view/test/build-thread-timeline.test.tsrenders one turn when daemon retry history contains duplicate turn starts— before:Error: Timeline projection found duplicate turn/started for turn-1Commands:
pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/thread-view --filter=@bb/server— passpnpm exec turbo run test --filter=@bb/db --filter=@bb/thread-view --force— 408 and 380 tests passpnpm 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 ininternal-skill-trees.test.ts(0644 vs 0664), unrelated to this changeManual 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/eventsroute and then reads the timeline is the faithful equivalent.Fixes #1839
Independent verification
Verified on a fresh worktree at
d7de9e5c3(branchbb/fix-1839-duplicate-turn-started;origin/main=c9aef7514is an ancestor; GitHub reportsMERGEABLE).Own root-cause read before reading this PR:
apps/host-daemon/src/event-sink.tsdeliverBatchreturns 0 on any non-permanent post failure, so a batch the server committed but whose response was lost is reposted verbatim; on maincollectDaemonTurnStartLookupKeysskippedturn/startedinputs andresolveDaemonTurnStartDispositionreturnedappendfor everyturn/started, so the replay stored a second start;groupEventProjectionTurnsthrew on it. The fix is at the right layer (server-owned ingestion policy in@bb/db; no daemon or wire change, so noHOST_DAEMON_PROTOCOL_VERSIONbump is needed).shouldApplyEventEffectinapps/server/src/internal/events.tsalready re-appliesturn/startedeffects 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.tsmintTurnId) 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/dbskips turn/started when a daemon replays an already-committed batch:AssertionError: expected { …(3) } to deeply equal { acceptedEvents: [ { …(2) } ], …(2) }@bb/dbskips a turn/started repeated inside one daemon batch:AssertionError: expected [ +0, 1 ] to deeply equal [ +0 ]@bb/thread-viewrenders one turn when daemon retry history contains duplicate turn starts:Error: Timeline projection found duplicate turn/started for turn-1@bb/serverkeeps a thread idle when a started/completed batch is posted again:AssertionError: expected [ 'turn/started', …(3) ] to deeply equal [ 'turn/started', …(2) ]@bb/serverreturns a timeline when a stored history holds a duplicate turn/started from a daemon replay:AssertionError: expected 500 to be 200Pass-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: passpnpm exec turbo run test --filter=@bb/db --filter=@bb/thread-view --filter=@bb/client-core --force: 408 / 380 / 238 passpnpm exec turbo run test --filter=@bb/server --force: 1819 pass, 1 fail (internal-skill-trees.test.tsmode 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/startedrows for one(threadId, turnId), thenGET /api/v1/threads/:id/timeline) is exactly thepublic-thread-dataroute test; it returns 500 with main's sources and 200 on this branch. The replay path through the real/session/eventsroute 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
Checksjob is red only on its last step,Check Actions cache usage, which timed out connecting toapi.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/completedare still stored twice, as on main, and projection tolerates that.