Skip to content

fix(runtime): isolate contexts and control individual agent runs - #3279

Merged
oss-maintainer merged 4 commits into
mainfrom
codex/fix-explicit-runtime-context
Sep 24, 2026
Merged

oss-maintainer merged 4 commits into
mainfrom
codex/fix-explicit-runtime-context

Conversation

@chickenlj

@chickenlj chickenlj commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

AgentScope-Java Version

2.0.4-SNAPSHOT

Description

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.

Request context ownership

  • Remove activeRc, agent-level getRuntimeContext(), and the deprecated RuntimeContextAware hook setter contract. Middleware and tool parameters are the context access points.
  • Remove Harness repository context suppliers and the context-less skill-promotion overload. Carry explicit context through skill lookup, creation, edits, resource operations, archiving and security rollback; context-less repository operations use the default namespace.
  • Update the PAW tool notification middleware to use its context parameter.

Execution control

  • Add lazy, single-subscription AgentRun<T> handles through ReActAgent/HarnessAgent prepareRun and prepareCall: unique run ID, status, terminal notification, immediate cancellation and cooperative interruption. A handle can be registered before subscription; terminal handles cannot affect later executions.
  • Move interruption out of AgentState into per-execution control. Session-targeted convenience methods select only the admitted execution; interrupting an idle session is a no-op. Nested calls get independent controls, while retries inside one invocation retain the owning handle.
  • Fix the session queue so cancelling queued B cannot release C ahead of running A. Cancellation, failure and completion retire the correct execution and shutdown registrations.
  • Bind graceful shutdown to each execution's control and explicitly resolved state. Queued calls cannot interrupt or save another call's state.
  • Add a service-owned run registry with owner/session checks and terminal cleanup. SessionTurnRunner registers handles before subscribing and cancels the exact handle instead of calling an agent-wide interrupt method.
  • Publish session.run_started with the SDK run_id. Authorized user.interrupt events can specify that ID. Cross-replica tickets carry a run fence; stale requests cannot cancel replacements. Invalid supplied IDs are rejected rather than falling back to session interruption.
  • Update English and Chinese SDK/context/service documentation. Immediate cancellation disposes reactive work; cooperative interruption retains the interrupted-reply/state-save path. Neither rolls back external effects nor forcibly stops blocking tools that ignore cancellation.

The Agent retains only lightweight controls needed for session-targeted interruption, not a RuntimeContext registry. Run lookup and authorization belong to the service. API removals are intentional for the current development version; no compatibility bridges are added.

User guide

  • Add the Chinese blog “Agent 执行控制最佳实践:取消、中断与运行中补充消息” and link it from the blog navigation.
  • Cover run/session identity, immediate cancellation versus cooperative interruption, queued calls, follow-up messages, Inbox delivery limits, correction-and-restart, timeouts, SSE ownership/reconnection, Service HTTP cancellation, approvals and shutdown.
  • Include docs/examples/execution-control/SessionRunGuide.java with ownership-aware registration, deadlines, interruption followed by new input, Inbox publication and event fan-out. The companion and Inbox/shutdown wiring compile against the current SDK with Java 17; navigation JSON and internal links were checked.

Validation

  • Formatting applied with mvn spotless:apply; Spotless checks and git diff --check passed.
  • 158 targeted tests passed across core (93), harness (52) and dataplane (13), including queued A/B/C cancellation, active cancellation, retry and nested-call isolation, shutdown ownership, sandbox release, registry cleanup, HTTP authorization/validation and stale remote run fencing.
  • Command: mvn -B -pl agentscope-core,agentscope-harness,agentscope-service/service-dataplane -am test -Dtest=AgentRunTest,ReActAgentRuntimeContextTest,GracefulShutdownTest,ReActAgentTest,ReActAgentInterruptToolCallTest,HarnessAgentTest,AgentRunRegistryTest,SessionTurnAdmissionTest,DataSessionRunCancellationTest -Dsurefire.failIfNoSpecifiedTests=false
  • The context/skill namespace regression suites also passed during the initial context-isolation change. Full local reactor verification has not been completed; at the author's request, local validation is limited to relevant tests rather than restarting the earlier Testcontainers-dependent full run. Full CI remains required.

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test) — targeted local suites passed; full CI pending
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

@chickenlj
chickenlj marked this pull request as ready for review September 24, 2026 10:12
Copilot AI lite review requested due to automatic review settings September 24, 2026 10:12

Copilot AI 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.

Copilot review overview

🟡 Changes recommended

Restore concurrent middleware regression coverage and update stale documentation examples and lifecycle descriptions.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 6 Low severity

Open (6)
What changed in this PR

This PR changes agent and skill execution to pass RuntimeContext explicitly, preventing cross-call context leakage.

Changes:

  • Removes shared runtime-context state and deprecated hook injection.
  • Propagates contexts through skill repositories, tools, promotion, and middleware.
  • Adds concurrency and namespace tests.
  • Updates English and Chinese documentation.
File Summary
docs/​v2/​zh/​docs/​building-blocks/​agent.md Documents explicit context usage.
docs/​v2/​zh/​blogs/​usecases/​logistics.md Updates context lifecycle guidance.
docs/​v2/​zh/​blogs/​usecases/​aidc-logistics.md Updates context lifecycle guidance.
docs/​v2/​en/​docs/​building-blocks/​agent.md Documents explicit context usage.
docs/​v2/​en/​blogs/​usecases/​logistics.md Updates context lifecycle guidance.
docs/​v2/​en/​blogs/​usecases/​aidc-logistics.md Updates context lifecycle guidance.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​tool/​SkillManageToolTest.java Updates repository setup.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​tool/​ProposeSkillToolTest.java Updates repository setup.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​skill/​WorkspaceSkillRepositoryTest.java Tests namespace isolation.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​skill/​curator/​SkillPromoterTest.java Updates promotion setup.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​skill/​curator/​SkillCuratorTest.java Updates curator setup.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​middleware/​HarnessSkillMiddlewareContextIsolationTest.java Tests context-isolated skill lookup.
agentscope-harness/​src/​test/​java/​io/​agentscope/​harness/​agent/​middleware/​HarnessSkillManageNamespaceTest.java Tests namespaced skill management.
agentscope-harness/​src/​main/​java/​io/​agentscope/​harness/​agent/​tool/​SkillManageTool.java Propagates contexts through skill operations.
agentscope-harness/​src/​main/​java/​io/​agentscope/​harness/​agent/​skill/​WorkspaceSkillRepository.java Adds explicit-context repository operations.
agentscope-harness/​src/​main/​java/​io/​agentscope/​harness/​agent/​skill/​curator/​SkillPromoter.java Uses explicit promotion contexts.
agentscope-harness/​src/​main/​java/​io/​agentscope/​harness/​agent/​HarnessAgentBuilderSupport.java Removes context supplier wiring.
agentscope-harness/​src/​main/​java/​io/​agentscope/​harness/​agent/​HarnessAgent.java Removes implicit context access.
agentscope-examples/​agents/​agentscope-paw/​src/​main/​java/​io/​agentscope/​claw2/​web/​toolbus/​ToolNotificationMiddleware.java Uses the per-call context.
agentscope-core/​src/​test/​java/​io/​agentscope/​core/​agent/​ReActAgentRuntimeContextTest.java Tests concurrent context isolation.
agentscope-core/​src/​main/​java/​io/​agentscope/​core/​ReActAgent.java Removes shared active context state.
agentscope-core/​src/​main/​java/​io/​agentscope/​core/​hook/​RuntimeContextAware.java Removes the deprecated hook contract.
agentscope-core/​src/​main/​java/​io/​agentscope/​core/​agent/​AgentBase.java Removes shared context injection.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.



**Reason two: full-link reachability.** `RuntimeContext` spans the complete lifecycle of an Agent from creation to execution; multiple downstream link nodes can consume it directly via `agent.getRuntimeContext()` without extra parameter passing:
**Reason two: full-link reachability.** `RuntimeContext` spans the complete lifecycle of an Agent from creation to execution; downstream tools and middlewares receive their own call context explicitly through method parameters:


**Reason two: full-link reachability.** `RuntimeContext` spans the complete lifecycle of an Agent from creation to execution; multiple downstream link nodes can consume it directly via `agent.getRuntimeContext()` without extra parameter passing:
**Reason two: full-link reachability.** `RuntimeContext` spans the complete lifecycle of an Agent from creation to execution; downstream tools and middlewares receive their own call context explicitly through method parameters:
## RuntimeContext (per-call context)

`RuntimeContext` (`io.agentscope.core.agent.RuntimeContext`) is a **per-call metadata bag**: pass one instance to `call` / `stream`, and the agent binds it for the duration of that call so downstream tools, middlewares, and hooks all observe the same reference. The framework unbinds it on completion.
`RuntimeContext` (`io.agentscope.core.agent.RuntimeContext`) is a **per-call metadata bag**. Pass a separate instance to each call; tools and middlewares receive the context through their parameters. The agent does not expose a shared current-context getter or inject contexts into shared hook fields. Skill repository operations and `HarnessAgent.promoteSkill(name, reviewerId, ctx)` likewise take an explicit context; context-less repository operations use the default namespace.
**原因一:线程安全。** 复用层底层是异步线程池模型,线程会被多个会话复用。如果通过 `ThreadLocal` 传递请求级数据,线程归还线程池后残留数据可能污染后续其他会话。`RuntimeContext` 由框架绑定到 `AgentBase` 实例上(per-agent-instance),随请求创建、随请求销毁,天然隔离,不存在跨会话串数据的风险。

**原因二:全链路可达。** `RuntimeContext` 贯穿 Agent 从创建到执行的完整生命周期,下游多个链路节点可以直接通过 `agent.getRuntimeContext()` 消费,无需额外传参:
**原因二:全链路可达。** `RuntimeContext` 贯穿 Agent 从创建到执行的完整生命周期,下游工具和中间件通过方法参数显式接收当次调用的上下文:
**原因一:线程安全。** 复用层底层是异步线程池模型,线程会被多个会话复用。如果通过 `ThreadLocal` 传递请求级数据,线程归还线程池后残留数据可能污染后续其他会话。`RuntimeContext` 由框架绑定到 `AgentBase` 实例上(per-agent-instance),随请求创建、随请求销毁,天然隔离,不存在跨会话串数据的风险。

**原因二:全链路可达。** `RuntimeContext` 贯穿 Agent 从创建到执行的完整生命周期,下游多个链路节点可以直接通过 `agent.getRuntimeContext()` 消费,无需额外传参:
**原因二:全链路可达。** `RuntimeContext` 贯穿 Agent 从创建到执行的完整生命周期,下游工具和中间件通过方法参数显式接收当次调用的上下文:
## RuntimeContext (per-call 上下文)

`RuntimeContext`(`io.agentscope.core.agent.RuntimeContext`)是 **per-call 元数据袋**:每次 `call` / `stream` 把一份实例传进去,agent 在执行期间把它绑定到自身,下游的工具、middleware、hook 都能读到同一份引用;调用结束后自动解绑。
`RuntimeContext`(`io.agentscope.core.agent.RuntimeContext`)是 **per-call 元数据袋**。每次调用传入独立实例,工具和 middleware 通过参数接收上下文。Agent 不提供共享的当前上下文 getter,也不向共享 hook 字段注入上下文。技能仓库操作及 `HarnessAgent.promoteSkill(name, reviewerId, ctx)` 同样显式接收上下文;不带上下文的仓库操作使用默认命名空间。

@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

Replaces the shared activeRc / getRuntimeContext() / RuntimeContextAware access paths with explicit RuntimeContext propagation through the skill repository, promoter and tool chain, plus regression tests for overlapping calls. The concurrency reasoning is sound and removing the shared mutable field is clearly the right fix — LGTM on the approach, only nits below.

Findings

  • [Warning] agentscope-core/.../ReActAgent.java:768 — null context now flows into onSystemPrompt, inconsistent with the RuntimeContext.empty() normalisation used everywhere else in this PR.
  • [Warning] agentscope-core/.../ReActAgent.java:208 — the surrounding class/field comments still describe the removed activeRc "side-channel", and stateForCall() still keeps an instance-level getAgentState() fallback.
  • [Info] agentscope-harness/.../WorkspaceSkillRepository.java:194 — the "null means default namespace" coalescing is duplicated across six methods; a single helper would protect the invariant this PR establishes.
  • [Info] agentscope-harness/.../HarnessSkillManageNamespaceTest.java:59 — patch / write_file / remove_file (and their rollback branches) are threaded with the context but not namespace-tested.

Not anchorable in the diff (documentation gaps worth a follow-up commit in this PR)

  • docs/v2/en/docs/harness/skill.md:269 and docs/v2/zh/docs/harness/skill.md:269 still show agent.promoteSkill("notes-taker", "alice") — the context-less overload is removed here, so the v2 examples no longer compile. This PR already updates docs/v2/*/docs/building-blocks/agent.md, so skill.md looks like an oversight rather than a deliberate deferral.
  • docs/v1/*/docs/harness/overview.md:153 still documents context being pushed to hooks implementing RuntimeContextAwareHook, which no longer exists. If the v1 docs are meant to describe the 1.x release only, a note to that effect would help readers who land there from search.

Tests

