Skip to content

fix(subagents): retry archived session deletes after sweep failures - #61801

Merged
jalehman merged 2 commits into
openclaw:mainfrom
electricsheephq:fix/sweep-sessions-delete-orphan-leak-v2
Apr 10, 2026
Merged

jalehman merged 2 commits into
openclaw:mainfrom
electricsheephq:fix/sweep-sessions-delete-orphan-leak-v2

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • make archive sweep deletion retry-safe by preserving run state until sessions.delete succeeds
  • prevent overlapping archive sweep retries while a delete is still in flight
  • keep this PR narrowly scoped to sweep retry / overlap behavior only

What this fixes

When delete-mode subagent cleanup reaches the archive sweep path, a failed sessions.delete call should not permanently lose the run record. This PR keeps the archived run entry around for retry and prevents a second sweep pass from overlapping the same in-flight delete.

What changed

  • call sessions.delete before deleting the archived run record during sweep
  • keep the archived run entry and retained attachments intact when sessions.delete fails so the next sweep can retry
  • add a sweepInProgress guard so overlapping sweep intervals do not duplicate delete attempts
  • add focused archive-sweep coverage for retry preservation and in-flight overlap protection

Scope

Files changed

  • src/agents/subagent-registry.ts
  • src/agents/subagent-registry.archive.e2e.test.ts
  • src/agents/subagent-registry.persistence.test.ts

Validation

  • pnpm test src/agents/subagent-registry.persistence.test.ts
  • pnpm test src/agents/subagent-registry.archive.e2e.test.ts

Copilot AI review requested due to automatic review settings April 6, 2026 09:57
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Apr 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adjusts subagent orphan cleanup/recovery behavior to avoid prematurely pruning in-flight sessions and to improve testability of orphan recovery logic.

Changes:

  • Adds an orphan-pruning grace window (ORPHAN_GRACE_MS) to reduce false-positive orphan detection during startup reconciliation.
  • Reorders context-engine “subagent ended” notification to occur after a sessions.delete attempt in the sweeper.
  • Introduces a small DI seam (OrphanRecoveryDeps) to allow injecting loadConfig/callGateway in orphan recovery code.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
src/agents/subagent-registry.ts Moves context-engine notification later in the sweep flow, but sweep deletion/retry behavior still needs correction.
src/agents/subagent-registry-helpers.ts Adds ORPHAN_GRACE_MS and grace-window logic to resolveSubagentRunOrphanReason.
src/agents/subagent-orphan-recovery.ts Adds dependency-injection seam for loadConfig and callGateway and threads it through recovery flow.
Comments suppressed due to low confidence (1)

src/agents/subagent-registry.ts:476

  • sweepSubagentRuns() still deletes the run record (subagentRuns.delete) before calling sessions.delete. If sessions.delete fails (gateway down/timeout), the run record is already gone and there’s no retry path, leaving an orphaned session-store entry. To match the PR intent, only delete/persist the run record (and consider attachment cleanup) after sessions.delete succeeds; on failure keep the run entry so the next sweep can retry.
    clearPendingLifecycleError(runId);
    subagentRuns.delete(runId);
    mutated = true;
    // Archive/purge is terminal for the run record; remove any retained attachments too.
    await safeRemoveAttachmentsDir(entry);

Comment thread src/agents/subagent-registry.ts Resolved
Comment thread src/agents/subagent-registry.ts Resolved
@greptile-apps

greptile-apps Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds three safeguards around subagent orphan handling: a 5-minute grace window (ORPHAN_GRACE_MS) that prevents newly-created runs from being prematurely classified as orphans, a DI seam (OrphanRecoveryDeps) for testability in subagent-orphan-recovery.ts, and a reordering of notifyContextEngineSubagentEnded in the sweep loop so it fires after sessions.delete rather than before.

