Skip to content

fix(core,harness): backport thread-safe builder reuse to 2.0.x (#3719) - #4449

Open
aiyili wants to merge 4 commits into
agentscope-ai:2.0.xfrom
aiyili:fix/builder-reuse-thread-safety
Open

aiyili wants to merge 4 commits into
agentscope-ai:2.0.xfrom
aiyili:fix/builder-reuse-thread-safety

Conversation

@aiyili

@aiyili aiyili commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Backports to 2.0.x the part of #3719 that is still open. main got ReActAgent.Builder.copy() in #3441 and the failed-build restore in #3811; nothing here goes beyond them.

Problem

On 2.0.x a builder cannot be reused, neither concurrently nor one build after the other:

  • ReActAgent.Builder.build() adds the middleware and hooks it generates to the builder's own collections and sorts them in place. Every build adds another copy, and concurrent builds throw ConcurrentModificationException from ArrayList.sort, as reported against 2.0.4.
  • HarnessAgent.Builder.build() adds the harness middlewares to its shared inner builder on every build and is not synchronized. The second agent built from one builder has 19 middlewares where the first has 10. With 8 concurrent builds, every agent ends up with a chain of 52 or 53 that mixes in instances from other builds.
  • A build that fails after the auto-wiring has run leaves stateStoreOverride, the injected remote store and the sandbox snapshot spec and execution guard on the builder. Replacing the distributed store does not help: the stale local store keeps winning, and the build fails again with the same validation error.

Fix

  • ReActAgent.Builder.copy() returns a builder with the same configuration and fresh registration collections, and build() builds from that copy.
  • HarnessAgent.Builder.build() is synchronized and builds from inner.copy(). The effective state store is now pushed to the inner copy on every build, as on main. Before, the shared inner carried it over from an earlier build; with a copy per build, the second agent would have been built without one.
  • messageBus and asyncToolRegistry are restored after every build, and stateStoreOverride together with the auto-wired filesystem spec values after a failed one. RemoteFilesystemSpec.restoreAutoInjectedStore is added for that, as in fix(harness): restore builder state after failed build #3811.

Tests

AgentBuilderReuseTest (core) and HarnessBuilderReuseTest (harness) are ports of the main tests, with two additions that this branch needs:

  • aConcurrentBuildWaitsForTheRunningOne holds one 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, since inner.copy() by itself already keeps the chains apart.
  • copyCarriesEveryConfiguredField gives every builder field a value that differs from its default and checks the copy field by field. copy() lists the fields by hand, so a field added to 2.0.x later and not copied fails here instead of silently dropping configuration.

On unmodified 2.0.x the core test fails (the second agent has two DynamicSkillMiddleware), and 7 of the 10 harness cases fail: the sequential and the concurrent reuse, the build that does not wait for a running one, and the four failed-build cases. The other three pass before and after; they pin what the port has to preserve: the state store of a distributed-store wiring, a new instance continuing a persisted conversation, and a store that an earlier build injected staying in place when a later one fails.

Each piece of the fix was then broken on its own:

Broken piece Caught by
core build() without copy() repeatedBuildDoesNotAccumulateGeneratedMiddleware
harness builds on the shared inner repeatedBuildHasFreshRuntimeMiddlewareAndFilesystemBindings, concurrentBuildsKeepIndependentMiddlewareChains
synchronized dropped aConcurrentBuildWaitsForTheRunningOne
stateStoreOverride not restored after a failure the four failed-build cases
remote store / sandbox spec not restored failedBuildRestoresAutoWiredRemoteFilesystemStore / failedBuildRestoresAutoWiredSandboxSpecForAnyThrowable
builder state restored even after a success repeatedBuildPreservesDistributedStateStoreWiring and two failed-build cases
message bus and registry restored only after a failure repeatedBuildHasFreshRuntimeMiddlewareAndFilesystemBindings
copy() missing a field or a collection copyCarriesEveryConfiguredField
state store pushed to inner only when auto-wired or absent repeatedBuildPreservesDistributedStateStoreWiring, builderRemainsReusableAfterFailedBuild
failed build drops the remote store instead of restoring it aStoreInjectedByAnEarlierBuildIsKeptWhenALaterBuildFails
remote store not restored at all failedBuildRestoresAutoWiredRemoteFilesystemStore

The one that survives is copy() without synchronized, which no test pins; it is kept as on main.

An earlier version of this description also listed newInstanceContinuesPersistedConversationAfterPreviousInstanceCloses for the message-bus mutant. That was wrong: the case failed there because of a flaw in the case itself, not because of the mutant. It built on the default state store, which lives under target/, so a run carried the conversation of earlier runs into this one, and once that was long enough the first call compacted it at the price of two more model calls. The case builds on an InMemoryAgentStateStore of its own now. With an 80-message conversation seeded into the default location, the old case fails with expected: <2> but was: <4> and the new one passes; with the change, the message-bus mutant leaves the case green.

One more case was added where codecov reported an added line without coverage: aStoreInjectedByAnEarlierBuildIsKeptWhenALaterBuildFails covers the branch of RemoteFilesystemSpec.restoreAutoInjectedStore for a store that was not null before the failed build, which is the case when an earlier build on the same builder injected the store and a later one fails. Every line this PR adds to production code is covered on Linux, branches included.

Not in this backport

  • The main-side follow-ups listed under "Suggested fix" in the issue: dropping the serialization and threading the state store through the subagent factories.
  • Setters on a shared builder are still not thread-safe, as on main: configure the builder before sharing it.

Verification

The full agentscope-core and agentscope-harness suites were run before and after the change on Windows and in a Linux container, at the base as of 2026-11-27. The failing lists are identical; the only difference is the added tests (core +3, harness +10).

Environment Module Before After Failing before and after
Windows core 3237 run, 0 F + 3 E 3240 run, 0 F + 3 E 2 × DangerousPathBypassTest.symlink* (no symlink privilege), SkillBoxTest$UploadContainment.preservesLegacyNamesWithRelativeNonNormalizedWorkDirectory
Windows harness 1619 run, 5 F + 12 E 1628 run, 5 F + 13 E (1629 with the last commit, green in CI) Windows path checks (Sandbox workspace root must be an absolute path), 2 × MemoryConsolidatorCommitGateTest, MemoryFlushSandboxIndependenceTest, and the flaky case below
Linux container core 3242 run, 0 F + 0 E 3245 run, 0 F + 0 E none
Linux container harness 1619 run, 3 F + 1 E 1629 run, 3 F + 1 E 3 × BaseSandboxFilesystemTest.edit_* (python3: not found in the image), MarketplaceStagerOrphanGcTest.unreadableEntryDoesNotFailStage

The Linux core suite is the one that matters for copy(): it is the only one of the four that runs without a failure. On the current head (9168a464, with 2.0.x merged in), the container run gives core 3282 run, 0 F + 0 E, and harness 1638 run with the same 3 F + 1 E.

CI. The first run of this PR was red for reasons that lay in the base branch: since the backports of 2026-11-13, every PR against 2.0.x failed the Windows job, at first in agentscope-core, and had its Ubuntu job cancelled. Those causes are fixed by #4454 and #4461, merged into 2.0.x on 2026-11-27; the harness part went in with #4461. The current run of this PR is green on both systems, on top of the current 2.0.x (core 3282 and harness 1638 tests on Linux, 3277 and 1638 on Windows). The local before/after runs in the table were made before the fixes existed, which is why the "before" column lists failures that the branch no longer has.

codecov. Its report of 2026-12-01 on 0bb4080b listed 3 lines of ReActAgent.java without coverage, none of them from this change. CI measures coverage on the merge commit with 2.0.x, where #4430 had changed ReActAgent.java on 2026-11-30, moving Builder.copy() 37 lines down compared with this branch, while the patch is read from the branch's own head. The last lines of the patch (head 5967–5970) were therefore looked up at 5967–5970 of the merged file, which is the end of mergeAndSortResults, RAG code this PR does not touch. 2.0.x is merged into this branch since 9168a464, so both refer to the same file again; the report for that commit shows every modified line covered.

One Windows run of this change also failed HarnessAgentTest.sandboxWithArtifactDeliveryTargetAndDisabledFilesystemTools_promptOmitsDeliverTool. Repeating its scenario 80 times on unmodified 2.0.x fails once with the same Sandbox workspace root must be an absolute path error (0 of 80 with this change): the in-memory sandbox fixture sometimes reports a Windows path as the workspace root. It does not go through the builder.

…scope-ai#3719)

`ReActAgent.Builder.build()` added the middleware and hooks it generates to the builder's own collections and sorted them in place, and `HarnessAgent.Builder.build()` added the harness middlewares to the shared `inner` builder on every build without synchronization. A builder could therefore not be reused: the second agent carried a second copy of every middleware, and concurrent builds threw `ConcurrentModificationException`. A build that failed after auto-wiring also left the state store and the filesystem spec values on the builder.

Ports what `main` has: `ReActAgent.Builder.copy()`, with `build()` building from that copy, and `HarnessAgent.Builder.build()` synchronized and building from `inner.copy()`, restoring the builder's write-backs after the build and the auto-wired values after a failed one (agentscope-ai#3811). The effective state store is now pushed to the inner copy on every build, since the shared builder no longer carries it over from an earlier build.

Tests: `AgentBuilderReuseTest` and `HarnessBuilderReuseTest` port from `main`, plus a check that a second build waits for a running one and a field-by-field check of `copy()`.
@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

aiyili and others added 2 commits December 1, 2026 12:49
…non-null restore

`newInstanceContinuesPersistedConversationAfterPreviousInstanceCloses` relied on the default state store, which lives under `target/`. A run therefore carried the conversation of earlier runs into this one. Once that was long enough (the compaction trigger is 50 messages), the first call compacted it at the price of two more model calls, and the case failed with `expected: <2> but was: <4>`. It builds on an `InMemoryAgentStateStore` of its own now. With an 80-message conversation seeded into the default location, the old case fails and the new one passes.

codecov reported one partial line in agentscope-ai#4449 as well, in `RemoteFilesystemSpec.restoreAutoInjectedStore`: the branch for a store that was not null before the failed build. That is the case when an earlier build on the same builder injected the store and a later one fails. A new case builds once, makes the second build fail, and checks that the injected store is still there.

This branch has not been deployed

No deployments
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.

1 participant