Skip to content

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

Merged
sailist merged 3 commits into
release/2026-11-12from
bug-354-11-11-session-lock-lifecycle
Nov 12, 2026
Merged

sailist merged 3 commits into
release/2026-11-12from
bug-354-11-11-session-lock-lifecycle

Conversation

@sailist

@sailist sailist commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

A session opened by another app instance could restore pending background-task completions and start notification turns before acquiring the exclusive session lock. This could execute pending work concurrently even though the later persistence guard rejected writes. This PR makes Loop initialization and reset wait for the existing session run gate before restoring or executing work.

Bug Reproduction Steps

  1. Persist a detached, terminal task whose completion notification has not been delivered.
  2. Make the session run gate reject initialization with session.occupied, as happens when another client holds the lock.
  3. Attempt to resume the session. Previously, Loop restoration could create the completion and start a notification turn before the write guard ran.
  4. With this change, initialization stops before Loop creation, completion creation, LLM calls, or turn.prompt. After the lock is released, retrying start() delivers the pending notification exactly once.

Root Cause

AgentLoopService.initializeLoop() drained the wire, read the journal snapshot, reconciled task history, restored completions, and created the Loop before runGate.begin() ran through ordinary prompt admission. resetLoop() had the same ordering gap. The append-log write guard only protected persistence; it could not prevent an unauthorized restore from executing a Turn first.

This is a fundamental ordering fix: the existing run gate now guards Loop initialization and reset directly. No second lock state machine is introduced.

Code Changes

  • Call runGate.begin() at the start of initializeLoop(), before wire draining, journal snapshots, task-history reconciliation, completion restoration, and Loop creation.
  • Call it again at the reset restoration boundary, before pending entries can be drained or snapshots restored. Undo retains its existing admission check, so its reset path checks the gate again without changing public terminal-event ordering.
  • Preserve the append-log write guard as the second line of defense.
  • Extend existing regression coverage without increasing the test declaration count:
    • occupied initialization has no Loop, completion, notification, LLM call, or turn.prompt; release-and-retry delivers once;
    • undo performs both its original admission and the reset admission.
  • 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/start while another client owns the session or the wire is stale Loop restoration and pending-task execution could begin before persistence was rejected Initialization fails before Loop restoration or Turn execution No supported workflow relies on bypassing session exclusivity Release the other client's lock or reload the stale session, then retry
Undo/reset restoration Reset could restore snapshots without its own gate check Reset rechecks the existing gate before restoring or draining work All undo/reset callers; the existing undo admission remains Retry after obtaining a valid lock
Normal prompt and terminal-event behavior Existing admission and public terminal-event order Unchanged All clients N/A

Affected module: agent-core-v2 Loop initialization/reset and its existing Loop/Task regression tests. There are no config, API-shape, prompt-text, or persisted-format changes.

Validation:

  • Focused m0-dev tests for Loop, Task, undo, and session run gate: 96/96 passed.
  • Every file that failed during full-suite runs passed independently: 160/160 tests passed.
  • agent-core-v2 typecheck and the monorepo root build passed; targeted oxlint reported zero errors.
  • The full concurrent suite did not finish green: the latest run had 17,422 passed, 3 failed, and 30 skipped. The remaining failures were two remote/process timer cases and one sessionIndex tick case; both files passed independently and are not modified by this PR.

Checklist

  • I have read the CONTRIBUTING document.
  • No separate issue; the requirement and regression reproduction are documented above.
  • I have added regression coverage for the fixed behavior.
  • The behavior-change table above is complete. The only removed behavior is unsupported lock bypass; legitimate retry behavior is preserved.
  • Added a patch changeset manually following .changeset/README.md; the gen-changesets skill was unavailable in the authoring session.
  • No doc update is needed for this internal lifecycle ordering fix.

@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-11T15:52:47.724560Z 96e2238 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.

@changeset-bot

changeset-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 96e2238

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

@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@96e2238
npx https://pkg.pr.new/@moonshot-ai/kimi-code@96e2238

commit: 96e2238

@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: 17e42dd3d7

ℹ️ 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".

initialTools?: readonly Tool[],
): Promise<void> {
if (this.initialized) return;
this.runGate.begin();

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 Hold the session lock for the entire restoration

When a large or slow persisted session takes more than three seconds to drain, reconcile tasks, or restore completions, this call does not keep the lock for that asynchronous operation: SessionRunGateService.schedule() releases it while SessionActivityView remains idle because restoration/reset is not counted as activity. Another app can then claim the session while this instance continues creating and draining the restored loop, recreating the concurrent notification-turn race for users resuming sessions with undelivered task completions. The same issue applies to the new call at line 532, and calling begin() again does not renew the timer for an already-held lock; use an operation-scoped lease or busy guard spanning all awaited restoration work.

AGENTS.md reference: AGENTS.md:L102-L105

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-354-11-11-session-lock-lifecycle branch from 17e42dd to 16d0de9 Compare November 11, 2026 14:59
@sailist
sailist changed the base branch from main to release/2026-11-12 November 11, 2026 15:00
- 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

@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: 96e2238406

ℹ️ 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".

});
this.createLoopFromSnapshot(snapshot, tools, completions, seededMessages);
} finally {
lease.release();

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 Preserve the direct hold when the restoration lease ends

When initialization remains idle for more than three seconds before restoring a pending notification, releaseWhenIdle() clears the direct HeldState.held flag while this lease alone keeps the lock file published. createLoopFromSnapshot() then schedules the restored turn, but this lease.release() removes the final lease and unpublishes the lock before or during that turn, allowing another app to acquire and run the same session concurrently. Fresh evidence in this revision is that the new operation lease permits the idle timer to clear the direct hold; prevent idle release while an operation lease exists or re-establish the activity hold before releasing it. The same issue occurs at line 568 after reset restoration.

AGENTS.md reference: AGENTS.md:L104-L107

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 9ae2757 into release/2026-11-12 Nov 12, 2026
14 checks passed
@sailist
sailist deleted the bug-354-11-11-session-lock-lifecycle branch November 12, 2026 03:59
@github-actions github-actions Bot mentioned this pull request Nov 12, 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