Repository navigation
perf(agent-core-v2): shard the session event bus by agent id - #3775
Conversation
🦋 Changeset detectedLatest commit: a4ce987 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 |
commit: |
There was a problem hiding this comment.
💡 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".
| return this.bus.subscribeAgent(this.agent, (event) => { | ||
| if (event.type === type) handler!(event); |
There was a problem hiding this comment.
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>; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| channel = new AgentChannel(agentId); | ||
| this.perAgent.set(agentId, channel); |
There was a problem hiding this comment.
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 👍 / 👎.
| this.perType.get(event.type)?.fire(event); | ||
| const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId); | ||
| channel?.all.fire(event); |
There was a problem hiding this comment.
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 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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
|
@codex review |
There was a problem hiding this comment.
💡 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".
| channel = new AgentChannel(agentId); | ||
| this.perAgent.set(agentId, channel); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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 | |||
There was a problem hiding this comment.
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 👍 / 👎.
| const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId); | ||
| channel?.all.fire(event); |
There was a problem hiding this comment.
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 👍 / 👎.
| this.perType.get(event.type)?.fire(event); | ||
| channel?.perType.get(event.type)?.fire(event); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| const channel = agent === undefined ? undefined : this.perAgent.get(agent.agentId); | ||
| channel?.all.fire(event); |
There was a problem hiding this comment.
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 👍 / 👎.
…g an agent full-stream channel
|
@codex review |
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
…to an agent full-stream channel
|
@codex review |
There was a problem hiding this comment.
💡 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!); |
There was a problem hiding this comment.
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 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
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).
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
allEmitterin 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
EventBusServicegains a shardedperAgentchannel map (Map<agentId, Emitter>);publishfires in a fixed order: all → perType → perAgent.AgentEventBusViewsubscribes to its own agent's channel instead of wrapping the global emitter with a filter closure — same event set, same order, O(1) delivery.onAgentmigrates to the sharded channel (same activation checks);listenerCounts()gains aperAgentfield (additive, old shape unchanged);deactivateAgentdisposes the agent's channel so finished agents leave no emitters behind.sessionEventBroadcaster,sessionProjection, transcriptcoreBinding) migrate automatically via the view change — WS/klient payload bytes are unchanged.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
gen-changesetsskill (.changeset/shard-session-event-bus-by-agent.md, minor).gen-docsskill, or this PR needs no doc update (no user-facing doc change).