Repository navigation
fix(issue #2528): index active RuntimeContext by runId for concurrent multi-session support - #2531
xzxiaoshan wants to merge 12 commits into
Conversation
…tive contexts with runId
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…runid-and-active-rc-concurrent # Conflicts: # agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
d95744e to
1074795
Compare
|
感谢修复 activeRc 的并发覆盖问题,使用 runId 索引活动上下文的方向是合理的。不过当前实现还有几处会影响会话隔离和运行稳定性的阻塞问题,暂时不建议合并: HarnessAgent.currentRcSupplier 调用了 getRuntimeContext(null),而该方法对 null 固定返回 null。因此技能管理相关的无 context 操作会使用空上下文,在 namespaced filesystem 下可能读写错误的用户目录。 CallExecution.runId 目前没有赋值,但普通、native structured 和 fallback structured 路径的 doFinally 都会执行 activeContexts.remove(scope.runId)。实际会触发 ConcurrentHashMap.remove(null) 的 NPE,只是被 Reactor 作为 dropped error 隐藏,所以现有测试仍然显示通过。建议删除这三处内部清理,统一依赖外层 Mono.using cleanup。 runId 目前不能保证活跃调用间唯一:复用同一个 RuntimeContext.Builder 会生成相同 runId,builder(source) 也会复制 runId。Registry 使用覆盖式 put 和仅按 key 删除时,一个调用结束可能误删另一个仍在运行的调用。建议使用 putIfAbsent 检测冲突,并通过 remove(runId, context) 精确清理。 RuntimeContextAware hook 仍然通过共享字段接收上下文。两个 session 并发时,A 可能读到 B 的 context,任一调用结束也可能把另一个调用的 context 清空。因此当前还不能认为跨 session 并发已经完全安全。 另外,这次直接删除了无参 getRuntimeContext() 和二参 promoteSkill() 等公共方法,建议保留 deprecated compatibility bridge,避免下游源码或二进制直接失效。 |
|
我来做进一步分析优化代码。只是有一点要讨论的是:引入无状态并行多 RuntimeContext 的情况下,无参 getRuntimeContext() 是破坏性的,返回任何一个 RuntimeContext 都是不合理的,如果只是返回最后一个 RuntimeContext ,恐会给项目带来其他问题。 |
认同你的判断:在同一 Agent 存在多个并发 RuntimeContext 时,无参 getRuntimeContext() 不应该返回最后一个或任意一个上下文,否则容易产生隐蔽的串会话问题。 |
…nups, keep getRuntimeContext() as a validated bridge, document RuntimeContextAware concurrency limitation
…ll RuntimeContext, not a build-time supplier
32af19e to
c75688f
Compare
|
一、已完成代码优化处理:优化处理 Reactor Context 二级回退、移除 doFinally 死代码、保留(标记为废弃) getRuntimeContext() 这个方法并增加兼容逻辑处理、同一个runId不允许并发执行的逻辑补充、补充 RuntimeContextAware 的javadoc说明。 |
…tAgentState in favor of runId/RuntimeContext-scoped access
…runid-and-active-rc-concurrent # Conflicts: # agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java
Concurrent invocations of a shared agent must keep both their request context and execution control isolated. A shared `activeRc` can expose another call's context. A session-owned interrupt flag also cannot distinguish running A from queued B in the same session. This PR passes RuntimeContext explicitly and gives each execution its own cancellable handle. Closes #2528. Incorporates the explicit-context skill I/O approach and namespace regression coverage from #2531, with thanks to its author.
f7c389b to
06d2959
Compare
|
This PR currently conflicts with git fetch origin
git checkout feat/runtime-context-runid-and-active-rc-concurrent
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved. Automated notification by github-manager-bot |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Indexes the active RuntimeContext by per-call runId in AgentBase so concurrent multi-session calls on one agent instance stop overwriting each other, and adds interrupt(runId) / getRuntimeContext(runId) on the Agent interface. The design reads well — registration before Mono.using, identity-scoped eviction in afterAgentExecution(rc), and the RuntimeContextAware javadoc now states plainly that the shared-field hook contract is not concurrency-correct. Two things need attention: the duplicate-runId guard is a behavioural break for external callers, and this PR is currently unmergeable (CONFLICTING/DIRTY) — the rebase reminder was already posted on 2026-08-02, so it is not repeated here.
Findings
- [Warning]
AgentBase.java:276-290— duplicaterunIdnow errors the call; callers using deterministic run ids (session / request / trace id) will start failing, which deserves an explicit upgrade note. - [Info]
ReActAgent.java:944-947—interrupt(String runId)fails silently for an unknown id; make the missed interrupt observable. - [Info]
AgentBase.java:684-688— registration is keyed onsupplied, eviction on the resolvedrc(possiblyempty()): correct today, easy to mis-wire later; one javadoc sentence would help.
Cross-repo / cascade note
Agent gains four non-default methods (interrupt(RuntimeContext), interrupt(RuntimeContext, Msg), interrupt(String), interrupt(String, Msg)). Everything in this repo is updated (the AGUI/aistio/harness stubs included), but any out-of-tree Agent implementation will break at compile time. If the interface additions were default no-ops instead, the same change would be source-compatible for 2.0.x.
Automated review by github-manager-bot
| // RuntimeContext) is rejected without ever reaching the cleanup path, which | ||
| // would otherwise evict the original registration. | ||
| if (supplied != null) { | ||
| RuntimeContext previous = | ||
| activeContexts.putIfAbsent(supplied.getRunId(), supplied); | ||
| if (previous != null) { | ||
| return Mono.error( | ||
| new IllegalStateException( | ||
| "RuntimeContext runId '" | ||
| + supplied.getRunId() | ||
| + "' is already active on this agent; a" | ||
| + " RuntimeContext must not be reused across" | ||
| + " concurrent calls. Build a fresh" | ||
| + " RuntimeContext (or copy via" | ||
| + " RuntimeContext.builder(rc)) per call.")); |
There was a problem hiding this comment.
Making a duplicate runId a hard IllegalStateException is the right call for concurrent calls, but it is also a new failure mode for existing users: any caller that constructs a RuntimeContext with a deterministic runId (session id, request id, trace id) and calls the agent twice — even sequentially, if the first registration is still live — now gets an errored Mono instead of the previous silent overwrite. Could the release/upgrade notes call this out explicitly, and would it be worth keeping the guard scoped to concurrently live calls only (the map is already evicted in afterAgentExecution, so sequential reuse with a fixed runId would still work if an ended call is guaranteed to have unregistered)?
| * @param runId the per-call run id (from {@link RuntimeContext#getRunId()}) | ||
| */ | ||
| @Override | ||
| public void interrupt(String runId) { |
There was a problem hiding this comment.
interrupt(String runId) resolves through getRuntimeContext(runId) and returns silently when the id is unknown. Combined with the new @deprecated no-arg interrupt(), a caller that passes a stale or mistyped runId gets a no-op that looks like a successful interrupt. A debug-level log (or returning boolean / throwing for an unknown id) would make the missed interrupt observable.
| protected void afterAgentExecution(RuntimeContext rc) { | ||
| if (rc != null) { | ||
| activeContexts.remove(rc.getRunId(), rc); | ||
| } | ||
| unbindRuntimeContextFromHooks(); |
There was a problem hiding this comment.
afterAgentExecution(rc) removes (runId -> rc) with remove(key, value), which is correct — the comment claims the identity match makes cleanup safe. One asymmetry worth a javadoc line: registration only happens when supplied != null, while releaseExecution always passes the resolved rc (possibly RuntimeContext.empty()), so the empty fallback both skips registration and performs a no-op removal. Fine as written, just easy for the next reader to mis-wire if registration is ever moved to the resolved rc.
|
该PR,已通过 #3279 聚合整理合入 main 分支。 |
问题
ReActAgent.activeRc是一个private volatile RuntimeContext单字段。当同一 agent 实例上多个不同(userId, sessionId)会话并发调用时,后启动的调用会覆写前一个的 RuntimeContext,导致:getRuntimeContext()在并发下返回错误会话或 nullISSUE:#2528
方案
1. RuntimeContext 新增强制 runId
为 RuntimeContext 新增
runId字段,在Builder.build()中未显式设置时自动生成 UUID。getRunId()始终非空,作为 per-call 的权威 correlation id。2. activeRc 升级为 runId 索引的 ConcurrentHashMap
将
ReActAgent.activeRc(单 volatile 字段)替换为AgentBase.activeContexts(ConcurrentHashMap<String, RuntimeContext>),按 runId 索引:runLifecycle的Mono.deferContextual中,调用activeContexts.put(context.getRunId(), context)releaseExecution(Mono.usingcleanup)中调用activeContexts.remove(context.getRunId()),保证 complete / error / cancel 全路径覆盖getRuntimeContext(String runId)精确查找;getActiveRuntimeContexts()返回只读快照3. API 变更
RuntimeContext.getRunId()Agent.getRuntimeContext(String runId)Agent.getActiveRuntimeContexts()AgentBase.runLifecycle(msgs, context, doCallFn)AgentBase.afterAgentExecution(RuntimeContext context)ReActAgent.getRuntimeContext()(无参)HarnessAgent.promoteSkill(name, reviewerId, runId)4. HarnessAgent skill 链路:去除「current」supplier
HarnessAgent 的 skill 命名空间原先依赖
currentRcSupplier——build 时注入、运行时经getActiveRuntimeContexts()猜「当前」上下文,并发下是 TOCTOU 竞态,可能把无 ctx 操作绑到随机活跃session(跨会话串写)。本次移除该 mechanism:
WorkspaceSkillRepository:废弃带Supplier<RuntimeContext>的构造器,新增无 supplier 构造器;无 ctx 操作统一落
RuntimeContext.empty()(默认命名空间)。HarnessAgentBuilderSupport.composeSkillRepositories:废弃带 supplier 版本,新增无 supplier overload。onSystemPrompt(ctx)、skill_manage工具ToolCallParam.getRuntimeContext()、SkillPromoter.promote(..., ctx)。(按照操作手册指南,HarnessAgent 的使用本就需要主动传入 RuntimeContext 所以 currentRcSupplier 的 currentContext 链路也不走)
API 变更表补充:
WorkspaceSkillRepository带Supplier<RuntimeContext>构造器