Skip to content

fix(agent-core-v2): release disposed agent scopes from the DI dependency graph - #3776

Merged
RealKai42 merged 2 commits into
MoonshotAI:mainfrom
huangzheng2016:perf/scope-dispose-leak
Sep 15, 2026
Merged

RealKai42 merged 2 commits into
MoonshotAI:mainfrom
huangzheng2016:perf/scope-dispose-leak

Conversation

@huangzheng2016

Copy link
Copy Markdown
Contributor

Related Issue

No tracking issue — internal performance work.

Problem

Disposing an agent scope (disposeAsync()) tears down its services, but the child container object stays linked in four places: CascadeTree._scopeSeq, DependencyGraph._in scope keys, anonymous unit edge nodes (e.g. tool instances), and the scope-unit provider book (a closure capturing the container). The whole per-scope service graph (~0.4–0.6MB per scope) therefore remains reachable forever.

Found via heap-snapshot retainer-chain analysis after large AgentSwarm runs: 385 disposed agent scopes were still fully resident (AgentStateService / AgentProfileService / EventDispatcherService / AgentLoopService ×385).

What changed

  • DependencyGraph.removeScope(scope) + PairIndex.deleteScope() — drops the scope's instances, _in scope keys, and outgoing edges (emptied inner maps are cleaned up too).
  • CascadeTree.dropScope(scope) — removes _scopeSeq/_inFlight entries, with a _droppedScopes WeakSet so an in-flight cascade transaction cannot reinsert a disposed scope (race covered by a dedicated test).
  • InstantiationService tracks anonymous unit edge nodes and calls removeScope(this) at the end of disposeCore — containers now detach themselves on dispose, no caller-side change needed.
  • scopeUnits releases the provider-book registration on scope death (idempotent for either death order).
  • Tests: BFS unreachability of a disposed child (services, anonymous nodes, parent), cascade-in-flight dispose race (red without the reinsert guard), parent cascades still settle after detach.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (N/A — internal perf work).
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill (.changeset/fix-disposed-subagent-scope-leak.md, patch).
  • Ran gen-docs skill, or this PR needs no doc update (no user-facing doc change).

@changeset-bot

changeset-bot Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 85163c0

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 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: f9326ab2fd

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

@@ -524,6 +526,7 @@ export class InstantiationService implements IInstantiationService {
}

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 Stop retaining retired service instances in _edgeNodes

When a service-backed FiberRuntime records a dependency, node is the service instance itself, so this adds every such instance to a scope-lifetime strong Set. Cascade replacement later calls _retireUnit, whose ledger entry removes the old instance from DependencyGraph, but nothing removes it from _edgeNodes; repeated updates in a long-lived app/session scope therefore retain every retired service graph until the entire scope is disposed, introducing another unbounded memory leak while fixing the child-scope leak. Track only otherwise-unowned anonymous nodes, or remove tracked nodes whenever their unit is retired.

Useful? React with 👍 / 👎.

@pkg-pr-new

pkg-pr-new Bot commented Sep 14, 2026 •

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

commit: 85163c0

@huangzheng2016

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 85163c03a5

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

@RealKai42
RealKai42 merged commit 48fad6e into MoonshotAI:main Sep 15, 2026
15 checks passed
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Oct 5, 2026
Step 5 of the incremental sync to 2.1.1: 14 upstream commits over 230
files. The bulk is the pi-tui re-baseline onto upstream v0.85.1.

Upstream's changes in this step, all absorbed:
- pi-tui re-baselined on upstream v0.85.1 (MoonshotAI#3780): the native platform
  modules were consolidated and renamed (darwin-modifiers ->
  darwin-platform, win32-console-mode -> win32-platform), a Linux/X11
  clipboard backend with prebuilds was added, and alt-screen search,
  autocomplete, editor, input, markdown and the render path were
  reworked; the native-asset copy scripts and flake.nix follow
- the session event bus is sharded by agent id (MoonshotAI#3775)
- disposed agent scopes are released from the DI dependency graph (MoonshotAI#3776)
- swarm cancellation no longer crashes the CLI (MoonshotAI#3779)
- tower mode no longer mistakes newly spawned agents for the previous
  name (MoonshotAI#3752)
- [secondary_model].default_effort fails fast when unsupported (MoonshotAI#3785)
- the managed usage payload switched to the quota model (MoonshotAI#3787)
- kap-server verifies indexed search results against session sources (MoonshotAI#3631)
- web dist synced from code-app (MoonshotAI#3792); docs for the web slash-command
  table and flat-form skill naming (MoonshotAI#3772, MoonshotAI#3774)

Fork behaviour preserved through the re-baseline (pi-tui/UPSTREAM.md):
- every `keep` intent card still has a matching per-file diff: the
  width/grapheme clamps, editor history hooks, multi-root @-completion,
  inline slash autocomplete, CJK autolink, fullscreen nav fall-through,
  mouse dispatch (cropped rows, prompt-width clicks, search-field
  forwarding), and sixel graphics with the startup probe
- the fork's image/terminal-image, latex and layout extensions ride on
  upstream's v0.85.1 baseline
- the fork's i18n layer covers the new user-facing strings

Verification and the follow-up fixes are recorded in the next commit:
the fork's auth-facade test still asserted the pre-quota managed-usage
shape, and the node-sdk dts build had lost its i18n specifier rewriting
in the 0.42.0 merge (found by this step's root typecheck).
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