Skip to content

fix(transcript): realign rebuilt turn ordinals to wire ids and mark wedged turns - #4280

Merged
sailist merged 4 commits into
mainfrom
bug-292-10-15-wedged-turn-transcript-seam
Oct 20, 2026
Merged

sailist merged 4 commits into
mainfrom
bug-292-10-15-wedged-turn-transcript-seam

Conversation

@sailist

@sailist sailist commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

A user session froze in the past: after the agent loop silently stalled mid-turn (background subagents kept running), restarting the app made the conversation view roll back roughly two days and never catch up; search still surfaced a query that never landed in the transcript.

Bug Reproduction Steps

  1. Run a session where a turn starts but its loop dies before writing any terminal event (e.g. the delivery of background-task completion notifications stalls while the turn is waiting).
  2. The client caches the live ordinal axis (the stuck turn shows as running).
  3. Restart the app. The server cold-rebuilds the transcript from the wire: materialized turns are renumbered 0..N (folded notification turns shift the axis), and the never-ended turn is fabricated as completed with null timestamps.
  4. The client merges by (turnId, ordinal); the two axes no longer align, so the view is permanently frozen at the pre-restart point and newer turns never render.

Root Cause

Three layers, two fixed here, one instrumented:

  1. Terminal events are only written by a live turn loop. A turn whose loop stalls stays started-forever; nothing reconciles it on rebuild, and the cold materializer hardcodes state: 'completed'. → Fixed: rebuilt transcripts now derive an explicit wedged state.
  2. Cold rebuild and live projection use different ordinal contracts. Live assigns ordinal = wire turn id; cold rebuild renumbered 0..N, so the axes always diverged at folded turns. → Fixed: cold rebuild now uses the same wire-id axis with holes.
  3. The notification delivery chain fails silently at several points (buffered-but-never-forwarded nudges, hung/latched wire flushes, lifecycle-guard drops, stuck dispatcher queue). The definitive break is not yet located, so this PR instruments every silent point instead of guessing a fix. → Observability: structured warnings + a per-turn watchdog; recovery semantics follow once a recurrence is caught by these logs.

Code Changes

  • packages/transcript (foldWireRecordFacts): rebuilt turns matched to wire facts are realigned to their wire turn ids (holes left for folded turns), startedAt restored from agent.turn.started / turn.prompt record times, and any turn with a prompt but no terminal event is marked wedged once a later turn prompt exists — the tail turn only when it is not the live active one.
  • Contract: TranscriptTurn gains an additive optional wedged boolean; state stays 'failed' so released clients keep parsing transcripts and render the turn as failed.
  • packages/kap-server: readColdSnapshot passes the live active wire turn id into the fold; the live projector closes the previous running turn as wedged when a new turn starts instead of silently overwriting it.
  • packages/agent-core-v2 observability: AppendLogStore warns once when appending over a latched storage failure and when a flush stays pending past 30s (repeats every 10min with scope/key/pending); WireService routes append failures to the daemon log; AgentLoopService arms a per-turn watchdog warning after 10min without observable progress (including pending-notification/pause/queue state) and logs notify buffering/consumption at debug level; AgentTaskService warns when lifecycle guards silently drop task notifications or terminal events; EventDispatcherService warns once per episode when dispatch is stuck for 30s+ with events queueing.
  • Tests: foldFacts realign/wedged/tail-rule cases, a readColdSnapshot regression replicating the incident wire shape (folded notification turns, a never-ended turn, a successor turn), consolidation of adjacent robustness cases to keep the test count flat, and a timer-leak assertion made deterministic by quiescing the spawned notification turn first.
  • Verified against the incident's real 15k-line wire export: the never-ended turn rebuilds at its wire id with wedged state and the true start time, all 260 visible turns land on wire-id ordinals, folded turns leave holes.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Cold-rebuilt turn ordinals/ids for sessions with folded or hidden wire turns Renumbered 0..N sequentially, diverging from the live axis ordinal = wire turn id, holes where turns were folded Clients merge axes that never agreed; old cached pages are superseded by the next reset/reload None needed (self-healing)
Turns with prompt but no terminal event in the wire Rebuilt as completed with null timestamps state failed + wedged: true, real startedAt, no endedAt Nobody; the fabrication was the bug Released clients parse fine (additive field, existing enum value) and show the turn as failed
startedAt on cold-rebuilt turns Absent Restored from wire record times when a match exists Nobody (additive) —
Live projector sees a new turn start while the previous is still running Previous running turn silently overwritten Previous turn closed as failed + wedged with its open step interrupted Nobody (anomaly path) —
Daemon log output No signal on stalled notification delivery, hung wire flushes, latched storage failures, silent lifecycle drops, or eventless running turns Bounded warn/debug lines (watchdog repeats every 10min per silent turn; stuck-flush every 10min) Nobody —

Affected modules and coverage: transcript fold/group (foldFacts cases in packages/transcript/test/layers.test.ts), kap-server cold rebuild (test/services/transcript.test.ts regression), live projector (existing kap-server transcript suites), agent-core-v2 loop/task/persistence/wire/dispatcher (existing suites incl. timer-leak test made deterministic). Full monorepo suite on Linux: 17029/17029 passed.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5735f14

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T09:52:53.902305Z 5735f14 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@5735f14
npx https://pkg.pr.new/@moonshot-ai/kimi-code@5735f14

commit: 5735f14

…edged turns

Cold transcript rebuilds numbered materialized turns 0..N while the live
projector assigns ordinal=wireId, so a session rebuilt after a restart got a
shifted axis that no longer aligned with what clients had cached live, and a
turn whose loop died before writing a terminal event was rebuilt as a fake
completed turn with no timestamps.

foldWireRecordFacts now reassigns every matched rebuilt turn to its wire turn
id (leaving holes for folded turns), restores startedAt from the
agent.turn.started / turn.prompt records, and marks a turn with no terminal
event as wedged (state failed + wedged flag) once a later turn prompt exists
in the wire; the tail turn is only wedged when it is not the live active one.
The live projector closes the previous running turn as wedged when a new turn
starts. The wedged marker is an additive optional field so released clients
keep parsing transcripts and render the turn as failed.
…ence failures

The wedged-turn incident showed a main agent loop can stall for hours with
zero diagnostics: task notifications pooled in memory, a latched or hung wire
flush swallowed every subsequent record, and the running turn produced no
watchdog output.

- AppendLogStore warns once when an append is accepted while a storage
  failure is latched, and warns when a flush stays pending past 30s
  (repeating every 10min) with scope/key/pending counts.
- WireService routes append failures to ILogService in addition to
  onUnexpectedError so they land in the daemon log.
- AgentLoopService arms a per-turn watchdog that warns after 10min without
  observable progress (steps, streaming partials, machine phase), including
  pending notification/pause/queue state; loop.notify and nudge consumption
  log buffered/drained counts at debug level.
- AgentTaskService warns when lifecycle guards silently drop task
  notifications or terminal events, and debug-logs in-process redelivery
  suppression.
- EventDispatcherService warns once per episode when dispatch is stuck for
  over 30s and events keep queueing behind it.
liruifengv
liruifengv previously approved these changes Oct 20, 2026
…nting leaked timers

With the loop turn watchdog armed, a notification-driven turn that happens
to be running at the assertion holds a legitimate interval, making the
global timer count scheduling-dependent. Cancel any spawned turn and pump
the clock until the loop is idle before counting.
@sailist
sailist force-pushed the bug-292-10-15-wedged-turn-transcript-seam branch from b9f2b4f to 5735f14 Compare October 20, 2026 09:49
@sailist
sailist merged commit 67325c1 into main Oct 20, 2026
16 checks passed
@sailist
sailist deleted the bug-292-10-15-wedged-turn-transcript-seam branch October 20, 2026 10:00
This was referenced Oct 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.

2 participants