Repository navigation
Description
Describe the bug
The Going-to-Production guide (docs/v2/zh/docs/others/going-to-production.md, section 7) recommends configuring a shared HarnessAgent.Builder at startup and calling builder.build() once per request:
HarnessAgent.Builder agentBuilder = HarnessAgent.builder()...;
// per HTTP request
try (HarnessAgent agent = agentBuilder.build()) { ... }On 2.0.4 this pattern is not safe under concurrent requests: with 2+ simultaneous build() calls we consistently get java.util.ConcurrentModificationException from ReActAgent.Builder.build().
Root cause
ReActAgent.Builder.build() in 2.0.4 mutates the builder's own collections in place:
middlewares.sort(Comparator.comparingInt(MiddlewareBase::order).reversed());— agentscope-coreReActAgent.java:5621hooks.add(skillHook)/hooks.remove(skillHook)in thefinallyblock around agent construction
ArrayList.sort on a list shared by concurrent builds throws ConcurrentModificationException; the hooks mutation is also racy (one build may remove a hook added by another).
HarnessAgent.Builder.build() in 2.0.4 is not synchronized and writes back stateStoreOverride, messageBus and asyncToolRegistry without restoring them in a finally, so a failed build leaves the shared builder polluted — consistent with the follow-on sandbox error below.
To Reproduce
- Configure one
HarnessAgent.Builderat startup, then build per request:
HarnessAgent.Builder builder = HarnessAgent.builder()
.name("...")
.model(model)
.workspace(workspace)
.distributedStore(store)
.filesystem(new E2bFilesystemSpec() /* ... */);
// concurrent HTTP handler
try (HarnessAgent agent = builder.build()) { ... }- Fire >=2 concurrent requests, each calling
builder.build()thenagent.call(...). - 4 concurrent requests reproduce reliably in our Spring Boot service.
Expected behavior
Builder.build() can be invoked concurrently on the same Builder instance (as the production guide's pattern implies), or the guide clearly states builds must be externally synchronized.
Error messages
Stack (2.0.4):
java.util.ConcurrentModificationException
at java.base/java.util.ArrayList.sort(ArrayList.java:1806)
at io.agentscope.core.ReActAgent$Builder.build(ReActAgent.java:5621)
at io.agentscope.harness.agent.HarnessAgent$Builder.build(HarnessAgent.java:2948)
After the failure we also observed follow-on SandboxException$SandboxConfigurationException: No active sandbox — sandbox filesystem used outside of a call context originating from WorkspaceMessageBus.queueDrain, apparently caused by partially-built agents.
Suggested fix
Main already makes the pattern correct by serializing HarnessAgent.Builder.build() (see below). Removing that serialization looks like a small follow-up, because after inner.copy() the only shared state a build touches is the builder's own wiring fields:
- Move build-time wiring into locals inside
buildInstance, sostateStoreOverride,messageBusandasyncToolRegistryare never written back to the builder, then dropsynchronizedfrombuild(). These values can be per-workspace (messageBusis derived from the per-build filesystem), which is why the current code writes and restores them. - Pass the effective state store explicitly to the subagent factories.
HarnessAgentBuilderSupport.buildGeneralPurposeFactory/buildDeclaredFactoryreadb.stateStoreOverridewhile building the parent; if that field stays untouched, children silently lose the parent's distributed store. AparentStateStoreparameter threaded throughbuildSubagentsMiddleware/buildDynamicSubagentsMiddlewarekeeps the existing behaviour. - Leave spec auto-wiring as it is:
RemoteFilesystemSpec.injectStoreIfAbsent,SandboxFilesystemSpec.snapshotSpecandexecutionGuardonly write values that are constant for a givenDistributedStore, and the subagent factories read them back when constructing child builders. Eliminating these writes needs a copy or override path for everySandboxFilesystemSpecsubclass; a delegating spec wrapper is the alternative if the mutation must go away. - Serialize
WorkspaceIndex.open(...)(or add a SQLite busy timeout). Concurrent builds of one workspace run schema initialization in parallel; a "database is locked" failure is swallowed and that agent reads through full store scans for its lifetime.
A prototype of steps 1, 2 and 4 passes the harness suite (1371 tests), including a regression test that runs 8 threads x 16 builds on one shared builder and checks that every agent gets its own middleware chain and the parent state store, with spotless:check green.
The alternative is to make the whole builder copy-on-build, the way ReActAgent does. That needs a hand-maintained field list in HarnessAgent.Builder.copy(), and a newly added builder field that is forgotten there would silently drop configuration, which is why the incremental option above seems preferable.
Whichever direction is chosen, the production guide should state whether build() is serialized or safe to call concurrently.
Environment
- AgentScope-Java Version: 2.0.4
- Java Version: 21
- OS: Windows 11
- Additional: Spring Boot 3.x,
E2bFilesystemSpecsandbox +DistributedStore
Additional context
- Workaround in use: serialize
build()behind a lock. - Status on main: fixed since a2cbea5 (feat: redesign Harness context and unify Service sessions with JEV #3441), released in v2.1.0-BETA1.
ReActAgent.Builder.copy()returns a builder with fresh collections andbuild()iscopy().buildInstance(), so the sort and hook mutations no longer touch shared state;HarnessAgent.Builder.build()issynchronizedand restoresmessageBus/asyncToolRegistryin afinally. - The fix serializes builds instead of removing the lock, so a shared builder with per-request
build()is safe on main but throughput is bounded by the build itself. - The 2.0.x maintenance branch (
origin/2.0.xat 5f95be9) does not contain the fix, so 2.0.x releases remain affected.
Activity
wahllllll commentedon Oct 27, 2026
I verified the report against both
v2.0.4and currentmain.v2.0.4, the reported concurrent-build failure is reproducible from the source shape:ReActAgent.Builder.build()mutates the shared middleware and hook collections (sort,add,remove), whileHarnessAgent.Builder.build()invokes that shared builder directly.main, the CME path is already addressed by the synchronized Harness build plusReActAgent.Builder.copy(); the existingHarnessBuilderReuseTest.concurrentBuildsKeepIndependentMiddlewareChainscovers the successful concurrent-build path.stateStoreOverridebefore validation. If the build then fails, the failed store remains on the reusable builder and wins every lateroverride == nullcheck. Replacing the distributed store can therefore keep failing with the original local-store validation error.I opened #3811 to restore that field only when a build fails, while preserving the successful-build behavior needed by dynamic subagent factories. It adds regression coverage for both field restoration and reuse after replacing the invalid store. The full harness module passes: 1403 tests, 0 failures, 0 errors, 32 skipped.
fix(harness): restore builder state after failed build (#3811)
juruoO-o commentedon Nov 12, 2026
Status update: #3811 (merged) restores builder state after a failed build (the failure-path contamination part). The concurrent
ConcurrentModificationExceptiondescribed against v2.0.4 remains open.aiyili commentedon Nov 27, 2026
I'd like to take the part that is still open:
2.0.x(50886798) still has the shape reported against 2.0.4.ReActAgent.Builder.build()adds its generated middleware and hooks to the builder's own lists and sorts them in place (ReActAgent.java:5947-5969).HarnessAgent.Builder.build()is not synchronized, adds the harness middlewares to the sharedinnerbuilder on every build, and writes backstateStoreOverride,messageBusandasyncToolRegistrywithout restoring them when a build fails.Plan, as a PR against
2.0.xonly. It is a backport of whatmainalready has, not a new design:ReActAgent.Builder.copy(), withbuild()building from that copy, so each agent gets its own middleware and hook lists.HarnessAgent.Builder.build()synchronized and building frominner.copy(), and the builder state restored after a failed build (fix(harness): restore builder state after failed build #3811).main(AgentBuilderReuseTest,HarnessBuilderReuseTest) ported to2.0.x, run first on the unmodified branch to show them fail.The
main-side follow-ups listed under "Suggested fix" (dropping the serialization, threading the state store through the subagent factories) are out of scope for this.aiyili commentedon Nov 27, 2026
Opened #4449 against
2.0.x.On unmodified
2.0.xthe builder could not be reused at all: the second agent built from oneHarnessAgent.Buildercarried 19 harness middlewares where the first carried 10, and with 8 concurrent builds every agent ended up with a chain of 52 or 53 that mixed in instances from other builds.The PR ports what
mainhas,ReActAgent.Builder.copy()from #3441 and the failed-build restore from #3811. One thing the port needed beyond a copy of that code: the effective state store is now pushed to the per-build copy on every build, asmaindoes, because the sharedinnerbuilder no longer remembers it from an earlier build.Two cases go beyond the
maintests. One holds a build in the middle ofbuild()and checks that a second one stays out; it is the only test that fails whensynchronizedis dropped. The other checkscopy()field by field, since it lists the builder's fields by hand.7 of the 9 harness cases and the core test fail on unmodified
2.0.xand pass with the change. The full core and harness suites have the same failing lists before and after on Windows and in a Linux container.