Skip to content

fix(agent-core-v2): keep session deletion from hanging - #3887

Merged
sailist merged 3 commits into
mainfrom
fix/session-delete-hang
Sep 18, 2026
Merged

sailist merged 3 commits into
mainfrom
fix/session-delete-hang

Conversation

@RealKai42

@RealKai42 RealKai42 commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related Issue

No public issue. A desktop app user on Windows 11 reported that after confirming "Delete session", the confirmation dialog keeps spinning and only restarting the app recovers. The embedded server never answers POST /api/v1/sessions/{session_id}:delete. All lifecycle operations on a session run on one per-session chain, so retrying the delete or reopening the session then waits behind the stuck operation too.

Problem

Deleting a live session closes it first, and some waits on the close path have no upper bound. Reading the code turned up three of them, and any one can keep a deletion from ever finishing:

  1. Agent removal ignores its own deadline. AgentLifecycleService.remove() quiesces the agent loop under a 3s deadline (added in fix(kimi-code): flush wire journals before print-mode exit #3531). That deadline is checked only after await Promise.all([loop.settled(), compactionSettled]) returns, and that await has no bound. If the loop does not settle after cancel(), removal waits forever, and so do session close and delete. Two ways that happens:
    • An engine turn has started but is not yet bound as the active turn, so cancel() does not reach it and it runs on.
    • A compaction keeps running after abort.
  2. Windows taskkill wait. On win32, HostProcess.kill() waits with no bound for the taskkill /T /F child to exit. Closing a session uses this call to force-stop background tasks that outlive the 5s grace period.
  3. Archive/resume deadlock. setSessionArchived() awaited whenResumeSettled() inside its lifecycle critical section. Suppose a resume is requested while the archive or restore is still queued: it lands behind the archive on the same per-session chain. The archive then waits for the resume, and the resume waits for the archive. No later lifecycle operation on that session starts, including delete.

We could not reproduce the reporter's environment, so this PR does not claim which of these fired there. Each one is an unbounded wait on the delete path, and each gets a regression test.

What changed

  • AgentLifecycleService.remove() now races the settle wait against the existing quiesce deadline. If the deadline passes, removal takes the path it already took when the deadline expired between polls:
    • stop the agent's tasks;
    • flush its wire journal;
    • stop the agent actor, which aborts and disposes whatever is still running.
  • On Windows, HostProcess.kill() stops waiting for taskkill after 5s. It then unrefs and terminates the stuck taskkill process, so it neither leaks nor keeps the process alive.
  • setSessionArchived() now waits for a pending resume before it enters the lifecycle critical section, not inside it. Inside the section, serialization already guarantees that any resume queued earlier has finished, so sessions are still classified as live or cold the same way.
  • A full compaction no longer applies a summary that arrives after the compaction was aborted. Removal no longer waits indefinitely for the compaction to settle; this check keeps an abandoned compaction from writing after its agent is torn down. It also fixes a user cancellation that races a late summary.

Tests:

  • agentLifecycle.test.ts: removal finishes at the quiesce deadline when the loop never settles.
  • hostProcessService.test.ts: on win32, kill() returns even when taskkill never exits, and the stuck taskkill is unreferenced and terminated.
  • coldSessionArchive.test.ts: uses a real SessionManager. A resume is requested after the archive has joined the chain; the archive still completes, and the resume queued behind it then runs.
  • fullCompaction.test.ts: a requester that ignores the abort signal delivers its summary after cancel(), and the summary is not applied.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: the issue must have a maintainer's /approve). There is no public issue; the report is described above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Deleting a live session closes it first, and three waits on that path
had no upper bound:

- AgentLifecycleService.remove() checked its 3s quiesce deadline only
  after awaiting loop.settled() and the compaction promise, so a loop
  that never settled after cancel() blocked agent removal, session
  close and delete forever. The settle wait now races the deadline and
  falls through to the existing forced-teardown path when it expires.
- HostProcess.kill() on Windows waited for taskkill to exit with no
  bound. It now stops waiting after 5s.
- setSessionArchived() awaited a pending resume inside its lifecycle
  critical section. A resume queued behind the archive then waited for
  the archive while the archive waited for it, wedging the session's
  lifecycle chain so that every later operation on the session,
  delete included, never started. The resume is now settled before
  the critical section is entered.
Copilot AI balanced review requested due to automatic review settings September 18, 2026 04:10
@changeset-bot

changeset-bot Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1c2ca44

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 Sep 18, 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-09-18T04:36:44.677116Z 1c2ca44 Manual request
🔒 Security Review ✅ Completed 2026-09-18T04:14:53.813728Z 47f9b84 PR opened
ℹ️ 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 Sep 18, 2026 •

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

commit: 1c2ca44

@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: 47f9b848bb

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copilot AI 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.

🟡 Changes recommended

The timed-out Windows taskkill child must be terminated and unreferenced to avoid leaking a live process handle.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Prevents session deletion from hanging during lifecycle shutdown.

Changes:

  • Bounds agent quiescence and Windows taskkill waits.
  • Avoids archive/resume lifecycle deadlocks.
  • Adds regression tests and a changeset.
File summaries
File Description
packages/agent-core-v2/test/workspace/sessionLifecycle/coldSessionArchive.test.ts Tests archive/resume serialization.
packages/agent-core-v2/test/session/agentLifecycle/agentLifecycle.test.ts Tests bounded agent removal.
packages/agent-core-v2/test/os/backends/node-local/hostProcessService.test.ts Tests the Windows kill timeout.
packages/agent-core-v2/src/workspace/sessionLifecycle/coldSessionArchive.ts Moves the resume wait outside serialization.
packages/agent-core-v2/src/session/agentLifecycle/agentLifecycleService.ts Bounds agent settlement by its deadline.
packages/agent-core-v2/src/os/backends/node-local/hostProcessService.ts Adds a timeout around taskkill.
.changeset/session-delete-hang.md Records the user-facing fix.
Review details

Suppressed comments (1)

.changeset/session-delete-hang.md:5

  • This release-note sentence is grammatically malformed. State the outcome directly so the generated changelog reads clearly.
Fix deleting or archiving a session sometimes never finishing.
  • Files reviewed: 7/7 changed files
  • Comments generated: 1
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

When the 5s wait on taskkill timed out, kill() returned but the spawned
taskkill child stayed alive and referenced, so every hang leaked a
taskkill.exe process and its handle could keep the CLI or server
process from exiting. Keep the handle and, when the timeout wins, unref
it and terminate it.
@RealKai42

Copy link
Copy Markdown
Collaborator Author

@codex review

@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: 229099752b

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…er abort

Cancelling a full compaction, or removing its agent, aborts the
compaction's signal, and the abort listener records the cancellation
and detaches the compaction right away. compactionRound() never checked
the signal again after the summary request returned, so a provider
request that finished despite the abort still went on to
applyCompaction(). That rewrote the context of a cancelled compaction,
and since agent removal now stops waiting for the compaction at its
quiesce deadline, it could also write records after the agent was torn
down and recreate files under a deleted session directory. Check the
signal after the last await and before applying the summary.
@RealKai42

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 1c2ca443af

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@sailist
sailist merged commit e3f48a2 into main Sep 18, 2026
16 checks passed
@sailist
sailist deleted the fix/session-delete-hang branch September 18, 2026 06:44
@github-actions github-actions Bot mentioned this pull request Sep 18, 2026
7723qqq added a commit to 7723qqq/kimi-code that referenced this pull request Sep 19, 2026
All deltas since merge base 1b89e4b now carry verdicts: MoonshotAI#3885 and
MoonshotAI#3894 ported, MoonshotAI#3896/MoonshotAI#3892/MoonshotAI#3887/MoonshotAI#3889 not-applicable (engine architecture
differs structurally — reasoning in the allowlist), the remaining eight
tracked as ROADMAP §6.1 items 22-28 with the prerequisite chain recorded
(models.dev proxy, trace id capture, steer id design pass). Gate exits 0.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Oct 5, 2026
Step 7 of the incremental sync to 2.1.1: 21 upstream commits over 263
files. 24 conflicts, concentrated in the provider/registry import path
(api_key_env, registry import) and the media-read layer where the fork's
inline media reading sits on top of upstream's ReadMediaFile guidance.

Upstream's changes in this step, all absorbed:
- Stop listing unavailable media tools in subagent menus and clarify
  Read errors for images and videos (MoonshotAI#3878)
- Providers can read their API key from a named environment variable
  (api_key_env in config.toml or the provider API) (MoonshotAI#3762)
- Keep follow-up messages sent during a turn from appearing twice after
  a session reload (MoonshotAI#3896)
- Session index compaction on startup, faster CLI startup, faster
  session list and resume on large workspaces, and incremental
  background search indexing (MoonshotAI#3889)
- Rename kimi install-app to kimi install-desktop, keeping the old name
  as a hidden alias (MoonshotAI#3864)
- Restore thinking display for OpenAI-compatible providers that send a
  reasoning string next to an unrecognized reasoning_details array
  (MoonshotAI#3910)
- Fix kimi -p exiting early and cancelling the active turn when a cron
  task fires (MoonshotAI#3875)
- Drop literal decision clauses from the system prompt and the auto
  permission mode reminder (MoonshotAI#3894)
- select_tools points out already-available tools to call directly and
  suggests announced names for near-miss selections (MoonshotAI#3885)
- Fix deleting or archiving a session sometimes never finishing (MoonshotAI#3887)
- Keep follow-up messages attached to their turn; undo the host turn
  instead of the follow-up alone (MoonshotAI#3891, MoonshotAI#3906)
- Remove the system-prompt rule that forbade all file access outside the
  working directory (MoonshotAI#3879)
- Stop workspace file watchers from scanning an unbounded project root;
  add [watch] enabled / KIMI_CODE_WATCH to disable watching (MoonshotAI#3892)

Fork behaviour that had to survive:
- the i18n layer: the registry-import and provider api_key_env strings
  went through `t()` with en/zh entries (providerApiKey,
  registryAuthRequired, providerAuthRequired, subtitleDefault,
  tokenLabel)
- the fork's inline media reading in the read tool, kept over
  upstream's ReadMediaFile guidance
- the provider/registry import path, where the fork's custom-registry
  flow and upstream's api_key_env support had to be reconciled

The merge also drops the unused READ_MEDIA_FILE_TOOL_NAME constant that
came in with this step (the fork reads media inline), keeping the lint
gate green.

Verified: typecheck clean across every package and app; full suite
17752 passed / 0 failed / 81 skipped / 1 todo; lint 0 errors.
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.

3 participants