Repository navigation
Description
Describe the bug
AgentSpawnTool retains every spawned non-persistent subagent in agentsByKey for the lifetime of the parent tool.
Each SpawnedAgent strongly references the actual Agent instance:
private record SpawnedAgent(
String key,
String agentId,
String sessionId,
String label,
Agent agent,
int depth) {}
private final ConcurrentHashMap<String, SpawnedAgent> agentsByKey =
new ConcurrentHashMap<>();For a non-persistent subagent, every spawn generates a new random key:
key = "agent:" + agentId + ":" + UUID.randomUUID();The new entry is then stored in agentsByKey:
agentsByKey.put(key, spawned);I could not find any corresponding agentsByKey.remove(...) or agentsByKey.clear() lifecycle path.
As a result, a long-lived parent agent that continuously spawns subagents retains all historical child Agent instances, even after their work has finished. Since those instances remain strongly reachable, they cannot be garbage-collected.
This is related to #1911, but that issue mainly asks about persistSession=true. This report provides a concrete reproduction showing that non-persistent subagents are also retained indefinitely.
To reproduce
A diagnostic test placed at:
agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/AgentSpawnRetentionDiagnosticTest.java
/*
* Copyright 2024-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.agentscope.harness.agent.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.TextBlock;
import io.agentscope.core.model.ChatResponse;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.Model;
import io.agentscope.core.model.ToolSchema;
import io.agentscope.core.state.AgentState;
import io.agentscope.harness.agent.middleware.SubagentEntry;
import io.agentscope.harness.agent.subagent.DefaultAgentManager;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
class AgentSpawnRetentionDiagnosticTest {
@Test
void finishedNonPersistentSpawnsRemainStronglyRegistered() {
AtomicInteger created = new AtomicInteger();
DefaultAgentManager manager =
new DefaultAgentManager(
List.of(
new SubagentEntry(
"worker",
"worker",
rc -> {
int index = created.incrementAndGet();
return ReActAgent.builder()
.name("worker-" + index)
.sysPrompt("worker")
.model(replyingModel())
.build();
})),
null);
AgentSpawnTool tool = new AgentSpawnTool(manager, null, 0);
AgentState parentState = AgentState.builder().build();
RuntimeContext context =
RuntimeContext.builder()
.userId("diagnostic-user")
.sessionId("diagnostic-parent")
.build();
int spawnCount = 256;
for (int i = 0; i < spawnCount; i++) {
String result =
tool.agentSpawn(context, parentState, "worker", null, null, 1, null).block();
assertTrue(result.contains("status: accepted"));
}
assertEquals(spawnCount, created.get());
assertTrue(tool.agentList().startsWith("Active subagents (" + spawnCount + "):"));
assertEquals(spawnCount, parentState.getToolContext().getSpawnRegistry().size());
}
private static Model replyingModel() {
return new Model() {
@Override
public String getModelName() {
return "diagnostic-model";
}
@Override
public Flux<ChatResponse> stream(
List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) {
return Flux.just(
new ChatResponse(
"diagnostic-model",
List.of(TextBlock.builder().text("done").build()),
null,
java.util.Map.of(),
"stop"));
}
};
}
}The test:
- Creates one
AgentSpawnTool. - Spawns 256 distinct non-persistent
ReActAgentinstances. - Passes no task to
agentSpawn, so every call returns immediately and no background subagent execution remains active. - Checks the factory invocation count,
agent_list, and the persisted spawn registry.
The key assertions are:
assertEquals(spawnCount, created.get());
assertTrue(
tool.agentList()
.startsWith("Active subagents (" + spawnCount + "):"));
assertEquals(
spawnCount,
parentState.getToolContext().getSpawnRegistry().size());Run it with:
mvn -pl agentscope-harness -am \
-Dtest=AgentSpawnRetentionDiagnosticTest \
-Dsurefire.failIfNoSpecifiedTests=false \
testObserved result:
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
BUILD SUCCESS
After all 256 spawn calls have returned:
- 256 distinct child agents were created.
agent_liststill reports all 256 entries as active.agentsByKeystill contains all 256SpawnedAgententries.- The parent
AgentState.spawnRegistrycontains 256 entries. - There are no active tasks in this reproduction.
The agents are not still executing, but their instances and associated object graphs remain retained.
Expected behavior
The framework should provide a bounded or explicit lifecycle for spawned subagents.
Possible designs include:
- an explicit
agent_release/agent_closeoperation; - configurable idle TTL or LRU eviction.
Automatically removing a child immediately after one task completes may not be compatible with subsequent agent_send calls, so the exact lifecycle policy probably requires discussion.
Potential impact
In a short-lived request-scoped parent agent, the retained object graph may eventually become unreachable together with the parent.
However, for a long-lived parent agent, the following structures can grow without an apparent bound:
- live child
Agentinstances referenced byagentsByKey; agentsByKey;labelToKeywhen labels are used;- serialized
spawnRegistrymetadata.
Depending on the spawn rate and resources owned by each child agent, this may eventually cause excessive heap usage or OOM.
This report confirms the unbounded retention behavior. It does not claim that a production OOM has already been reproduced or quantify the retained heap size per child agent.
Environment
- AgentScope-Java: current
main, commit8d96bb0d - Java: OpenJDK 21.0.2
- OS: Linux 6.8.0-138-generic x86_64
Activity
oss-maintainer commentedon Sep 14, 2026
Issue Evaluation
Category:
bug| Area:area/harness| Status: Confirmed (verified against currentmain)Root Cause:
AgentSpawnToolinserts every spawned agent intoagentsByKey, and non-persistent spawns get a fresh random UUID key each time. There is noremove/clearpath in the tool or its owning middlewares, so eachSpawnedAgent(which strongly references the liveAgentinstance) stays reachable for the parent tool's whole lifetime.Impact: Unbounded memory growth for long-running agents that repeatedly spawn short-lived subagents.
Severity: medium
Suggested direction: evict non-persistent entries when the spawned agent finishes (or bound
agentsByKeywith an LRU/TTL), while keeping persisted agents reachable.Automated evaluation by github-manager-bot
aiyili commentedon Oct 1, 2026
Hi, I'd like to work on this. The report is precise —
agentsByKeyhas no eviction path for non-persistent spawns. Plan: release spawned non-persistent agents when their task completes (and on tool close), with tests asserting the map no longer retains finished non-persistent entries while persistent ones are kept. PR coming shortly.aiyili commentedon Oct 1, 2026
Update from someone who started on this: a safe fix is wider than it looks, so stepping back and sharing the analysis for whoever picks it up.
The retention is in
agentsByKey(andlabelToKeyvia reverse lookup), and non-persistent spawns can be re-referenced by key after spawn — so cleanup cannot simply happen on first task completion. Doing it correctly needs reference counting across all three execution paths (taskRepository.putTaskfire-and-forget, the synchronous Mono with race/orTimeout, and adopted tasks), with a completion hook thatTaskRunSpec/TaskRepositorydoes not currently offer — i.e. a small design decision (where the completion callback lives) is a maintainer call rather than a drop-in patch.Suggestion: either (a) add an optional completion hook to
TaskRunSpec/TaskRepositoryand evict non-persistent entries when the count drops to zero, or (b) cap the map with a per-agent LRU bound. Happy to implement either once a direction is chosen.fix(harness): add explicit lifecycle management for spawned agents (a…