Skip to content

[Bug]: HarnessAgent.Builder.build() is not thread-safe — concurrent build() throws ConcurrentModificationException although Going-to-Production recommends sharing one Builder #3719

Open

Description

@Peng-io

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-core ReActAgent.java:5621
  • hooks.add(skillHook) / hooks.remove(skillHook) in the finally block 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

  1. Configure one HarnessAgent.Builder at 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()) { ... }
  1. Fire >=2 concurrent requests, each calling builder.build() then agent.call(...).
  2. 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:

  1. Move build-time wiring into locals inside buildInstance, so stateStoreOverride, messageBus and asyncToolRegistry are never written back to the builder, then drop synchronized from build(). These values can be per-workspace (messageBus is derived from the per-build filesystem), which is why the current code writes and restores them.
  2. Pass the effective state store explicitly to the subagent factories. HarnessAgentBuilderSupport.buildGeneralPurposeFactory / buildDeclaredFactory read b.stateStoreOverride while building the parent; if that field stays untouched, children silently lose the parent's distributed store. A parentStateStore parameter threaded through buildSubagentsMiddleware / buildDynamicSubagentsMiddleware keeps the existing behaviour.
  3. Leave spec auto-wiring as it is: RemoteFilesystemSpec.injectStoreIfAbsent, SandboxFilesystemSpec.snapshotSpec and executionGuard only write values that are constant for a given DistributedStore, and the subagent factories read them back when constructing child builders. Eliminating these writes needs a copy or override path for every SandboxFilesystemSpec subclass; a delegating spec wrapper is the alternative if the mutation must go away.
  4. 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, E2bFilesystemSpec sandbox + 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 and build() is copy().buildInstance(), so the sort and hook mutations no longer touch shared state; HarnessAgent.Builder.build() is synchronized and restores messageBus / asyncToolRegistry in a finally.
  • 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.x at 5f95be9) does not contain the fix, so 2.0.x releases remain affected.

Activity

  1. wahllllll commented on Oct 27, 2026

    @wahllllll
    Contributor

    I verified the report against both v2.0.4 and current main.

    • On 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), while HarnessAgent.Builder.build() invokes that shared builder directly.
    • On current main, the CME path is already addressed by the synchronized Harness build plus ReActAgent.Builder.copy(); the existing HarnessBuilderReuseTest.concurrentBuildsKeepIndependentMiddlewareChains covers the successful concurrent-build path.
    • A remaining failure-path bug was still present: distributed-store auto-wiring writes stateStoreOverride before validation. If the build then fails, the failed store remains on the reusable builder and wins every later override == null check. 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.

  2. juruoO-o commented on Nov 12, 2026

    @juruoO-o
    Collaborator

    Status update: #3811 (merged) restores builder state after a failed build (the failure-path contamination part). The concurrent ConcurrentModificationException described against v2.0.4 remains open.

  3. aiyili commented on Nov 27, 2026

    @aiyili
    Contributor

    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 shared inner builder on every build, and writes back stateStoreOverride, messageBus and asyncToolRegistry without restoring them when a build fails.

    Plan, as a PR against 2.0.x only. It is a backport of what main already has, not a new design:

    1. ReActAgent.Builder.copy(), with build() building from that copy, so each agent gets its own middleware and hook lists.
    2. HarnessAgent.Builder.build() synchronized and building from inner.copy(), and the builder state restored after a failed build (fix(harness): restore builder state after failed build #3811).
    3. The reuse tests from main (AgentBuilderReuseTest, HarnessBuilderReuseTest) ported to 2.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.

  4. aiyili commented on Nov 27, 2026

    @aiyili
    Contributor

    Opened #4449 against 2.0.x.

    On unmodified 2.0.x the builder could not be reused at all: the second agent built from one HarnessAgent.Builder carried 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 main has, 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, as main does, because the shared inner builder no longer remembers it from an earlier build.

    Two cases go beyond the main tests. One holds a build in the middle of build() and checks that a second one stays out; it is the only test that fails when synchronized is dropped. The other checks copy() 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.x and 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions