Skip to content

fix(harness): add explicit lifecycle management for spawned agents - #2917

Merged
jujn merged 24 commits into
agentscope-ai:mainfrom
guslegend0510:codex/fix-2915-agent-retention
Nov 19, 2026
Merged

jujn merged 24 commits into
agentscope-ai:mainfrom
guslegend0510:codex/fix-2915-agent-retention

Conversation

@guslegend0510

@guslegend0510 guslegend0510 commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2915

  • Add explicit lifecycle control for spawned subagents.
  • Add a required reusable flag to agent_spawn:
    • reusable=true keeps the subagent addressable for later agent_send calls until agent_release or parent shutdown.
    • reusable=false creates a one-shot subagent that closes after its task reaches a terminal state.
  • Add agent_release for idle reusable subagents. Release is rejected while a synchronous, asynchronous, remote, cancelled, or timeout-promoted execution is still in flight.
  • On successful release, close the child agent when possible, remove its live key, label, and persisted spawn entry, and invalidate user-visible Gateway handles.
  • Scope live subagent registries by (userId, parentSessionId) so concurrent callers and sessions do not address each other's subagents.
  • Track execution ownership with leases across local, remote, background, cancelled, and timeout-promoted executions.
  • Serialize initialization for the same persistent subagent identity so concurrent cache misses construct only one child while still waiting for a fully initialized winner.
  • Revoke exposed Gateway handles by child session, including persisted handles backed by the durable subagent registry.
  • Preserve compatibility for serialized spawn entries that predate the reusable field; missing values default to reusable behavior.
  • Preserve persistent session state when the parent HarnessAgent closes, while still closing runtime child instances owned by the spawn tool.
  • Update the English and Chinese Harness subagent documentation in both docs/dev and docs/v2.

Behavior

reusable=true is for follow-up workflows:

agent_spawn agent_id="reviewer" task="review the PR" label="pr-reviewer" reusable=true
agent_send label="pr-reviewer" message="also check the schema changes"
agent_release label="pr-reviewer"

reusable=false is for one-shot delegation:

agent_spawn agent_id="reviewer" task="review every change" reusable=false

A one-shot subagent requires a task and cannot be combined with label, persistSession, or expose_to_user, because those options imply later addressing or reuse. No TTL, LRU, force-release, or automatic retained-agent limit is introduced; retained lifecycle remains explicit.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with the main branch and cannot be merged. Please rebase (or merge main) and resolve the conflicts:

git fetch origin
git checkout codex/fix-2915-agent-retention
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved.


Automated notification by github-manager-bot

@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

This is the right shape for the leak: an explicit ACTIVE/RELEASING/RELEASED state machine, execution leases that gate release, user/parent-session scoped registries, gateway revocation on close, and AutoCloseable on the tool with closeOwnedAgentSpawnTool() wired through both middlewares. Persisting the registry under ToolContextState with a synchronized snapshot, and the doc updates (en+zh), are consistent with the change. AgentSpawnToolLifecycleTest covers busy-release rejection, lease idempotency and close-during-in-flight, which is encouraging for a change this behavioural.

Findings

  • [Warning] close() does not take either of the two monitors the rest of the class uses, so a spawn racing with shutdown can publish into an unreachable registry — see inline comment. This is the one place where the leak this PR fixes could survive.
  • [Warning] beginClose() deliberately ignores inFlight while beginRelease() does not; please state that intent and confirm no invocation path bypasses tryAcquire().
  • [Info] locking a public mutable map as the monitor; mixed synchronized + AtomicReference lifecycle state.

Suggestions

Diff is 1766/-474 across 15 files; per the size guidance I focused on the lifecycle/registry core and the persisted-state change and did not line-review the middleware plumbing or the docs prose. One follow-up worth considering: the RELEASING state has no timeout, so a hung child pins release for that key forever — an in-flight age metric would make that debuggable.

Verdict

Comment only, not approval: the two [Warning]s are in the concurrency contract this PR exists to establish, and the PR currently has a merge conflict with main.


Automated review by github-manager-bot

