Skip to content

perf(agent-core-v2): shard the session event bus by agent id - #3775

Merged
RealKai42 merged 8 commits into
MoonshotAI:mainfrom
huangzheng2016:perf/event-bus-sharding
Sep 15, 2026
Merged

RealKai42 merged 8 commits into
MoonshotAI:mainfrom
huangzheng2016:perf/event-bus-sharding

Conversation

@huangzheng2016

Copy link
Copy Markdown
Contributor

Related Issue

No tracking issue — internal performance work.

Problem

In sessions with many concurrent subagents (large AgentSwarm runs), every agent's events flow through one shared allEmitter in the session event bus, and every per-agent view (AgentEventBusView) attaches an agentId filter closure to it. Each streamed delta therefore costs O(live agents) closure calls plus an O(L) listener-array snapshot (Emitter.fire).

Load test (5 rounds × 128 subagents of identical work per round): GC runs per round grew 281 → 1542 and event-loop p99 grew 25ms → 135ms across rounds — per-event cost scales with the number of live agents.

What changed

  • EventBusService gains a sharded perAgent channel map (Map<agentId, Emitter>); publish fires in a fixed order: all → perType → perAgent.
  • AgentEventBusView subscribes to its own agent's channel instead of wrapping the global emitter with a filter closure — same event set, same order, O(1) delivery.
  • onAgent migrates to the sharded channel (same activation checks); listenerCounts() gains a perAgent field (additive, old shape unchanged); deactivateAgent disposes the agent's channel so finished agents leave no emitters behind.
  • kap-server's three per-agent consumers (sessionEventBroadcaster, sessionProjection, transcript coreBinding) migrate automatically via the view change — WS/klient payload bytes are unchanged.
  • Tests: sharded delivery semantics, generation isolation, listener counts, channel cleanup, broadcaster integration.

Compatibility: the raw global stream and the per-type channel keep their exact semantics, so the only global consumers (kap-server WS broadcast, tests) are untouched; klient does not use this bus.

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/shard-session-event-bus-by-agent.md, minor).
  • 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: a4ce987

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 Sep 14, 2026 •

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

commit: a4ce987

@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: d82d3ebd87

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

Comment on lines +199 to +200
return this.bus.subscribeAgent(this.agent, (event) => {
if (event.type === type) handler!(event);

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 full-stream-before-typed ordering in agent views

When a typed handler is registered before a full-stream handler on the same AgentEventBusView, both now share the per-agent emitter and run in registration order, producing typed → full. The parent EventBusService guarantees full → typed regardless of registration order, and the previous view preserved that by using separate all/per-type emitters; callers mixing both subscription forms can therefore observe reversed side-effect ordering. Keep separate dispatch phases or otherwise preserve the existing IEventBus ordering.

Useful? React with 👍 / 👎.

readonly scopePath: string;
readonly all: number;
readonly perType: Record<string, number>;
readonly perAgent: Record<string, number>;

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 Render the new per-agent listener counts in the inspector

After agent-view subscriptions move off all and perType, their real counts exist only in this new field, but apps/kimi-inspect/src/components/di/DiEventsPanel.tsx:109-123 still renders only bus.all and bus.perType. Consequently, sessions using the sharded channels appear to have zero bus listeners in the Events panel even when many are attached, defeating the debug snapshot's purpose; extend busRows to display perAgent entries.

Useful? React with 👍 / 👎.

…nt channels and render perAgent counts in the inspector

@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: 557923cd7a

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

Comment on lines +103 to +104
channel = new AgentChannel(agentId);
this.perAgent.set(agentId, channel);

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 Dispose sharded channels with the event bus

When EventBusService is disposed while an agent channel remains live—for example during service re-provisioning or teardown before every agent finalizer runs—Service.dispose() closes only emitters added through _register; this newly created channel is never registered, and no override disposes or clears perAgent. The disposed bus therefore retains these listeners and publish(..., agent) can continue invoking them, unlike the previous implementation where every delivery emitter was owned by the bus's disposable store. Explicitly close and clear all current agent channels when the bus is disposed.

Useful? React with 👍 / 👎.

Comment on lines +67 to +69
this.perType.get(event.type)?.fire(event);
const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId);
channel?.all.fire(event);

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 Deliver agent full streams before session typed handlers

When a session-level typed handler and an agent-view full-stream handler observe the same agent event, the global typed emitter now fires before the agent full-stream emitter. Before sharding, the view's full-stream handler was attached to allEmitter, so it always ran before every per-type handler; concrete consumers coexist for events such as TurnEnded, where session services use typed subscriptions while SessionEventBroadcaster uses the agent view's full stream. Fresh evidence after the earlier review is that the added fix preserves ordering only inside the agent channel while these lines still reverse the cross-channel order, leaving observable side effects reordered.

Useful? React with 👍 / 👎.

@huangzheng2016

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 557923cd7a

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

…andlers and dispose sharded channels with the bus
@huangzheng2016

Copy link
Copy Markdown
Contributor 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: b5f0bc581d

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

Comment on lines +109 to +110
channel = new AgentChannel(agentId);
this.perAgent.set(agentId, channel);

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 Prevent rebuilding agent channels after bus disposal

When a stale AgentEventBusView subscribes after EventBusService.dispose() during teardown or service re-provisioning, this path creates a fresh, non-disposed AgentChannel because the override only clears channels that existed at disposal time. The agents map also remains populated, so a subsequent agent-domain publish passes activation validation and invokes the new listener even though the global emitters remain closed. Fresh evidence after the earlier disposal fix is this post-disposal recreation path; prevent channel creation once the bus's disposable store is closed.

Useful? React with 👍 / 👎.

@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: 61c660b529

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

@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor

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 Use a patch bump for this performance change

This change improves performance but adds no new user capability, so the minor entry will unnecessarily advance the CLI's minor version; the repository changeset rules classify small improvements as patch, so downgrade this entry accordingly.

AGENTS.md reference: AGENTS.md:L86-L88

Useful? React with 👍 / 👎.

Comment on lines +68 to +69
const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId);
channel?.all.fire(event);

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 Isolate channels when replacing an agent generation

