Skip to content

fix(subagents): deduplicate completion announce — prevent duplicate internal-context turns in parent session on retry - #61525

Merged
obviyus merged 3 commits into
openclaw:mainfrom
electricsheephq:fix/61479-announce-dedup
Apr 10, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
electricsheephq:fix/61479-announce-dedup

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes (plain English)

When a sub-agent completed its task but the completion announcement failed partway, retrying the cleanup would re-announce the completion to the parent agent — causing duplicate messages. This fix tracks whether the announcement was already delivered and skips re-announcing on retry, only performing cleanup bookkeeping.

Technical details

Root cause: No deduplication of the completion announce flow. On retry/re-entry after a partial cleanup failure, the entire announce+inject cycle re-ran even if the parent had already received the completion message.

Fix:

  • Persist completionAnnouncedAt on the subagent run record after successful delivery
  • Skip announce injection for runs where delivery already succeeded, proceeding directly to cleanup
  • Lifecycle regression test covering retry/re-entry after successful delivery

Files changed:

  • src/agents/subagent-registry.ts — sweep integration with dedup tracking, completionAnnouncedAt persistence
  • src/agents/subagent-registry.types.ts — type definition for completionAnnouncedAt field on subagent run records
  • src/agents/subagent-registry-lifecycle.ts — announce dedup and delivery tracking logic
  • src/agents/subagent-registry-lifecycle.test.ts — lifecycle regression tests for dedup announce behavior

Related

Test plan

  • 8/8 lifecycle tests pass
  • Deduped announce skips re-injection for already-delivered completions
  • Ended hook fires correctly on retry with sendFarewell: true
  • cleanupCompletedAt set correctly on dedup path

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Apr 5, 2026
@100yenadmin
100yenadmin marked this pull request as ready for review April 5, 2026 22:20
Copilot AI review requested due to automatic review settings April 5, 2026 22:20

@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: eced002a2a

ℹ️ 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".

@greptile-apps

greptile-apps Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces completionAnnouncedAt as a persisted timestamp on SubagentRunRecord to deduplicate the completion-announce flow: once a subagent's completion message has been successfully delivered, retries skip re-injection and go directly to hook emission and attachment cleanup via finalizeSubagentCleanup({ skipAnnounce: true }). The two previously flagged issues (retry skipping the ended-hook and attachment cleanup, and missing test coverage for the hook-emission retry path) have been addressed in this revision.

Confidence Score: 5/5

Safe to merge — the deduplication logic is correct, retry paths preserve all required side-effects, and the previously flagged gaps have been addressed.

All remaining findings are P2 or lower. The core logic correctly gates on completionAnnouncedAt, re-routes retries through finalizeSubagentCleanup with skipAnnounce: true (so hook emission and attachment cleanup still run), and resets the field in the killed-suppress path. The four new tests cover the dedup, hook-on-retry, give-up, and delivery-status-throw scenarios. No blocking issues remain.

No files require special attention.

Reviews (2): Last reviewed commit: "fix(subagents): dedupe delivered complet..." | Re-trigger Greptile

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

This PR addresses subagent completion-announcement retries causing duplicate internal-context turns in the parent session by persisting a “delivered” marker on the subagent run record and short-circuiting subsequent announce attempts.

Changes:

  • Add completionAnnouncedAt to persisted SubagentRunRecord to mark successful completion announce delivery.
  • Skip re-running the announce flow when completionAnnouncedAt is already set, and finish cleanup bookkeeping instead.
  • Add a regression test covering re-entry after a successful delivery.

Reviewed changes

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

File Description
src/agents/subagent-registry.types.ts Adds completionAnnouncedAt to the run record schema.
src/agents/subagent-registry-lifecycle.ts Sets/persists delivery marker and short-circuits announce cleanup flow based on it.
src/agents/subagent-registry-lifecycle.test.ts Adds regression test ensuring announce flow isn’t re-run once delivery is marked.
Comments suppressed due to low confidence (2)