*/
@Override
public void close() {
for (Map.Entry<RegistryScope, ScopedRegistry> scoped : registries.entrySet()) {

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.

close() reads and mutates registries without the synchronized (registries) monitor that registryFor/releaseRegistry/removeRegistryIfEmptyLocked use, and it mutates registry.agentsByKey/labelToKey without the synchronized (registry) monitor that the spawn/release paths use. Concretely: a spawn racing with close can computeIfAbsent the very scope close is removing and end up publishing an agent into an orphaned ScopedRegistry that is no longer reachable (never closed, never removable), and registry.users (a plain int) is incremented under one lock and never reconciled by close. Since close is exactly the path that is supposed to guarantee nothing leaks, please take the same two locks here (or swap registries to hold an atomic refcount) so the invariant is enforced rather than hoped for.

return true;
}

private synchronized boolean beginClose() {

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.

beginClose() ignores inFlight, unlike beginRelease(). That means close() will closeAgent() underneath a live execution, and the holder's Lease.close() then decrements a counter on an already-RELEASED agent. If force-closing in-flight children on parent shutdown is the intent, fine — but the asymmetry with beginRelease() deserves a comment saying so, because inFlight otherwise reads like a universal guard. Also note inFlight is only incremented by tryAcquire(); any code path that invokes managed.spawned.agent() without holding a lease (worth a grep for spawned.agent() outside the lease helpers) will be invisible to release and could be closed mid-call.

@JsonProperty("spawn_registry")
public Map<String, SpawnEntry> getSpawnRegistry() {
return Map.copyOf(spawnRegistry);
synchronized (spawnRegistry) {

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.

Guarding spawnRegistry with synchronized here is the right call, but note the monitor is the map itself, which is reachable from a serialized/deserialized state graph. LinkedHashMap is also still mutated through getSpawnRegistry() callers who hold a stale snapshot. Consider a private final lock object plus immutable-snapshot-on-write, so nothing outside this class can accidentally lock the wrong thing or mutate the returned map.

if (state != LifecycleState.ACTIVE) {
return null;
}
inFlight++;

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.

ManagedAgent mixes a synchronized state machine (state, inFlight) with two AtomicReferences for gateway exposure. exposedSubagentId/exposureBridge are cleared with getAndSet(null) in closeManagedAgent, which is outside the monitor, so two concurrent releases of the same managed agent can each see a non-null half of the pair at worst once — harmless today because both are cleared before markReleased(), but folding them into the same monitor would make the lifecycle easier to reason about, which is the whole point of this PR.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR has conflicts with the main branch and cannot be merged. Please rebase or merge main into your branch and resolve the conflicts:

git fetch origin
git checkout codex/fix-2915-agent-retention
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review after conflicts are resolved.


*Automated notification by *

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Correction: the merge-conflict reminder above was posted with an empty bot signature due to a template-variable bug in the automation. The content and the action requested are unchanged.


Automated notification by github-manager-bot

@jujn jujn reopened this Oct 27, 2026
@mintlify

mintlify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 4d72f0d.

Approve preview

@jujn jujn added the P2 重要不紧急 label Nov 4, 2026
@jujn
jujn merged commit c792de6 into agentscope-ai:main Nov 19, 2026
7 checks passed
xzxiaoshan added a commit that referenced this pull request Nov 20, 2026
…#4274)

## Background

Swept the last 125 PRs (#4272→#4075) for single-OS CI failures under
`mvn -B -T1C clean verify` (one build OS red, the other green on the
same commit = flake suspect). Cross-PR repeats and main's own red run on
2026-11-19 (ubuntu, run 44516464414) pinpoints four still-broken test
classes; all fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `RocketMqExecutionTest` | #4182, #4192, #4103 + main run 44516464414
(2026-11-19, ubuntu) | `turn reaches SUCCEEDED did not become true
within 10s` while the turn kept progressing (modelCalls complete, acks
climbing, lastFailure=none) — deadline breakthrough under starvation,
not a lost turn | shared `waitUntil` deadline 10s→30s (repo tier
#3726/#3774) |
| `AgentScopeAdapterTest` | #4204 (same-commit re-run green = confirmed
flake), #4191, #4246 | `Timed out observing Turn` at 6.7–8.5s elapsed;
resume/recovery one step from terminal | `turn.await(5s)`→30s at all 3
sibling sites via `TURN_DEADLINE`, outer `get` budgets +5s margin |
| `WorkerRuntimeTest` | #4219, #4224, #4255 (windows) | (a) `Worker
lease lost` after 2.4s — 1s claim leases expired between claim and
release; (b) `renewed.await(5s)` missed at 6.5s while the recovery lane
was healthy; (c) `Interrupted sleep interrupted` —
`WorkerRuntime.process()` interrupts the calling thread on lease-renewal
failure and manual `tick()` runs it on the test thread | (a) claim
leases 1s→30s (staleness under test still comes from `release(ZERO)` +
re-claim); (b) latches 5s→30s; (c) raw `Thread.sleep`→interrupt-proof
`pause()` at 5 sites, mirroring the #4176 fix for the same signature in
`ProcessRecoveryTest` |
| `ChatSessionsTest.await` (shared with `ChatControllerTest`) | #4233,
#4182 (stuck-RUNNING at 40.8s/46.4s), #4268, #4163 (poll threw `Durable
database transaction failed`) | two surfaces of one cause: every
snapshot poll opens a writing sqlite transaction contending with the
runtime's own writes, and windows runners starve turns past 30s (same
file already measured 56.6s starvation and uses 120s elsewhere, #3726) |
deadline 30s→120s (aligned tier) + tolerate transient `UNAVAILABLE`
store exceptions while polling; persistent failure rethrows at the
deadline, FAILED-turn fast-fail unchanged |
| `CommandExecutorTest.missingExitCodeIsUnknown` | local -T2C full-repo
stress (2026-11-19; pristine-main baseline of the same class green) |
the 2s network budget fired on scheduler starvation before the instant
fake response was processed, misclassifying the failure as a deadline
miss instead of a missing exit code (2.97s elapsed) | budget 2s→30s for
this non-deadline-semantics test; the two deadline-semantics tests keep
their tight budgets |

## Constraint compliance

- Happy path zero cost: every change only extends failure-path deadlines
or hardens helpers; no new sleeps, no weakened assertions.
- Minimal widening anchored to measured data (each comment cites victims
+ measured values); 30s follows the repo's established deflake tier,
120s follows this file's own previously measured starvation tier.
- Structural hardening preferred: `pause()` helper, transient-lock
retry, lease decoupling from the tested invariant.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`ProcessRecoveryTest.replacementCollectsOriginalResultWithoutRepeatingEffect`
(#4214: `expected: 2 but was: 3`): recovery-semantics race (model re-run
without effect re-run after abrupt halt) — a product question for the
durable recovery work, not a deadline flake.
-
`JevEvidenceProcessorTest.filterFailureIsWithheldButRankFailureFollowsScoredEvidence`
(#4265: delivered `[]` on a 25×-slowed runner): root cause not
established; single occurrence.
- Already fixed upstream, victims predate the fix:
`AgentScopeAgentExecutorInputRequiredTest` (#4157/#4187/#4152 all
predate #4176's `BaseReActAgentRunner` change), `InboxMiddlewareTest`
(#4093 predates #3738), `HarnessAgentSubagentStreamEventsTest` (#4183
predates #2917).
- `SkillBoxTest$UploadContainment` quartet (#4201/#4202/#4212/#4229):
test does not exist on main (fork stack only); deterministic cross-drive
path bug, not load flakiness.
- #4184/#4185: both-OS compile breaks from dependency major bumps
(dependabot), out of scope.

Also applied during review: sibling sites with the identical measured
mechanism were widened in the same pass — the remaining 1s fixture claim
leases in `WorkerRuntimeTest` (fenced begin/update/release sequences,
same #4219 signature), the start/PAUSED 5s budgets in the same
`AgentScopeAdapterTest` method as the victims, and the 5s/4s observe
budgets in
`completeLocalBackendRunsNativeAgentWhileManagedObserverIsBlocked`.

## Test plan

- [x] Full local `mvn -B -T2C clean verify` green (stricter than CI's
-T1C). Locally excluded, each verified to fail identically on pristine
main on this machine (Windows/git-bash) while passing on CI:
`JsonFileAgentStateStoreTest` (symlink permissions), the
`agentscope-extensions-durable-sandbox` trio plus
`ToolInSandboxExampleTest`/`SandboxRoundTripTest` (sandbox shell heredoc
incompatible with local git-bash python3), and the
`AgentScopeAdapterTest`/`ProcessRecoveryTest`/`HarnessExternalToolProcessRecoveryTest`
trio (durable-adapter classes whose Windows runs are skipped on CI; the
same named tests fail on pristine main locally).
- [ ] CI green on both OS.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: AgentSpawnTool retains every non-persistent spawned Agent indefinitely

4 participants