Repository navigation
fix(workspace): reclaim instances when last owner releases - #4422
Conversation
- 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 detectedLatest commit: 696228f The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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(); |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
该竞态只发生在冷启动或重建后的极短窗口,目前没有实际触发证据,本 PR 暂不处理,后续再单独跟进。
- escalate stdio shutdown to SIGKILL after a bounded SIGTERM grace - cover workspace reacquisition while an uncooperative MCP is closing
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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 }); |
There was a problem hiding this comment.
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 👍 / 👎.
`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.
The reference-counted lease reclamation was already in the tree; only the `WorkspaceInstance.dispose()` error isolation was missing and landed in a3f3521.
Requirement or Bug
常驻 kap-server 在 session 归档、关闭或临时调用结束后仍保留 workspace instance 与 baseline MCP,导致内存和 stdio 子进程持续增长。
Bug Reproduction Steps
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
createRuntimeFs仍保留纯 runtime 的同步构造;新增外层acquireWorkspaceFs组合 lease,因此根目录/fs::suggest仍不注册或 materialize workspace。Behavior Changes and Affected Users
persist: falseadditional dirs/add-dir、desktop/web 与 SDK 的非持久化目录调用persist: true写盘并在重建后恢复getOrCreate()返回 raw instance,programForSession()返回 raw Programacquire()/ lease 包装实例agent-core-v2包的仓库内调用方受影响模块与覆盖:
WorkspaceInstanceManager/SessionManager/Program:独立 lease、重复释放、last-release 竞态、慢 attach、代际切换、失败与冷操作回收。persist两种目录的冷重建。corepack pnpm build、corepack pnpm lint通过;agent-core-v2、kap-server、node-sdk、klient、CLI typecheck 全部通过。Checklist
persist: false的保留替代是persist: true,其余即时回收与等待退出均为修复所需的语义。gen-changesets并提交.changeset/reclaim-idle-workspaces.md。