When a new AgentContext is activated for an existing agent ID before the stale context is deactivated—a sequence explicitly exercised by the new stale-generation test—both generations retain the same ID-keyed channel. A non-agent-domain event such as CronFired published with the new context is consequently delivered to the stale view too, whereas the previous sourceOf(event) === this.agent check isolated those events by context identity; dispose or replace the channel when activation replaces its context.

Useful? React with 👍 / 👎.

Comment on lines +70 to +71
this.perType.get(event.type)?.fire(event);
channel?.perType.get(event.type)?.fire(event);

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 typed-handler registration order across channels

When an agent-view typed handler is registered before a session-level typed handler for the same event, both previously occupied the shared perType emitter and therefore ran in registration order. These separate dispatch phases now always invoke the session handler first, reversing observable side-effect ordering for that registration sequence; preserve a common ordering mechanism for typed subscriptions while retaining the sharded lookup.

Useful? React with 👍 / 👎.

…keep typed handlers on the shared per-type channel

@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: ec9246df4d

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

Comment on lines +73 to +74
const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId);
channel?.all.fire(event);

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 Validate the context before firing the agent channel

When a lifecycle generation is replaced, a late non-agent-domain event published by the stale generation is now delivered to the new generation's full-stream subscribers because this lookup uses only agentId; the active-context check above applies only to AgentEvent2. This can occur with observable agent-scope events such as CronFired, which is dispatched from an asynchronous promise continuation, and causes broadcasters or transcript projectors attached to the replacement view to process stale events. Fresh evidence after the earlier generation-replacement fix is that replacing the channel removes old listeners but does not prevent stale publishers from selecting the replacement channel; require the supplied context to still be active before firing it.

Useful? React with 👍 / 👎.

@huangzheng2016

Copy link
Copy Markdown
Contributor 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: 3602bb9d54

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

): IDisposable {
if (this.disposedBus) return Disposable.None;
if (typeof typeOrHandler === 'function') {
return this.channelFor(agent.agentId).all.event(typeOrHandler);

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 Reject stale contexts when subscribing to agent channels

During overlapping teardown and recreation of the same agent ID, a retained view from the old generation can subscribe after activateAgent has installed the replacement context; this code selects the replacement channel using only agentId, so a non-agent-domain event published by the replacement is delivered to the stale view too. Previously, the full-stream filter compared sourceOf(event) with the view's exact context and rejected that event. Fresh evidence beyond the earlier generation-isolation comment is this post-replacement subscription path; validate that agent is still active before attaching it to the channel.

Useful? React with 👍 / 👎.

@huangzheng2016

Copy link
Copy Markdown
Contributor 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: c19b8cef9a

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

}
return this.channelFor(agent.agentId).all.event(typeOrHandler);
}
return this.subscribe(typeOrHandler, handler!);

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 Honor the agent in typed subscribeAgent calls

When a caller uses the newly exposed three-argument subscribeAgent(agent, type, handler) overload, this branch discards agent and registers the handler on the session-wide per-type emitter. An event of that type published by any other agent therefore invokes the handler, defeating the method's agent-scoped contract; either remove this unused overload or apply the same agent/context filtering as the view's typed subscriptions.

Useful? React with 👍 / 👎.

@huangzheng2016

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: a4ce987be4

ℹ️ 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 f248624 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