src/agents/subagent-registry-lifecycle.ts:395

  • completionAnnouncedAt is set before several operations that can throw (e.g., setDetachedTaskDeliveryStatusByRunId, hook emission, attachment cleanup). If any of those throws, the entry will still have completionAnnouncedAt set, and the next re-entry will short-circuit announce+cleanup (see startSubagentAnnounceCleanupFlow) and can skip important cleanup steps (attachment deletion, hook emission, clearing wake/fallback state). Consider either (a) wrapping the post-announce cleanup steps so they can’t abort the function, and only setting/persisting completionAnnouncedAt once the whole finalize path has safely passed the point of no return, or (b) changing the short-circuit path to run the remaining cleanup steps when completionAnnouncedAt is present (skip delivery, but still do hooks/attachments/state cleanup).
    if (didAnnounce) {
      entry.completionAnnouncedAt = Date.now();
      setDetachedTaskDeliveryStatusByRunId({
        runId,
        runtime: "subagent",
        sessionKey: entry.childSessionKey,
        deliveryStatus: "delivered",
      });
      entry.wakeOnDescendantSettle = undefined;
      entry.fallbackFrozenResultText = undefined;
      entry.fallbackFrozenResultCapturedAt = undefined;
      const completionReason = resolveCleanupCompletionReason(entry);
      await emitCompletionEndedHookIfNeeded(entry, completionReason);
      const shouldDeleteAttachments = cleanup === "delete" || !entry.retainAttachmentsOnKeep;
      if (shouldDeleteAttachments) {
        await safeRemoveAttachmentsDir(entry);
      }
      if (cleanup === "delete") {
        entry.frozenResultText = undefined;
        entry.frozenResultCapturedAt = undefined;
      }
      completeCleanupBookkeeping({
        runId,
        entry,
        cleanup,
        completedAt: Date.now(),
      });

src/agents/subagent-registry-lifecycle.ts:376

  • In the success path (didAnnounce === true), setDetachedTaskDeliveryStatusByRunId(...) is called directly and can throw (there’s already a dedicated safeSetSubagentTaskDeliveryStatus wrapper used on the failure/give-up path). If this throws, it will abort the finalize path and also prevent completionAnnouncedAt from being persisted, reintroducing duplicate announce injection after restart. Recommend using the safe wrapper (or an equivalent try/catch) here as well.
      entry.completionAnnouncedAt = Date.now();
      setDetachedTaskDeliveryStatusByRunId({
        runId,
        runtime: "subagent",
        sessionKey: entry.childSessionKey,
        deliveryStatus: "delivered",
      });

@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: 8f42b955ef

ℹ️ 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".

@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: 69562014c7

ℹ️ 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".

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The retry path issue (missing emitCompletionEndedHookIfNeeded and safeRemoveAttachmentsDir) was addressed -- the short-circuit now re-enters finalizeSubagentCleanup with { skipAnnounce: true }, which runs both ended-hook emission and attachment cleanup. The NaN bug on the give-up path has also been fixed with ?? 0 defaulting. Regression tests added for both scenarios.

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 4 out of 4 changed files in this pull request and generated 5 comments.

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

Copy link
Copy Markdown
Contributor Author

Related issues: This PR also relates to #59996 (heartbeat model config ignored unless heartbeat session has persisted override), #56941 (heartbeat isolatedSession: true does not create fresh sessions), and #52015 (overlapping heartbeat runs overwrite session and cause nested session keys). These share the same session routing/key management code paths.

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 4 out of 4 changed files in this pull request and generated 1 comment.

Comment thread src/agents/subagent-registry.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 4 out of 4 changed files in this pull request and generated 2 comments.

Comment thread src/agents/subagent-registry.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 4 out of 4 changed files in this pull request and generated 2 comments.

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: eb6919e62f

ℹ️ 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

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 5 out of 5 changed files in this pull request and generated no new comments.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

@steipete @jalehman another I run locally that cuts token usage and increases efficiency of gateway when running multi agent sprints (helps with gateway stalling as well during heavy sprints).

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Refreshed this PR on current main and narrowed it to the dedup-only slice from issue #61479.

What is in scope now:

  • persist a completionAnnouncedAt-style guard on the run record
  • skip rerunning the internal completion announce flow after it has already been delivered
  • still finish cleanup / hooks correctly on retry or re-entry
  • tolerate post-delivery bookkeeping write failures without re-announcing

What is intentionally out of scope now:

  • subagent-registry.ts sweep ordering
  • orphan-session reconciliation / startup grace-window changes

Those cleanup/orphan changes are being split away so they can be reviewed independently from the duplicate-announcement fix.

Targeted validation:

  • pnpm exec node scripts/run-vitest.mjs run --config vitest.agents.config.ts src/agents/subagent-registry-lifecycle.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 4 out of 4 changed files in this pull request and generated no new comments.

@obviyus

obviyus commented Apr 10, 2026

Copy link
Copy Markdown
Collaborator

@greptile-apps review

@greptile-apps

greptile-apps Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

Tip:

Greploop — Automatically fix all review issues by running /greploops in Claude Code. It iterates: fix, push, re-review, repeat until 5/5 confidence.

Use the Greptile plugin for Claude Code to query reviews, search comments, and manage custom context directly from your terminal.

@obviyus obviyus self-assigned this Apr 10, 2026

@obviyus obviyus 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.

Verified the duplicate subagent completion-turn bug and confirmed the fix keeps retry/re-entry on one cleanup path while skipping only the already-delivered announce injection.

Maintainer follow-up: distilled the delivered/failed detached-task delivery-status writes onto the shared safe helper and added the changelog entry in the active Unreleased fixes block.

Local gate: pnpm test src/agents/subagent-registry-lifecycle.test.ts

@obviyus obviyus 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.

Verified the duplicate subagent completion-turn bug and confirmed the fix keeps retry/re-entry on one cleanup path while skipping only the already-delivered announce injection.

Maintainer follow-up: distilled the delivered/failed detached-task delivery-status writes onto the shared safe helper, rebased onto current main, and kept the changelog entry at the end of the active Unreleased fixes block.

Local gate: pnpm test src/agents/subagent-registry-lifecycle.test.ts

@obviyus
obviyus merged commit 47c0a51 into openclaw:main Apr 10, 2026
7 checks passed
@obviyus

obviyus commented Apr 10, 2026

Copy link
Copy Markdown
Collaborator

Landed on main.

Thanks @100yenadmin.

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…(thanks @100yenadmin)

* fix(subagents): dedupe delivered completion announces

* refactor(subagents): distill cleanup delivery status writes

* fix: dedupe delivered subagent completion announces (openclaw#61525) (thanks @100yenadmin)

---------

Co-authored-by: Eva <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…(thanks @100yenadmin)

* fix(subagents): dedupe delivered completion announces

* refactor(subagents): distill cleanup delivery status writes

* fix: dedupe delivered subagent completion announces (openclaw#61525) (thanks @100yenadmin)

---------

Co-authored-by: Eva <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@6tizer

6tizer commented May 3, 2026

Copy link
Copy Markdown

Reproducing on v2026.5.2 (Telegram)

I can confirm this issue is still reproducible on OpenClaw 2026.5.2 with Telegram channel.

Environment

  • OpenClaw: 2026.5.2 (8b2a6e5)
  • OS: macOS 26.4.1 (Apple Silicon)
  • Channel: Telegram
  • Main model: zai/glm-5-turbo

Symptoms

When a subagent (X bookmark topic scanning) completes, the parent session receives the completion announcement multiple times and sends duplicate messages to the Telegram user.

From session logs:

  1. Subagent completes successfully at 15:08
  2. Parent session receives completion announce
  3. Compaction triggers at the same time
  4. Prompt error: "This operation was aborted"
  5. Same completion announce arrives again
  6. Parent sends duplicate messages to user

Impact

  • Confusing UX for Telegram users
  • Token waste processing duplicate results
  • No dedup mechanism in parent session

Workaround

Currently adding manual dedup rules in AGENTS.md, but this should be handled at the framework level.

Would appreciate a fix for this. The deterministic idempotency keys from #17150 helped with some cases, but the retry/re-entry path still causes duplicates.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…(thanks @100yenadmin)

* fix(subagents): dedupe delivered completion announces

* refactor(subagents): distill cleanup delivery status writes

* fix: dedupe delivered subagent completion announces (openclaw#61525) (thanks @100yenadmin)

---------

Co-authored-by: Eva <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…(thanks @100yenadmin)

* fix(subagents): dedupe delivered completion announces

* refactor(subagents): distill cleanup delivery status writes

* fix: dedupe delivered subagent completion announces (openclaw#61525) (thanks @100yenadmin)

---------

Co-authored-by: Eva <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…(thanks @100yenadmin)

* fix(subagents): dedupe delivered completion announces

* refactor(subagents): distill cleanup delivery status writes

* fix: dedupe delivered subagent completion announces (openclaw#61525) (thanks @100yenadmin)

---------

Co-authored-by: Eva <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
chovizzz added a commit to chovizzz/openclaw that referenced this pull request Sep 5, 2026
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.

bug(subagents): completion announce retry re-injects duplicate internal-context turns — transcript bloat and lane starvation

4 participants