Skip to content

fix(agent-core-v2): deduplicate restored task notifications - #4836

Merged
sailist merged 6 commits into
release/2026-11-12from
bug-352-11-11-task-notification-replay
Nov 11, 2026
Merged

sailist merged 6 commits into
release/2026-11-12from
bug-352-11-11-task-notification-replay

Conversation

@sailist

@sailist sailist commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Users with completed background tasks can receive the same completion notifications again after resuming a compacted conversation or undoing a turn. This PR restores once-only notification delivery across resume and undo while preserving first delivery for undelivered tasks and tasks that complete during reset.

Bug Reproduction Steps

  1. Start background tasks and let their completion notifications enter the conversation history.
  2. Compact the conversation, then resume the session; alternatively, undo a turn whose history contains an already delivered task notification.
  3. Before this fix, the same task notification IDs are queued and delivered again. The updated resume and undo regression cases reproduce three failures before the fix and pass after it.

A separate regression case covers exiting after turn.prompt is persisted but before message.appended: this is not delivery, so resume must still restore the notification.

Root Cause

restoreTaskCompletions restores terminal tasks from the complete physical journal, but previously rebuilt the delivered set only from active messages, pending entries, and legacy task.waitDelivered records. Compaction and undo remove old notification messages from the active view, so already delivered tasks incorrectly appear undelivered.

This is a fundamental fix: the delivered set now also reuses task origins from the complete journal's durable context.append_message records. A turn.prompt alone is deliberately not treated as delivered because it is written at turn start, before the notification message is appended. No new notification protocol or wire format is introduced.

Code Changes

  • Centralize delivery-key recording and restore it from durable appended-message records as well as the existing active and legacy sources.
  • Keep delivery records scoped to the current agent while accepting legacy journal messages without an agent ID.
  • Update existing regression cases to assert actual pending/history behavior: compaction resume does not requeue old notifications, undo does not redeliver them, a task completing during reset is still delivered once, and a prompt-only crash does not suppress recovery.
  • Add a patch changeset for @moonshot-ai/kimi-code.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Resume after compaction Already delivered background task notifications can be queued again Only undelivered terminal notifications are restored Users resuming compacted sessions; no supported workflow depends on duplicate delivery Not needed; this removes erroneous duplicate delivery
Undo / reset Notifications removed from active history can be delivered again Previously delivered notifications stay delivered, while tasks completing during reset are delivered once Users undoing turns with background tasks Once-only delivery was explicitly requested; no toggle is added
Exit between turn start and message append The undelivered completion is restored on resume The completion is still restored; a prompt alone is not a delivery receipt Sessions exiting during the notification append window Existing recovery behavior is preserved
Prompt / turn finalization TurnEnded could be persisted before PromptCompleted, allowing late completion writes to race undo Existing terminal order is preserved: TurnEnded, AgentErrorEvent for failures, then PromptCompleted; every materialized prompt is settled Clients observing lifecycle order and undo invoked during turn completion Existing public contract is preserved; no toggle is added

Affected module: agent-core-v2 task completion restoration. Public APIs and persisted record shapes are unchanged. Current messages, pending entries, and legacy task.waitDelivered compatibility remain intact. The three modified test files contain 94 tests, with no net change in test declaration count.

Follow-up: Prompt Completion Ordering

The first CI run also exposed a pre-existing completion-order race: PromptProjection published durable prompt.completed from turn.result.then(...) after the public TurnEnded. When undo started in that gap, the late completion record could land after the undo switch triple and fail switchBranch() validation with records.write_failed.

endTurn() now explicitly completes every waiter materialized into the turn after TurnEnded and, for failures, AgentErrorEvent. The deferred turn.result.then(...) completion path has been removed, while turn.result still resolves last. Existing public terminal ordering is preserved: turn.ended → error → prompt.completed, and the related snapshots retain that contract.