The grace window and DI seam changes look correct and well-structured. However, the sweepSubagentRuns change has a significant discrepancy between the PR description and the actual implementation:

  • Described: run record deleted only after sessions.delete succeeds; warning logged and entry retried on failure.
  • Actual: subagentRuns.delete(runId) still executes before callGateway (unchanged); sessions.delete failures are silently ignored (// ignore). Only the notification ordering changed.

This means the retry-on-failure path described for the sweep loop does not exist, and a sessions.delete failure will silently leave an orphaned gateway session with no recovery on the next cycle."

Confidence Score: 2/5

Not safe to merge as-is: the sweep loop's described retry-on-failure behavior is unimplemented, leaving a class of gateway session leaks unaddressed.

The grace window and DI seam are implemented correctly, but the core sweep ordering fix described in the PR summary was not actually made. The run record is still deleted before the gateway call and failures are silently swallowed — this is not a regression from main, but it means the fix is incomplete relative to its stated goals, and the inaccurate PR description will mislead future readers about what #49004 guarantees.

src/agents/subagent-registry.ts — sweepSubagentRuns does not implement the retry/reorder semantics described in the PR summary.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/subagent-registry.ts
Line: 472-496

Comment:
**Run-record deletion is not actually reordered**

The PR description states: *"`sweepSubagentRuns()` now deletes run record only after gateway `sessions.delete` succeeds. On failure, logs warning and retries next sweep cycle."* But the diff shows none of that was implemented.

`subagentRuns.delete(runId)` is still at line 473, unconditionally, **before** the `callGateway` call at line 478 — the same position as in the pre-PR code. The `catch` block still contains only `// ignore` with no warning and no retry: if `sessions.delete` fails, the in-memory run record is already gone and the failure is silently swallowed. There is no mechanism to retry on the next sweep cycle.

The one real change here — moving `notifyContextEngineSubagentEnded` to fire after `sessions.delete` rather than before — is a genuine improvement. But the described run-record reordering and retry-on-failure behaviour are absent.

If the intent is to only delete the run record after the gateway confirms the session is gone and retry on failure, the sweep body should be restructured so that `subagentRuns.delete` / `mutated = true` / `notifyContextEngineSubagentEnded` are inside the success path, and the `catch` block logs a warning and leaves the record intact for the next sweep cycle:

```ts
try {
  await subagentRegistryDeps.callGateway({
    method: "sessions.delete",
    params: { key: entry.childSessionKey, deleteTranscript: true, emitLifecycleHooks: false },
    timeoutMs: 10_000,
  });
  // Only clean up after gateway confirms deletion
  subagentRuns.delete(runId);
  mutated = true;
  await safeRemoveAttachmentsDir(entry);
  void notifyContextEngineSubagentEnded({
    childSessionKey: entry.childSessionKey,
    reason: "swept",
    workspaceDir: entry.workspaceDir,
  });
} catch (err) {
  log.warn(`sweepSubagentRuns: sessions.delete failed for ${runId}, will retry next cycle: ${String(err)}`);
  // Leave the record intact; archiveAtMs already elapsed so next sweep retries.
}
```

Alternatively, if the intention was only to reorder the notification (the actual change), the PR description should be corrected so reviewers and future readers are not misled about what #49004 guarantees.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(agents): improve orphan reconciliati..." | Re-trigger Greptile

Comment thread src/agents/subagent-registry.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d765b86238

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry-helpers.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Related issues: This PR also relates to #61741 (race condition in subagent/session cleanup causes late child stdout to hit cleared active run, leading to announce timeout and orphaned child processes), #44925 (subagent completion silently lost — no retry, no notification, no auto-restart on timeout), and #53810 (subagent premature announce bug — model-specific tool call handling issues). These share the same subagent lifecycle and orphan reconciliation code paths. Note: the original linked issue #49004 is now closed.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a6c969be97

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0584c223fe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry-helpers.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

Comment thread src/agents/subagent-registry.ts Resolved
Comment thread src/agents/subagent-registry.ts Resolved
Comment thread src/agents/subagent-registry-helpers.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

@100yenadmin 100yenadmin changed the title fix(agents): startup orphan reconciliation grace period — prevent deletion of in-flight subagent sessions fix(subagents): retry archived session deletes after sweep failures Apr 10, 2026
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Refreshed this PR on current main and narrowed it to the sweep-order / retry-preservation slice from issue #49000.

What is in scope now:

  • do not drop the archived run record before sessions.delete succeeds
  • keep archived delete-mode runs retryable when sessions.delete fails
  • avoid overlapping sweep passes while a prior archive delete is still in flight
  • keep the archive-sweep regression coverage focused on retry + overlap behavior

What is intentionally out of scope now:

  • startup orphan grace-window protection
  • deferred post-grace orphan recheck
  • orphan-recovery dependency threading

Those startup/orphan protections are being split into a separate follow-up branch so they can be reviewed independently from the sweep retry fix.

Targeted validation:

  • pnpm exec node scripts/run-vitest.mjs run --config vitest.agents.config.ts src/agents/subagent-registry.persistence.test.ts
  • Result: 1 file, 12 tests passed
  • pnpm exec vitest run --config vitest.e2e.config.ts src/agents/subagent-registry.archive.e2e.test.ts
  • Result: 1 file, 9 tests passed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread src/agents/subagent-registry.ts Resolved
@jalehman jalehman self-assigned this Apr 10, 2026
@jalehman
jalehman merged commit 3b289c7 into openclaw:main Apr 10, 2026
8 checks passed
@jalehman

Copy link
Copy Markdown
Contributor

Merged via squash.

Thanks @100yenadmin!

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…penclaw#61801)

Merged via squash.

Prepared head SHA: 1152c26
Co-authored-by: 100yenadmin <[email protected]>
Co-authored-by: jalehman <[email protected]>
Reviewed-by: @jalehman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants