Skip to content

fix(workspace): reclaim instances when last owner releases - #4422

Merged
sailist merged 3 commits into
mainfrom
bug-303-10-26-workspace-instance-leak
Oct 26, 2026
Merged

sailist merged 3 commits into
mainfrom
bug-303-10-26-workspace-instance-leak

Conversation

@sailist

@sailist sailist commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

常驻 kap-server 在 session 归档、关闭或临时调用结束后仍保留 workspace instance 与 baseline MCP,导致内存和 stdio 子进程持续增长。

Bug Reproduction Steps

  1. 启动 kap-server,在独立 workspace 中配置一个真实 stdio MCP server。
  2. 创建该 workspace 的唯一 session,并等待 MCP 进入 connected 状态。
  3. 归档该 session。
  4. 修复前,session 已从 live 列表消失,但 workspace 仍处于 materialized 状态,MCP 仍 connected,子进程也不退出;只有整个服务进程退出或显式强制 close 才会回收。

Root Cause

WorkspaceInstanceManager.getOrCreate() 返回没有 owner 的共享实例,生产路径只在 App 进程退出时关闭它。Session controller 退休也不会释放 workspace 或 Program 代际资源。与此同时,Program 和 baseline MCP 的部分清理是 fire-and-forget,stdio close 只发送 kill,不等待真实退出。

这是根本修复:为每次使用建立明确的 lease ownership,最后引用释放即回收,并让后续使用在旧清理完成后重新 materialize,而不是增加定时 reaper 或保留进程级缓存。

Code Changes

 WorkspaceInstanceManager
- getOrCreate() -> 无 owner 的共享实例,进程退出时才 close
+ acquire() -> 每个调用方持有独立、幂等的 lease
+ last release -> 同步摘除实例 -> 等待清理 -> 后续 acquire 重建
+ closing / attachment 按 instance identity 隔离,attach 与 release 可安全并发

 SessionManager 与调用方
+ controller entry 持有长期 lease,并以 operationCount 保护生命周期操作
+ create/resume/archive/delete/fork/createChild 与临时调用按实际时长持 lease
+ fs 普通请求在 finally 释放,下载流在 end/close 才释放

 清理链
+ Program 汇总并等待代际清理,baseline MCP shutdown 可等待
+ stdio close 在 kill 后等待真实进程退出
+ persist: true 目录跨重建恢复,persist: false 随零引用清空

createRuntimeFs 仍保留纯 runtime 的同步构造;新增外层 acquireWorkspaceFs 组合 lease,因此根目录 /fs::suggest 仍不注册或 materialize workspace。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
无 owner workspace 的生命周期 保留到 kap-server/ACP 进程退出 最后一个 session、操作或临时 lease 释放后立即回收 使用 desktop、web、VS Code、ACP、SDK、klient 或 print 模式并归档 session 的用户 无;后续使用会重新 materialize,MCP 冷启动是已接受的成本
共享 workspace 与进行中操作 没有按 owner 区分的回收边界 等所有 live session、controller 操作和流都离开后才回收 多 session 共用 workspace、fork/resume 及下载流使用者 不适用;使用期间仍保持实例存活
persist: false additional dirs 在 workspace 内共享并保留到进程退出 零引用回收时清空,冷重建后不再出现 VS Code /add-dir、desktop/web 与 SDK 的非持久化目录调用 使用 persist: true 写盘并在重建后恢复
baseline stdio MCP 关闭 kill 发出后清理即可返回 等待连接关闭和真实进程退出后才完成 closing 配置 stdio MCP 的 desktop、web、VS Code、ACP 与 SDK 用户 无;这是避免旧进程跨实例存活的必要语义
内部 workspace API getOrCreate() 返回 raw instance,programForSession() 返回 raw Program acquire() / lease 包装实例 private agent-core-v2 包的仓库内调用方 该包为 private;仓库内调用方均已迁移,公开 SDK 方法签名不变

受影响模块与覆盖:

  • WorkspaceInstanceManager / SessionManager / Program:独立 lease、重复释放、last-release 竞态、慢 attach、代际切换、失败与冷操作回收。
  • kap-server:真实 stdio MCP 归档退出、共享 session 最后释放、cold restore/delete、fs 普通请求与下载流、persist 两种目录的冷重建。
  • node-sdk、klient、CLI、ACP、VS Code:对应临时调用与生命周期回归;VS Code 非持久化目录测试更新为新的零引用语义。
  • m0-dev 全量:900 个测试文件、17,451 个测试通过,7 个文件、38 个测试按配置跳过。
  • corepack pnpm build、corepack pnpm lint 通过;agent-core-v2、kap-server、node-sdk、klient、CLI typecheck 全部通过。

Checklist

  • 已阅读 CONTRIBUTING。
  • 无独立 GitHub issue;本 PR 已直接提供复现步骤、根因和影响范围。
  • 已通过改造现有测试覆盖本修复,测试声明数量没有净增长。
  • 行为变化表已完整列出;persist: false 的保留替代是 persist: true,其余即时回收与等待退出均为修复所需的语义。
  • 已运行 gen-changesets 并提交 .changeset/reclaim-idle-workspaces.md。
  • 无需额外文档更新;过时的 SDK 注释已同步修正,现有文档未描述进程级保留语义。

- hold reference-counted leases across sessions and temporary callers
- await MCP and stdio process cleanup before rebuilding instances
- restore persisted directories and clear ephemeral directories on reclamation
@changeset-bot

changeset-bot Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 696228f

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 26, 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-26T11:01:33.638748Z 696228f 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 26, 2026 •

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

commit: 696228f

@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: 6f5042b690

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

if (process !== undefined) {
try {
await process.kill();
await process.wait();

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 Bound MCP termination before awaiting exit

When a stdio MCP server traps or ignores SIGTERM, HostProcess.kill() only sends that signal and this newly added wait() never settles. Workspace disposal consequently remains in the manager's closing map, so every later acquisition of that workspace waits forever and application shutdown can also hang; use a bounded wait with forced termination rather than awaiting an uncooperative child indefinitely.

Useful? React with 👍 / 👎.

"@moonshot-ai/kimi-code": patch
---

Fix workspace resource leaks by releasing resources when no live sessions remain.

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 Name the loss of non-persisted directories

The updated VS Code integration test establishes that a persist: false directory is now discarded after the last session closes and is absent after resume, but this changeset only mentions resource reclamation. Users of VS Code and SDK add-dir flows therefore will not learn about the removed retention behavior or that persist: true is the available alternative; state that loss explicitly in the release entry.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

} catch (error) {
disposalError = error;
}
await this.manager.shutdown();

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 Wait for MCP startup before completing disposal

If the last workspace lease is released while initialize() is still awaiting MCP config or identity readiness, this shutdown sees an empty manager and completes, but initialize() can subsequently resume and call connectAll(). Temporary workspace operations such as skill listing do not await MCP readiness, so an HTTP MCP connection can be created after the workspace has already been removed and never receive another shutdown; prevent initialization after disposal or await outstanding initialization and mutations before the final shutdown.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

该竞态只发生在冷启动或重建后的极短窗口,目前没有实际触发证据,本 PR 暂不处理,后续再单独跟进。

7Sageer
7Sageer previously approved these changes Oct 26, 2026
- escalate stdio shutdown to SIGKILL after a bounded SIGTERM grace
- cover workspace reacquisition while an uncooperative MCP is closing

@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: 7945eafce9

ℹ️ 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.references.set(instance.id, references - 1);
return;
}
void this.close(instance);

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 Retain the workspace for the whole MCP probe

When global.mcp.testServer probes a stdio server using a cwd inside a materialized workspace, McpManagementService.withProbe() only obtains the raw instance via findContaining() and holds no lease while connectAll() runs. If the final session is archived or closed concurrently, this release path immediately removes and disposes that workspace, so the probe's subsequent RuntimeResolver.acquire() can fail with runtime.not_found or lose its runtime mid-probe; before this change the instance remained alive. Acquire a workspace lease for this path and release it after the probe's shutdown.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

- hold the containing workspace lease until stdio probe shutdown completes
- cover lease ordering across connection and shutdown

@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: 696228ff50

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

const workspace = this.workspaceInstances.findContaining(stdioCwd);
if (workspace !== undefined) {
workspaceId = workspace.id;
workspaceLease = await this.workspaceInstances.acquire({ workspaceId: workspace.id });

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 Preserve the root when leasing the probe workspace

When a workspace has been unregistered while one of its sessions is still live, findContaining() returns the still-materialized instance, but this ID-only acquire() calls IWorkspaceService.get() and throws WORKSPACE_NOT_FOUND because no root fallback was supplied. Consequently, SDK or /api/v2/mcp test-server requests with a cwd inside that live workspace now fail, whereas the previous code probed through the existing raw instance; acquire with both the workspace ID and its root.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 2e539f2 into main Oct 26, 2026
27 of 28 checks passed
@sailist
sailist deleted the bug-303-10-26-workspace-instance-leak branch October 26, 2026 11:55
This was referenced Oct 27, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 4, 2026
`WorkspaceInstance.dispose()` only isolated `program.dispose()`. A throw
from `unitHost.dispose()` or `runtimes.dispose()` aborted the remaining
cleanup and left `lifecycle` stuck at `closing`, so the instance never
reached `disposed` and whatever came after it — the runtimes' process
teardown included — never ran.

All three parts now run regardless, the first failure is rethrown as-is and
several become an `AggregateError`, matching the disposal contract the
reference-counted manager already relies on.

Local-form note: the rest of MoonshotAI#4422 was already in this tree — the fork's
`IWorkspaceInstanceManager` is `acquire() → WorkspaceInstanceLease` with no
`getOrCreate`/`close`, the manager keeps `closing`/`release()` reference
counting, `client-stdio` carries the same `STDIO_TERMINATION_GRACE_MS`
SIGKILL escalation, `workspaceMcpService.disposeAsync()` is wired through
`program.ts`, and `mcpManagementService` already holds the workspace lease
across a probe. Only this dispose gap was missing.

Verified: agent-core-v2 typecheck clean; workspace + mcpManagement suites
383 pass. Reverting the try/catch pair reddens the new
`keeps disposing the remaining parts when one of them throws` case.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 4, 2026
The reference-counted lease reclamation was already in the tree; only the
`WorkspaceInstance.dispose()` error isolation was missing and landed in
a3f3521.
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