HarnessSkillMiddlewareContextIsolationTest.usesCallContextWhenSharedActiveContextPointsToAnotherSession now asserts explicit propagation, but the name still refers to the removed "shared active context" mechanism — renaming it would keep the intent of the regression suite obvious.

Cross-repo / compatibility note

getRuntimeContext(), RuntimeContextAware, the repository context suppliers and the 2-arg promoteSkill are all public API removals. No remaining references were found in this repository's non-test code, so the build is safe; external users only get the updated building-blocks/agent.md wording as a migration hint, which seems thin for a breaking change of this size — consider calling it out in the release notes / changelog.


Automated review by github-manager-bot

protected Mono<Msg> seedSystemMsg(Object callExectution) {
RuntimeContext rc =
callExectution instanceof CallExecution ce ? ce.rc : getRuntimeContext();
RuntimeContext rc = callExectution instanceof CallExecution ce ? ce.rc : null;

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.

The new null fallback hands a null RuntimeContext straight to mw.onSystemPrompt(this, ctx, p), while the rest of this PR normalises absent context with RuntimeContext.empty() (see WorkspaceSkillRepository). Third-party middlewares that dereference the context will hit an NPE on this path. Suggest callExectution instanceof CallExecution ce ? ce.rc : RuntimeContext.empty(), or document the nullable contract on onSystemPrompt.

* one agent instance per request via a factory method. {@link io.agentscope.core.model.Model},
* {@link io.agentscope.core.tool.Toolkit} (as a template — {@code build()} deep-copies it), and
* {@link io.agentscope.core.state.AgentStateStore} are all safe to share across instances.
* <p><b>Concurrency:</b> Calls sharing a {@code (userId, sessionId)} slot are serialized;

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.

This comment block sits right above the call that replaced this.activeRc = ctx, and the class javadoc still claims the instance field is "only a side-channel default for out-of-call accessors" (~line 748) — that field is gone now, so the wording should be refreshed here. Related: stateForCall() still falls back to the instance-level getAgentState() when the scope is not a CallExecution, which is a shared-state read under concurrency; worth either tightening the fallback or stating explicitly that it is only reachable outside a call.


/** Variant of {@link #skillExists(String)} scoped to the supplied request context; {@code null} uses the default namespace. */
public boolean skillExists(String skillName, RuntimeContext context) {
return getSkill(skillName, context != null ? context : RuntimeContext.empty()) != null;

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.

context != null ? context : RuntimeContext.empty() is now repeated at lines 194, 248, 284, 329, 364 and 394. A single private RuntimeContext scoped(RuntimeContext ctx) helper would keep the "null means default namespace" rule in one place — that invariant is the core of this fix, so it is worth making it un-forgettable for the next method added here.

new java.util.concurrent.Semaphore(0);

@Test
void skillManageCreateEditDeleteFollowTheActiveCallNamespace() throws Exception {

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.

Nice coverage for the create/edit/delete path. The same PR threads the context through patch, write_file and remove_file in SkillManageTool (including the rollback branches at lines 424/528/588); those are the paths most likely to silently fall back to the default namespace, so extending this test to one action per branch would close the remaining gap.

@chickenlj chickenlj changed the title fix(core): pass runtime contexts explicitly across agent calls fix(runtime): isolate contexts and control individual agent runs Sep 24, 2026

@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

Re-review after the new commit aa1e116f ("add per-run execution handles and cancellation"); my previous pass was on 3ba6f050. This is the right shape for #2528: a per-execution RunControl kills both failure modes at once — the activeRc cross-call context leak and the session-scoped interrupt flag that could not tell running A from queued B. The AgentRun single-subscription guard, the RUNNING-vs-cancel semantics, and the data-plane run_id fencing are all well documented in the docs updates, and the test coverage (AgentRunTest, HarnessSkillManageNamespaceTest, DataSessionRunCancellationTest) matches the surface area. Findings below are about the release treatment of the removed API and two lifecycle edge cases, not about the design direction.

Findings

  • [Warning — compatibility] core/state/AgentState.java (removed block) — this PR deletes three public API points from agentscope-core with no deprecation cycle: the RuntimeContextAware interface (file removed), AgentBase.getRuntimeContext(), and AgentState.interruptControl(). Per the review context, core interface changes cascade to harness / distribution / extensions and to user code. Please add a Migration notes / breaking-change entry next to the existing 1.0-deprecation wording in context.md, and consider landing this against a minor release: the PR description targets 2.0.4-SNAPSHOT, and removing public API in a patch version breaks semver for anyone on a released build. Two things that are not a problem, for the record: interruptControl was transient + @JsonIgnore and excluded from equals/hashCode, so already-persisted AgentState JSON loads unchanged; and RuntimeContextAware has only 5 in-repo references, all updated here.
  • [Warning] core/agent/RunControl.java:82 — interrupt() decides on status == RUNNING, but start() runs later inside the admitted call, so an interrupt that arrives after subscription and before admission hard-cancels (CancellationException, no partial-result save) instead of interrupting cooperatively. Both outcomes also return true, so the caller cannot tell them apart.
  • [Warning] service-dataplane/.../AgentRunRegistry.java:41 — termination-driven removal is a net, not a guarantee: a run that is registered, never subscribed and never cancelled emits no terminal signal and keeps its entry (plus its source lambda) in a long-lived @Component map forever. An expiring cache or a terminal-status sweep would close that.
  • [Info] core/agent/AgentRun.java:133 — public AgentRun.create() produces a handle whose status never leaves QUEUED (nothing outside prepareRun/prepareCall calls start()), so interrupt() on it always degrades to cancel().
  • [Info] core/agent/RunControl.java:29 — CONTEXT_KEY = new Object() is anonymous in reactor-context dumps; a named, typed key is easier to diagnose when a context fails to propagate.

Notes

  • move()/write()-adjacent: the null-exitCode unboxing pattern I flagged on #3269 also appears elsewhere in the sandbox filesystem — worth one sweep if ExecuteResponse.exitCode() can legitimately be null on timeout.
  • The four one-line docs/v2/{en,zh}/blogs/usecases/{logistics,aidc-logistics}.md edits are unrelated to this change; splitting them out would keep the runtime refactor diff clean.

Automated review by github-manager-bot

}

/** Running calls interrupt cooperatively; calls not yet admitted are cancelled. */
public boolean interrupt(InterruptSource source, Msg message) {

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.

[Warning] interrupt() has a start() race that turns a cooperative interrupt into a hard cancel. The branch decides on status == RUNNING, but start() is only called later, when the source is actually admitted (in AgentBase). A caller that reads run.status() == RUNNING (or is simply fast) and interrupts while the status is still QUEUED falls through to return cancel() at L92, which emits cancellation + a CANCELLED terminal, so the run that was about to execute is killed with CancellationException instead of taking the interrupt path (no partial-result state save, no interrupted recovery reply).

Two options:

  • make start() part of the subscription handoff, i.e. transition QUEUED -> RUNNING inside AgentRun.subscribeOnce() before the source is invoked, so any post-subscribe interrupt is cooperative; or
  • keep the current semantics but document interrupt() as "cooperative if admitted, cancelling otherwise" and have AgentRun.interrupt(Msg) report which one happened — today both return true, and the caller cannot tell a graceful interrupt from a kill.

Related, smaller robustness point: the synchronized (this) block decides the status while the two tryEmit* calls happen outside the lock. Sinks only accept the first terminal value, so status() and the termination() signal can in principle diverge (status CANCELLED, signal FAILED). Emitting inside the same monitor, or driving status from the emitted signal, would guarantee exactly one terminal observable.

}

/** Cooperatively interrupt a running run, or cancel it if it has not started. */
public boolean interrupt(Msg message) {

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.

[Info] AgentRun.create() is public, but a run built that way only carries RunControl in the reactor context (contextWrite in subscribeOnce); nothing outside the agent's own prepareRun/prepareCall path calls RunControl.start(). So for a directly-created handle the status never leaves QUEUED, which means interrupt() always degrades to cancel() and status() never reports RUNNING. Either narrow create() (package-private, or @apiNote internal) so the only reachable constructors go through the agent, or have subscribeOnce() perform the QUEUED -> RUNNING transition itself when no managed starter is present.

if (runs.putIfAbsent(run.runId(), entry) != null) {
throw new IllegalStateException("Run already registered: " + run.runId());
}
run.termination().subscribe(status -> runs.remove(run.runId(), entry));

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.

[Warning] This cleanup is a net, not a guarantee — the map is unbounded if the terminal signal is ever missed. Two concrete gaps:

  1. register() after the run has already terminated: Sinks.one() emits FAILED from onErrorMap before the subscriber downstream completes, so a caller that subscribes eagerly and registers in a later callback can subscribe to an already-emitted termination and still get the value (fine), but a run that is created, never subscribed and never cancelled emits nothing at all — its entry lives forever.
  2. Any exception thrown between putIfAbsent and subscribe (or a future code reshuffle) leaks the entry the same way.

Since this is a @Component in a long-lived data-plane process, a cheap belt-and-braces eviction would help: an expiring cache (Caffeine.expireAfterWrite) or a periodic sweep that drops entries whose run.status().isTerminal() is true. Otherwise one leaked run per abnormal teardown slowly grows both the map and the AgentRun graph (source lambda + context) it holds.

@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

Re-review of the single new commit 63b6468c since my previous pass on ff5be1eb. The change is a one-line eager initialization of CallExecution.interruption, which does fix a real NPE path — checkInterrupted() and the InterruptedException resume read the field, and it is only assigned in beforeAgentExecution. CI is green on this head (build ubuntu/windows, validate, license, codecov all pass). One concern about how the window is closed, plus a status note: the five findings from my previous review (public API removal without a deprecation/migration note, the interrupt()-before-start() race in RunControl, the AgentRunRegistry map growth, the AgentRun.create() QUEUED-only handle, and the anonymous CONTEXT_KEY) are untouched by this commit and still open, so I am keeping this at COMMENTED rather than approving.

Findings

  • [Warning] agentscope-core/.../ReActAgent.java:1700 — eager init turns a loud NPE into a fail-open window: reads before the beforeAgentExecution seed observe a RunControl-detached InterruptControl, so an interrupt arriving there is silently ignored.
  • [Info] agentscope-core/.../ReActAgent.java:763 — the seeded-vs-constructed split is the root cause; a constructor-injected final field removes it.

Suggestions

// CallExecution owns the signal of exactly one execution — same invariant RunControl documents.
final InterruptControl interruption;

CallExecution(AgentState state, PermissionEngine permissionEngine, String slotKey,
        long loadedVersion, InterruptControl interruption) { ... }

If activateSlotForContext cannot see the RunControl at construction time, seeding in the constructor is still possible by passing control.interruption() down from beforeAgentExecution, which keeps every reader past line 1700 on the same instance.

Notes

  • The handleInterrupt path at line 4304 resolves the source through scopeFrom(cv), so it benefits from the same per-call identity; worth confirming in the cancellation test that an interrupt during a queued-then-admitted run still reports USER rather than defaulting.

Automated review by github-manager-bot

private static final String PERMISSION_DENIED_BY_USER = "Permission denied by user";
private static final String PERMISSION_DENIED_BY_RULES = "Permission denied by rules";

InterruptControl interruption = new InterruptControl();

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.

Initializing here closes the NPE (checkInterrupted() at line 1789 and interruption.getSource() at 2487/4304 can run before beforeAgentExecution seeds the field at line 763), but it converts the unseeded window from a loud failure into a silent one: any read before the seed sees a different InterruptControl than the one owned by the run's RunControl, so an interrupt() that lands in that window is simply never observed (fail-open) instead of blowing up.

Since CallExecution is built fresh per call in activateSlotForContext (line 705) and never escapes unseeded today, the safest shape is to pass the control in through the constructor and make the field final — that removes the window instead of papering over it, and also documents that the signal is owned by exactly one execution (the same invariant RunControl states on line 2). If keeping the mutable field is deliberate (e.g. for the callExectution side-channel at line 769), worth a short comment saying who owns the instance before and after the seed.

scope.systemMsg = null;
// Clear any stale interrupt signal for this session before the new call begins.
scope.state.interruptControl().reset();
scope.interruption = control.interruption();

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.

scope.rc, scope.systemMsg and scope.interruption are all re-seeded here on a scope that was just constructed, which is a good argument for the constructor-final shape above: the only mutable leftovers on CallExecution are exactly the fields with a per-call owner.

@oss-maintainer
oss-maintainer merged commit 8d9bec6 into main Sep 24, 2026
8 checks passed
@oss-maintainer
oss-maintainer deleted the codex/fix-explicit-runtime-context branch September 24, 2026 14:47
oss-maintainer pushed a commit that referenced this pull request Sep 24, 2026
…3283)

Concurrent calls must not change another session's tool visibility,
streaming callbacks, or skill resources. This PR builds on main after
#3279 and adapts the request-scoped tool composition work from #2463,
with additional fixes for construction-time isolation and explicit
context propagation. Related: #2439, #2459. Credit to @xzxiaoshan for
the original implementation in #2463.

Co-authored-by: xzxiaoshan <[email protected]>
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.

[Bug]:ReActAgent 作为无状态单例,不应持有可变实例字段 activeRc

3 participants