Checklist

  • I have read the CONTRIBUTING document.
  • No related issue; the reproduction, evidence, and root cause are documented above.
  • Updated existing regression tests prove the resume and undo behavior, including continued delivery of a new completion and prompt-only crash recovery.
  • The behavior-change table is complete, and the changeset names the removed duplicate-delivery behavior; once-only delivery was explicitly approved.
  • Added the required patch changeset.
  • No documentation update is needed for this bug fix.

Verification

  • Prompt-only regression before the follow-up fix: 0 notifications; after the fix: 1 notification.
  • Local and m0-dev: 3 test files, 94/94 tests passed on the final release base.
  • agent-core-v2 typecheck passed.
  • Root pnpm run build passed on the final release base.
  • Focused oxlint: 0 errors; 2 pre-existing reverse() warnings in rpc-events.test.ts.
  • Prompt finalization follow-up: loop 67/67, plan 32/32, tool 164/164, config 121/121, klient 23/23, and coreLoopService 19/19 passed locally; related remote regression files passed 151/151 and the root build passed.

@changeset-bot

changeset-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 22a4319

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 Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T13:04:43.829200Z 22a4319 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 Nov 11, 2026 •

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

commit: 22a4319

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 78c3582ece

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +29 to +30
if (record.type === 'turn.prompt') {
recordDelivery(record['origin'] as PromptOrigin | undefined);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Do not treat a started prompt as delivered

If the process exits after turn.prompt is persisted but before the notification's message.appended event, this marks the task as delivered even though it never entered the conversation. LoopJournal writes turn.prompt immediately at turn.started (journal.ts:361-370), so the previous restore path would retry this completion, whereas the new scan suppresses it permanently and silently loses the background-task result on resume. Only index a record that proves the notification was appended, or pair the prompt with a later delivery marker.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eb0c246fd5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +210 to +212
complete(prompt: ActivePrompt, result: TurnResult): void {
const waiter = this.waiters.get(prompt.id);
if (waiter !== undefined) this.settleCompletion(waiter, result);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Settle every prompt materialized into the turn

When a notification such as a background-task completion is appended to an already active turn, materialized() calls launched() for that notification's separate waiter, but this method now settles only the primary turn.prompt. The notification handle therefore remains pending forever and its submitted/started lifecycle never emits prompt.completed; previously every launched waiter subscribed to the shared turn.result. Settle all prompt IDs materialized into the completed turn, not only the original prompt.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

const requestId = promptOnly || result.type === 'cancelled' ? undefined : result.type === 'completed' ? this.lastRequestId : this.activeRequestTrace?.requestId;
const error = result.type === 'failed' ? toKimiErrorPayload(result.error) : undefined;
const interruptReason = result.type === 'completed' ? undefined : interruptReasonFor(result);
this.options.prompts.complete(turn.prompt, result);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep prompt completion after the turn's terminal events

On a failed turn, this now publishes prompt.completed before both turn.ended and the error event dispatched below. Klient's existing contract test in packages/klient/test/e2e/invalid-input-matrix.test.ts:1020-1026 explicitly requires turn.started → turn.ended → error → prompt.completed; clients that treat prompt completion as the terminal marker can now stop listening before receiving the failure details, and that e2e test will fail. Preserve the public terminal ordering even if the durable completion record must be written earlier.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 22a4319e65

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +211 to +212
for (const waiter of this.waiters.values()) {
if (waiter.launchedTurn?.id === turnId) this.settleCompletion(waiter, result);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid rescanning every historical prompt waiter

In long-lived sessions, every submitted or notification prompt remains in waiters, so this full-map scan makes each turn progressively more expensive and total finalization work quadratic in the number of prompts processed since startup. Track the waiters launched for each turn (or remove settled waiters while retaining their terminal projection) so completing a turn touches only its own prompts.

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 5ad9aa1 into release/2026-11-12 Nov 11, 2026
15 checks passed
@sailist
sailist deleted the bug-352-11-11-task-notification-replay branch November 11, 2026 13:11
@github-actions github-actions Bot mentioned this pull request Nov 11, 2026
Grapedge added a commit that referenced this pull request Nov 12, 2026
* fix(agent-core-v2): truncate oversized skill content (#4834)

* fix(kap-server): bind the main agent when a session is created (#4839)

* fix(kap-server): bind the main agent when a session is created

* fix(kap-server): reject a profile on prompt submissions

* fix(kap-server): reject a profile change through the session profile

* fix(kap-server): wait for model configuration before binding a new session

* fix(agent-core-v2): deduplicate restored task notifications (#4836)

* fix(agent-core-v2): deduplicate restored task notifications

* chore: add notification replay fix changeset

* fix(agent-core-v2): preserve task notifications after prompt-only crashes

* fix(agent-core-v2): complete prompts before ending turns

* test: align lifecycle snapshots with prompt completion order

* fix(agent-core-v2): settle all prompts during turn finalization

* fix(kap-server): drop reserved metadata keys from session profile updates (#4842)

* fix(kap-server): drop reserved metadata keys from session profile updates

* fix(kap-server): keep stored reserved metadata keys on profile updates

* docs: split and rewrite the server API reference (#4841)

* docs: split and rewrite the server API reference

* docs: redirect old server API anchors to the split pages

* docs: describe profile metadata as a replacement

* docs: mark question responses as answered-only

* fix(kap-server): avoid heartbeat timeout after scheduling stalls (#4823)

* fix(kap-server): avoid heartbeat timeout reaping after stalls or clock jumps

* fix(kap-server): grace heartbeat window for short scheduling stalls

* fix(kap-server): treat only clearly late heartbeats as scheduling stalls

* fix(kap-server): time heartbeats on a monotonic clock and drain queued input before reaping

---------

Co-authored-by: Kimi Code (Grok Bot) <[email protected]>

* fix(kap-server): undo a turn only once when requests race (#4846)

* docs: describe heartbeat stall handling (#4849)

* docs: describe heartbeat stall handling

* docs: explain the monotonic clock in the heartbeat notes

* fix(agent-core-v2): acquire session lock before loop restoration (#4848)

* fix(agent-core-v2): acquire session lock before loop restoration

* chore: add session lock lifecycle changeset

* fix(agent-core-v2): hold session lock through loop restoration

- add an operation-scoped lease to the session run gate
- hold it across loop initialization, reset, and pending drains
- cover idle timeout and release ordering

* fix(agent-core-v2): keep the output of stopped tool calls (#4854)

* fix(kap-server): drop the partial reply of a retried step (#4855)

* fix(agent-core-v2): dedupe historical tool schemas (#4862)

* fix(agent-core-v2): dedupe historical tool schemas

* chore: add duplicate tool schema changeset

* fix(agent-core-v2): preserve first tool schema declaration

* fix(agent-core-v2): remind on changed tool schemas

* fix(agent-core-v2): block stale tool schema calls

* fix(agent-core-v2): normalize registry schemas in pending checks

* fix(agent-core-v2): import registry tool metadata type

* fix(agent-core-v2): preserve abort handling during validation

* fix(agent-core-v2): refine validation hook preparation

* fix(agent-core-v2): make validation hooks synchronous

* fix(agent-core-v2): preserve tool result notes on fork (#4867)

* fix(agent-core-v2): preserve tool result notes on fork

* chore: add fork tool result note changeset

* fix(agent-core-v2): scope tool result note restoration to forks

* fix(agent-core-v2): normalize inherited tool result notes

* fix(agent-core-v2): isolate fork note restoration

* feat(tui): sweep running titles toward text and add KIMI_CODE_TUI_ANIMATION_FPS (#4843) (#4870)

* chore: sync web dist from code-app (#4871)

code-app: 8ab17294e031323186d357d121c5360b8353900e

Co-authored-by: kimi-agent-bot <[email protected]>

* ci: release packages (#4835)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore: sync web dist from code-app

code-app: 5835391dac3a2b9e0c65ffbd418f0d6042a7adb2

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: qer <[email protected]>
Co-authored-by: Kimi Code (Grok Bot) <[email protected]>
Co-authored-by: grapedge <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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