Skip to content

fix(issue #2528): index active RuntimeContext by runId for concurrent multi-session support - #2531

Closed
xzxiaoshan wants to merge 12 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/runtime-context-runid-and-active-rc-concurrent
Closed

xzxiaoshan wants to merge 12 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/runtime-context-runid-and-active-rc-concurrent

Conversation

@xzxiaoshan

@xzxiaoshan xzxiaoshan commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

问题

ReActAgent.activeRc 是一个 private volatile RuntimeContext 单字段。当同一 agent 实例上多个不同 (userId, sessionId) 会话并发调用时,后启动的调用会覆写前一个的 RuntimeContext,导致:

  • 跨会话上下文泄漏(用户 A 的工具读到用户 B 的 session/tenant)
  • getRuntimeContext() 在并发下返回错误会话或 null
  • 偶发性状态丢失,难以复现

ISSUE:#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.using cleanup)中调用 activeContexts.remove(context.getRunId()),保证 complete / error / cancel 全路径覆盖
  • 查询:getRuntimeContext(String runId) 精确查找;getActiveRuntimeContexts() 返回只读快照

3. API 变更

变更 说明
RuntimeContext.getRunId() 新增,始终非空
Agent.getRuntimeContext(String runId) 新增,按 runId 精确查找
Agent.getActiveRuntimeContexts() 新增,返回活动上下文
AgentBase.runLifecycle(msgs, context, doCallFn) 新增 context 参数
AgentBase.afterAgentExecution(RuntimeContext context) 新增 context 参数
ReActAgent.getRuntimeContext() (无参) 移除,使用 runId 重载替代
HarnessAgent.promoteSkill(name, reviewerId, runId) 新增 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。
  • 运行时 ctx 全程显式传入:中间件 onSystemPrompt(ctx)、skill_manage 工具
    ToolCallParam.getRuntimeContext()、SkillPromoter.promote(..., ctx)。

(按照操作手册指南,HarnessAgent 的使用本就需要主动传入 RuntimeContext 所以 currentRcSupplier 的 currentContext 链路也不走)

API 变更表补充:

变更 说明
WorkspaceSkillRepository 带 Supplier<RuntimeContext> 构造器 @deprecated 标记废弃,改用无 supplier 构造器

@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@codecov

codecov Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/core/agent Agent runtime, pipeline, hooks, plan area/examples agentscope-examples area/harness agentscope-harness (test/runtime support) labels Aug 11, 2026
…runid-and-active-rc-concurrent

# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
@xzxiaoshan
xzxiaoshan force-pushed the feat/runtime-context-runid-and-active-rc-concurrent branch from d95744e to 1074795 Compare August 24, 2026 10:34
@guslegend0510

Copy link
Copy Markdown
Contributor

感谢修复 activeRc 的并发覆盖问题,使用 runId 索引活动上下文的方向是合理的。不过当前实现还有几处会影响会话隔离和运行稳定性的阻塞问题,暂时不建议合并:
AgentBase.runLifecycle() 不再从 Reactor Context 读取 RUNTIME_CONTEXT_KEY,但 legacy stream(..., RuntimeContext) 仍只通过 Reactor Context 传递上下文。这会导致 userId/sessionId/attributes 丢失,状态写入默认 session。

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,避免下游源码或二进制直接失效。
建议补充以下回归测试后再合并:
legacy stream(..., context) 的 session 隔离;
normal/native/fallback 路径无 dropped error;
error/cancel cleanup;
重复 runId/复用 Builder;
Harness namespaced skill create/edit/delete;
RuntimeContextAware hook 的双 session 并发。
修复方向本身没有问题,但以上几项会直接影响生产环境的多用户隔离,建议本轮先处理。

@xzxiaoshan

xzxiaoshan commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

我来做进一步分析优化代码。只是有一点要讨论的是:引入无状态并行多 RuntimeContext 的情况下,无参 getRuntimeContext() 是破坏性的,返回任何一个 RuntimeContext 都是不合理的,如果只是返回最后一个 RuntimeContext ,恐会给项目带来其他问题。
感觉不保留无参的 getRuntimeContext 更合适,理由是框架使用者升级版本后,能直接性的在编译层面直接发现问题而不是隐性的还可以使用这个方法。

@guslegend0510

Copy link
Copy Markdown
Contributor

感谢修复 activeRc 的并发覆盖问题,使用 runId 索引活动上下文的方向是合理的。不过当前实现还有几处会影响会话隔离和运行稳定性的阻塞问题,暂时不建议合并: AgentBase.runLifecycle() 不再从 Reactor Context 读取 RUNTIME_CONTEXT_KEY,但 legacy stream(..., RuntimeContext) 仍只通过 Reactor Context 传递上下文。这会导致 userId/sessionId/attributes 丢失,状态写入默认 session。

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,避免下游源码或二进制直接失效。 建议补充以下回归测试后再合并: legacy stream(..., context) 的 session 隔离; normal/native/fallback 路径无 dropped error; error/cancel cleanup; 重复 runId/复用 Builder; Harness namespaced skill create/edit/delete; RuntimeContextAware hook 的双 session 并发。 修复方向本身没有问题,但以上几项会直接影响生产环境的多用户隔离,建议本轮先处理。

认同你的判断:在同一 Agent 存在多个并发 RuntimeContext 时,无参 getRuntimeContext() 不应该返回最后一个或任意一个上下文,否则容易产生隐蔽的串会话问题。
我提出兼容性问题,并不是要求继续保留原来的错误语义。可以考虑保留一个 deprecated compatibility bridge:
没有活动上下文时返回 null;
只有一个活动上下文时返回该上下文;
存在多个活动上下文时明确抛出 IllegalStateException,提示调用方改用 getRuntimeContext(runId)。
这样既不会在并发时静默返回错误上下文,也能避免已有二进制直接出现 NoSuchMethodError。如果项目决定接受 breaking change,也建议明确记录迁移方式。
不过,无参方法是否保留并不是当前 review 的主要阻塞点。以下运行时问题仍需要单独处理:
HarnessAgent.currentRcSupplier 目前调用 getRuntimeContext(null),按新实现它永远返回 null,所以 namespaced skill 操作会退化到空上下文/default namespace。
legacy stream(..., RuntimeContext) 写入的是 Reactor Context,但新的 runLifecycle 不再读取它;我这边已复现指定 session 没有消息、消息进入 default session。
CallExecution.runId 没有赋值,三处 activeContexts.remove(scope.runId) 会执行 remove(null);我这边已捕获到 Reactor dropped NPE。
相同 runId 并发时,当前的 put 加按 key 删除仍可能覆盖或误删另一个活动调用。
因此,无参 API 的处理方案可以继续讨论,但上述运行时回归仍建议在本轮修复并补测试后再合并。

…nups, keep getRuntimeContext() as a validated bridge, document RuntimeContextAware concurrency limitation
…ll RuntimeContext, not a build-time supplier
@xzxiaoshan
xzxiaoshan force-pushed the feat/runtime-context-runid-and-active-rc-concurrent branch from 32af19e to c75688f Compare August 28, 2026 10:03
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

一、已完成代码优化处理:优化处理 Reactor Context 二级回退、移除 doFinally 死代码、保留(标记为废弃) getRuntimeContext() 这个方法并增加兼容逻辑处理、同一个runId不允许并发执行的逻辑补充、补充 RuntimeContextAware 的javadoc说明。
二、优化对 HarnessAgent 这条线的 使用 current 方式的 RuntimeContext 的处理(currentRcSupplier 相关)。
@guslegend0510

@guslegend0510 guslegend0510 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

…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
oss-maintainer pushed a commit that referenced this pull request Sep 24, 2026
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.
@CLAassistant

CLAassistant commented Sep 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@xzxiaoshan
xzxiaoshan force-pushed the feat/runtime-context-runid-and-active-rc-concurrent branch from f7c389b to 06d2959 Compare September 24, 2026 16:37
@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged (mergeable: CONFLICTING). Please rebase or merge main into feat/runtime-context-runid-and-active-rc-concurrent and resolve the conflicts:

git fetch origin
git checkout feat/runtime-context-runid-and-active-rc-concurrent
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This 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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 — duplicate runId now 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 on supplied, eviction on the resolved rc (possibly empty()): 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

Comment on lines +276 to +290
// 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."));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Comment on lines +944 to +947
* @param runId the per-call run id (from {@link RuntimeContext#getRunId()})
*/
@Override
public void interrupt(String runId) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +684 to +688
protected void afterAgentExecution(RuntimeContext rc) {
if (rc != null) {
activeContexts.remove(rc.getRunId(), rc);
}
unbindRuntimeContextFromHooks();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

该PR,已通过 #3279 聚合整理合入 main 分支。

@xzxiaoshan xzxiaoshan closed this Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/agent Agent runtime, pipeline, hooks, plan area/examples agentscope-examples area/harness agentscope-harness (test/runtime support) bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants