Skip to content

fix(subagents): keep in-flight announce handoffs retryable - #136820

Closed
leilei3167 wants to merge 8 commits into
openclaw:mainfrom
leilei3167:fix/subagent-inflight-handoff-pending-credit
Closed

leilei3167 wants to merge 8 commits into
openclaw:mainfrom
leilei3167:fix/subagent-inflight-handoff-pending-credit

Conversation

@leilei3167

@leilei3167 leilei3167 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #136513

A duplicate subagent completion handoff using the same idempotency key can get status: "in_flight" (with admissionPending) while the original handoff is still admitting or executing. Direct announce delivery was treating that nonterminal response as { delivered: true, path: "direct" }, which credited delivery and retired retry state before any terminal evidence existed.

Changes

  • Map nonterminal gateway announce responses to a retryable non-delivery (completion_handoff_pending, terminal: true) so custody stays open and same-attempt media fallback stays suppressed.
  • Honor terminal on the completion direct-primary dispatch branch so a retryable pending result does not fall through to steer fallback.
  • Retain original handoff ownership after in_flight: a later retry joins the same-key Gateway result even when the original run has settled and a successor requester turn is active, instead of steering into that successor. First-attempt steering is unchanged when nothing is retained yet.
  • Bind retained handoff keys to announce lifecycle cleanup: keep across retryable pending attempts; release on terminal retirement (success, abandonment, permanent failure, deadline expiry / give-up via clearSubagentPendingDelivery and suspendPendingFinalDelivery).
  • Fix oxlint import/first in subagent-announce-direct-delivery.ts (file comment + all imports before re-exports).
  • Regression: in-flight + admissionPending → no credit / no fallback; later terminal ok on the same key → delivered; settled A + active successor B → replay A's cached terminal, no steer; retention released on abandonment / cleanup retirement.
  • Keep completion_handoff_pending out of the settle-wake failure replay budget: schedule same-key observation backoffs without spending replayCount / completeBatch on the third pending observation.
  • Enforce absolute lifecycle expiry for pending settle observations: reuse delivery.deadlineAt when present, otherwise the announce hard-expiry clock (ANNOUNCE_COMPLETION_HARD_EXPIRY_MS); past expiry retires via completeBatch (requester settle wake expired) and releases the handoff identity.

Evidence

$ node_modules/.bin/oxlint src/agents/subagents/announce/subagent-announce-direct-delivery.ts
# exit 0 (import/first fixed)

$ node_modules/.bin/vitest run \
    src/agents/subagents/announce/subagent-announce-delivery.test.ts \
    src/agents/subagents/announce/subagent-announce-dispatch.test.ts \
    src/agents/subagents/announce/subagent-announce-completion-handoff-retention.test.ts
 Test Files  3 passed (3)
      Tests  295 passed (295)

$ node_modules/.bin/vitest run --config test/vitest/vitest.agents-support.config.ts \
    subagents/announce/subagent-announce.requester-settle-wake.test.ts
 Test Files  1 passed (1)
      Tests  37 passed (37)
# includes:
# - keeps a pending handoff through both backoffs without spending the failure replay budget
# - retires pending settle observations past the announce lifecycle deadline
# - honors an inherited delivery.deadlineAt for pending settle expiry

Pending settle-wake fix (tip 9dd9517792b): completion_handoff_pending stays outside scheduleSameKeyReplay / failure budget. Same attempt key observes on 30s then 120s backoffs without incrementing replayCount. Pending observations now persist deadlineAt from delivery.deadlineAt (min across the batch) or now + ANNOUNCE_COMPLETION_HARD_EXPIRY_MS; past that bound completeBatch with requester settle wake expired clears the wake and releases retained handoff identity. Within the bound, pending retries still do not consume the failure budget.

Retention lifecycle unit coverage: preserve across retryable pending; release on abandonment / success / permanent failure / pending observation expiry; release via clearSubagentPendingDelivery / child-run retirement helper.

Residual: true Gateway e2e / Control UI admission+replay owner proof is not available on this box. Strongest in-repo coverage is the settle-wake unit path above (pending observation within bound → terminal delivery; pending beyond announce deadline → terminal expiry cleanup).

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 3, 2026
@leilei3167

Copy link
Copy Markdown
Contributor Author

@steipete quick check-in on this one — maps in-flight/admission-pending announce responses to retryable non-delivery so we don't credit before terminal evidence. Focused announce delivery + dispatch tests pass locally.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 11, 2026, 11:08 PM ET / September 12, 2026, 03:08 UTC (Revision 24).

ClawSweeper review

What this changes

The PR keeps unfinished subagent completion handoffs retryable under the same identity, suppresses fallback delivery, and adds retention cleanup, persisted settlement expiry, and regression coverage.

Merge readiness

⛔ Blocked before merge - 6 items remain

This PR remains necessary: current main and v2026.9.4 still credit unfinished handoffs as delivered. The discussion adds a useful composition regression, and the related merged repairs do not resolve this replay defect.

Priority: P1
Reviewed head: 6bd6b32a78b4bb969b6005f9b1acc68f1ef6fea5
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The repair has useful source and regression evidence, but broken fixtures, runtime-proof gaps, and unresolved durable expiry semantics prevent merge readiness.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: Needs real behavior proof before merge: the composition regression exercises real reservation, replay, facade, and direct-announcement owners, but substitutes persistence and terminal delivery. It does not show after-fix pending-to-final recovery, successor isolation, or durable expiry cleanup through a real runtime boundary. Redacted terminal traces or logs count; screenshots or recordings help when they show the behavior. Remove private addresses, endpoints, keys, phone numbers, and user data. Update the PR body with proof to trigger re-review; if needed, ask a maintainer to comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: Needs real behavior proof before merge: the composition regression exercises real reservation, replay, facade, and direct-announcement owners, but substitutes persistence and terminal delivery. It does not show after-fix pending-to-final recovery, successor isolation, or durable expiry cleanup through a real runtime boundary. Redacted terminal traces or logs count; screenshots or recordings help when they show the behavior. Remove private addresses, endpoints, keys, phone numbers, and user data. Update the PR body with proof to trigger re-review; if needed, ask a maintainer to comment @clawsweeper re-review.
Evidence reviewed 11 items Current main still contains premature delivery credit: The pending-response branch returns delivered: true before inspecting terminal delivery evidence.
Latest release also retains the defect: The v2026.9.4 source returns delivered: true for a pending Gateway response.
Introduced behavior and preserved execution fences: The merge-base-to-head diff changes pending credit, steering selection, retention, and settlement retries. The extracted agent-call helper preserves its existing cancellation, source-owner check, and delegated-policy arguments; this is an OpenClaw Gateway replay change without a demonstrated dependency on the Codex implementation.
Findings 1 actionable finding [P2] Supply the live requester lookup in both added registry mocks
Security None None.

How this fits together

Subagent announcement delivery carries completed child work back to the requesting agent and records whether delivery succeeded. Gateway replay responses feed this decision, while the subagent registry retains pending work and schedules settlement retries.

flowchart TD
  A[Child completes] --> B[Registry settlement batch]
  B --> C[Announcement delivery]
  C --> D[Gateway handoff replay]
  D --> E{Terminal evidence?}
  E -->|Pending| F[Retain identity and retry]
  F --> C
  E -->|Delivered| G[Record delivery and retire batch]
  F -->|Lifecycle expiry| H[Record blocked settlement]
Loading

Decision needed

Question Recommendation
Should pending requester-settle observations inherit the earliest child delivery deadline, or otherwise expire 30 minutes after their first pending observation? Calibrate and accept the lifecycle bound: Record the intended deadline, older-row behavior, and interaction with active requester execution after reviewing real persistence and recovery evidence.

Why: This adds a durable retirement policy that can end an outstanding completion obligation; repository policy requires explicit acceptance, and the earlier timeout repair does not approve this separate limit.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: Needs real behavior proof before merge: the composition regression exercises real reservation, replay, facade, and direct-announcement owners, but substitutes persistence and terminal delivery. It does not show after-fix pending-to-final recovery, successor isolation, or durable expiry cleanup through a real runtime boundary. Redacted terminal traces or logs count; screenshots or recordings help when they show the behavior. Remove private addresses, endpoints, keys, phone numbers, and user data. Update the PR body with proof to trigger re-review; if needed, ask a maintainer to comment @clawsweeper re-review.
  • Supply the live requester lookup in both added registry mocks (P2) - This full-module mock omits getLatestLiveSubagentRunByChildSessionKey, which the current settlement owner calls before dispatch at lines 358–363. Both replay cases therefore fail on the missing mock export before reaching their delivery assertions. The added subagent-announce.requester-settle-wake.outbox.test.ts factory has the same omission. Add the explicit lookup mock to both suites, as already done in the pending suite, and rerun them.
  • Resolve merge risk (P1) - The new persisted expiry can retire an outstanding settlement before its terminal reply is observed; acceptance and upgrade proof for fresh batches, older rows, restart, and overlapping descendants remain missing.
  • Resolve merge risk (P1) - Same-key recovery and successor isolation are covered with substituted delivery responses, leaving their composition with actual Gateway execution and final delivery unproven.
  • Complete next step (P2) - Repair the replay and outbox fixtures, obtain acceptance of the persisted expiry policy, and supply after-fix runtime and upgrade evidence.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P2] Supply the live requester lookup in both added registry mocks — src/agents/subagents/announce/subagent-announce.requester-settle-replay.test.ts:17-21
Agent review details

Security

None.

PR surface

Source +310, Tests +1214. Total +1524 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 403 93 +310
Tests 8 1543 329 +1214
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 1946 422 +1524

Review metrics

Metric Value Why it matters
Durable expiry surface 1 persisted deadline field; 30-minute fallback The new field controls retirement after restart and needs an accepted compatibility contract.
Production versus test growth Production net +310 lines; tests and support net +1,214 lines Production growth implements retained retry identity and bounded settlement observation; the test growth includes split suites and new regressions.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #136513
Summary: This PR is the candidate repair for the specific pending-replay accounting defect; nearby merged repairs address distinct settlement failures.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Validate settlement retirement before landing (recommended)
    Obtain expiry-policy acceptance and demonstrate same-key terminal recovery, successor isolation, and durable cleanup on fresh and restored state.
  2. Separate the expiry policy
    Pause the durable-deadline portion if its retirement semantics cannot yet be reconciled with active requester execution.

Technical review

Best possible solution:

Keep delivery obligations open until terminal evidence or an explicitly accepted lifecycle limit, with one settlement owner preserving identity and cleanup across retries and restart.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: replay can return in_flight, the facade returns it without waiting for a final, and current main credits delivery immediately. The discussion supplies a failing composition regression; this read-only review did not execute it.

Is this the best way to solve the issue?

Unclear as a complete solution: correcting pending credit and retaining the original identity fit the existing owners, but the durable expiry policy needs acceptance and recovery evidence.

Full review comments:

  • [P2] Supply the live requester lookup in both added registry mocks — src/agents/subagents/announce/subagent-announce.requester-settle-replay.test.ts:17-21
    This full-module mock omits getLatestLiveSubagentRunByChildSessionKey, which the current settlement owner calls before dispatch at lines 358–363. Both replay cases therefore fail on the missing mock export before reaching their delivery assertions. The added subagent-announce.requester-settle-wake.outbox.test.ts factory has the same omission. Add the explicit lookup mock to both suites, as already done in the pending suite, and rerun them.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 41861b8055af.

Labels

Label justifications:

  • P1: The central defect can retire required subagent completion delivery prematurely and remains present on current main and the latest release.
  • merge-risk: 🚨 compatibility: The new persisted deadline changes how existing and restored settlement obligations expire.
  • merge-risk: 🚨 message-delivery: Retry retention and expiry affect whether a completion is replayed, duplicated, or retired without an observed final.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Needs real behavior proof before merge: the composition regression exercises real reservation, replay, facade, and direct-announcement owners, but substitutes persistence and terminal delivery. It does not show after-fix pending-to-final recovery, successor isolation, or durable expiry cleanup through a real runtime boundary. Redacted terminal traces or logs count; screenshots or recordings help when they show the behavior. Remove private addresses, endpoints, keys, phone numbers, and user data. Update the PR body with proof to trigger re-review; if needed, ask a maintainer to comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Repair both missing registry mocks and rerun the replay and outbox suites.
  • Attach redacted after-fix runtime traces showing pending admission, same-key terminal recovery, successor isolation, and failure or expiry cleanup.
  • Record expiry-policy acceptance and verify fresh batches, older rows without deadlineAt, cold restoration, and overlapping descendants.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (23 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-06T11:22:06.802Z sha 9dd9517792be72fc8fcb1883afea3bf29c2205ea :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T12:18:43.034Z sha 9df73087bb548702f58676aeb4573b08836b8f47 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T01:42:15.451Z sha 02769a9050d31b2c3c471e9762ec8e392795238a :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T01:55:41.747Z sha 6715ecc7f77415516f0ad00f0c03885e79e58cf1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-07T03:36:33.649Z sha 36e036779767f33b33e76d930c27c1272b5a4454 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-09T04:46:05.439Z sha c8730ac69a0bc0b9b79db65310560d8667a63697 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-09T06:32:20.459Z sha a207f9889dc047e4d1853cc1de29b2bf6ef33efc :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-10T04:44:04.748Z sha 7359f30eab466a9cf9c298a43897175e257a0381 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Sep 4, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 5, 2026
@leilei3167
leilei3167 force-pushed the fix/subagent-inflight-handoff-pending-credit branch from 9d3acb8 to 9ca094a Compare September 6, 2026 09:51
@leilei3167
leilei3167 force-pushed the fix/subagent-inflight-handoff-pending-credit branch from 706c367 to dad3692 Compare September 6, 2026 10:47
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 6, 2026
vincentkoc added a commit that referenced this pull request Sep 6, 2026
#140018)

* fix(ci): keep preflight job outputs under GitHub's 1 MiB cap

Pull requests that need the full canonical Node test plan failed preflight
with "Job outputs exceed 1,048,576 bytes", which made ci-gate report every
lane as selected=missing. The compact plan lists 7,749 striped test files
explicitly, and GitHub measures job outputs in UTF-16, so the effective cap
for all preflight outputs is 524,288 characters. The manifest reached ~522K
characters on the github profile as the tracked test inventory grew.

Emit each Node matrix row's groups as gzip+base64 JSON at the manifest
boundary and unpack them in the shard runner. On current main this takes the
github-profile manifest from 522,522 to 195,410 characters and the blacksmith
profile from 450,639 to 158,571, with identical jobs and group membership.
The manifest imports the codec through the existing target-plan seam, the
trusted runner checkout lists it, and plain OPENCLAW_NODE_TEST_GROUPS_JSON
remains for the Vitest cache warmer.

Related to #139929 and #136820.

* fix(ci): load the Node test groups codec only for grouped rows

The manifest imported scripts/lib/ci-node-test-groups-codec.mts
unconditionally through importTargetPlan. An ordinary manual
workflow_dispatch whose target_ref predates the codec is not a
compatibility target, so the import threw before planning even though
such targets emit an ungrouped plan and never call the encoder.

Import the codec only when the emitted Node rows carry groups, and keep
the clear failure when a grouped plan comes from a target without it.
The workflow-guard fixture can now omit the codec so a codec-free manual
target runs the real manifest step.

* fix(ci): preserve grouped historical test plans

Negotiate the packed group codec against the selected target and fall back to the same five-field legacy projection when the codec is unavailable.

Five-field projection adapted from #140036.

Co-authored-by: Peter Steinberger <[email protected]>

---------

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 7, 2026
openclaw#140018)

* fix(ci): keep preflight job outputs under GitHub's 1 MiB cap

Pull requests that need the full canonical Node test plan failed preflight
with "Job outputs exceed 1,048,576 bytes", which made ci-gate report every
lane as selected=missing. The compact plan lists 7,749 striped test files
explicitly, and GitHub measures job outputs in UTF-16, so the effective cap
for all preflight outputs is 524,288 characters. The manifest reached ~522K
characters on the github profile as the tracked test inventory grew.

Emit each Node matrix row's groups as gzip+base64 JSON at the manifest
boundary and unpack them in the shard runner. On current main this takes the
github-profile manifest from 522,522 to 195,410 characters and the blacksmith
profile from 450,639 to 158,571, with identical jobs and group membership.
The manifest imports the codec through the existing target-plan seam, the
trusted runner checkout lists it, and plain OPENCLAW_NODE_TEST_GROUPS_JSON
remains for the Vitest cache warmer.

Related to openclaw#139929 and openclaw#136820.

* fix(ci): load the Node test groups codec only for grouped rows

The manifest imported scripts/lib/ci-node-test-groups-codec.mts
unconditionally through importTargetPlan. An ordinary manual
workflow_dispatch whose target_ref predates the codec is not a
compatibility target, so the import threw before planning even though
such targets emit an ungrouped plan and never call the encoder.

Import the codec only when the emitted Node rows carry groups, and keep
the clear failure when a grouped plan comes from a target without it.
The workflow-guard fixture can now omit the codec so a codec-free manual
target runs the real manifest step.

* fix(ci): preserve grouped historical test plans

Negotiate the packed group codec against the selected target and fall back to the same five-field legacy projection when the codec is unavailable.

Five-field projection adapted from openclaw#140036.

Co-authored-by: Peter Steinberger <[email protected]>

---------

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
@goslingmanagment

Copy link
Copy Markdown
Contributor

Current-main regression: canonical admission replay retires a required-visible settle batch

This adds a runnable composition case to #136820, beyond the historical release/deadline evidence already posted on #136513. Source baseline: c6138de0df9bb658b0c73442d4a271aa21c4bb6a; inspected PR head: 36e036779767f33b33e76d930c27c1272b5a4454 (open).

New proof: the fixture does not mock an in_flight RPC response or replace the turn service. It calls the real createAgentDedupeLifecycle.reserve, then composes real request preflight → turn-service cached replay → internal facade → direct announcement → requester-settle owner. Registry/session discovery and the request envelope are controlled. The delivery wrapper delegates to real direct delivery.

A previously dispatching, yielded generation requiring a visible final is replayed while its exact-key admission reservation is outstanding. The child already has a successful completion and delivered receipt. No timeout is advanced or injected.

node scripts/run-vitest.mjs src/agents/subagents/announce/subagent-announce.requester-settle-replay.test.ts

On unchanged main production: 1 failed / 1 passed. In the pending case the reservation remains accepted with its original reservationId, yet completeBatch is called with { delivered: true, path: "direct" }, the wake returns true, and the required-visible state is cleared. The terminal cached-transcript-final control passes.

Sensitivity check: changing only pending credit to retryable non-delivery made both cases pass (2 passed, 7.54s); that diagnostic guard was then reverted. This isolates the failing branch, not a complete fix: same-key retention, failure budgets and expiry still belong to this PR. The final deliverable contains only the test (+193 lines; production delta 0).

Required changed-surface gate passed (including agents-other test typecheck and changed-file lint, 0 warnings/errors):

node scripts/check-changed.mjs --base c6138de0df9bb658b0c73442d4a271aa21c4bb6a -- src/agents/subagents/announce/subagent-announce.requester-settle-replay.test.ts

The command used repository-pinned pnpm 12.3.4 on PATH. The intentionally failing test is not presented as green CI or merge-ready code.

The source chain is service replay → facade acceptance handling → pending delivery credit → batch retirement.

Independent P0–P2 review of the test-only deliverable completed scoped-clean, with no actionable findings. This is a review of the regression, not approval of the PR or its lifecycle policy.

Scope: this is an intentionally red regression contribution, not another functional fix or a merge-readiness verdict on this PR. #138966 already removed the old executing-turn announcement deadline; #140137/#140930 recovery/provenance are present in this main snapshot. The case uses subagent_settle and no deadline, so those repairs do not eliminate this admission-replay trigger. No old-release patch was transplanted.

Limits: source-only, in-process composition, not an installed-runtime test, full-process Gateway, real provider, or live channel run. Initial asynchronous admission is represented by the real reservation owner, not a complete first agent dispatch. Persistence callbacks are controlled; no cold restore, durable expiry, active-successor isolation, or same-key terminal recovery sequence is proved. The green terminal control supplies a synthetic transcript-final payload; it does not prove outbound delivery. Pending acceptance, a successfully delivered error/timeout notice, and a meaningful final answer remain distinct. This test does not clear the PR's broader real-behavior/expiry proof gaps.

Reproducer — add the following test file on the pinned main
import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentDedupeLifecycle } from "../../../gateway/agent-turn/agent-dedupe-lifecycle.js";
import { setGatewayDedupeEntries } from "../../../gateway/agent-turn/agent-dedupe.js";
import { createInternalAgentTurnFacade } from "../../../gateway/agent-turn/internal-facade.js";
import { createGatewayMethodRegistry } from "../../../gateway/methods/registry.js";
import { createChatRunState } from "../../../gateway/server-chat-state.js";
import type { GatewayRequestContext } from "../../../gateway/server-methods/types.js";
import { createSyntheticPluginRuntimeClient } from "../../../gateway/server-plugin-runtime-client.js";
import { getAgentEventLifecycleGeneration } from "../../../infra/agent-events.js";
import { withPluginRuntimeGatewayRequestScope } from "../../../plugins/runtime/gateway-request-scope.js";
import { trackAsyncWork } from "../../../shared/async-work-scope.js";
import type { SubagentRunRecord } from "../registry/subagent-registry.types.js";
import { setSubagentAnnounceDeliveryDepsForTest } from "./subagent-announce-delivery.runtime.js";
import { sendSubagentAnnounceDirectly } from "./subagent-announce-direct-delivery.js";
import { maybeWakeRequesterAfterAllChildrenSettled } from "./subagent-announce.requester-settle-wake.js";

const registryRead = vi.hoisted(() => ({
  hasDescendantRunAwaitingSettle: vi.fn(() => false),
  listSubagentRunsForRequester: vi.fn<() => SubagentRunRecord[]>(() => []),
  getLatestSubagentRunByChildSessionKey: vi.fn(() => undefined),
}));
const deliver = vi.hoisted(() => vi.fn());

// Keep admission preflight, turn service, dedupe and facade real. Only the
// enclosing request envelope and the registry/session fixture are substituted.
vi.mock("../../../gateway/server-methods.js", () => ({
  authorizeGatewayRequestPreDispatch: async () => ({ error: null }),
  createRequestGatewayMethodRegistry: () => ({ isControlPlaneWrite: () => false }),
  runWithGatewayRequestEnvelope: async (
    _method: string,
    _client: unknown,
    run: () => Promise<unknown>,
  ) => await run(),
}));
vi.mock("../registry/subagent-registry-read.js", () => registryRead);
vi.mock("../spawn/subagent-depth.js", () => ({ getSubagentDepthFromSessionStore: () => 0 }));
vi.mock("./subagent-announce.js", () => ({ hasUsableSessionEntry: () => true }));
vi.mock("./subagent-announce-delivery.js", () => ({
  deliverSubagentAnnouncement: (...args: unknown[]) => deliver(...args),
  loadRequesterSessionEntry: () => ({
    canonicalKey: "agent:main:main",
    entry: { sessionId: "requester-session" },
  }),
}));

const REQUESTER_KEY = "agent:main:main";
const ATTEMPT_KEY = `announce:requester-settle:main:${REQUESTER_KEY}:settled-child:yield-1`;

describe("requester settle canonical admission replay", () => {
  afterEach(() => {
    setSubagentAnnounceDeliveryDepsForTest();
    registryRead.listSubagentRunsForRequester.mockReset();
    deliver.mockReset();
  });

  it.each(["pending", "terminal"] as const)(
    "requires terminal evidence before retiring a required-visible batch: %s",
    async (phase) => {
      const methodRegistry = createGatewayMethodRegistry([]);
      const context = Object.assign({} as GatewayRequestContext, {
        trackExecution: trackAsyncWork,
        agentRunSeq: new Map(),
        broadcast: vi.fn(),
        chatAbortControllers: new Map(),
        chatRunState: createChatRunState(),
        dedupe: new Map(),
        getRuntimeConfig: () => ({}),
        getGatewayMethodRegistry: () => methodRegistry,
        logGateway: { error: vi.fn(), warn: vi.fn() },
        nodeSendToSession: vi.fn(),
        removeChatRun: vi.fn(),
      });
      context.createAgentTurnFacade = (principal) =>
        createInternalAgentTurnFacade({
          ...principal,
          getContext: () => context,
          getMethodRegistry: () => methodRegistry,
        });
      const child: SubagentRunRecord = {
        runId: "settled-child",
        childSessionKey: "agent:main:subagent:settled-child",
        requesterSessionKey: REQUESTER_KEY,
        requesterDisplayKey: "main",
        requesterAgentId: "main",
        task: "finish child work",
        cleanup: "keep",
        createdAt: 1_000,
        execution: { status: "terminal", endedAt: 3_000, outcome: { status: "ok" } },
        expectsCompletionMessage: true,
        completion: { required: true, resultText: "child result", capturedAt: 3_000 },
        delivery: { status: "delivered" },
        requesterSettleWake: {
          status: "dispatching",
          attemptCount: 1,
          batchRunIds: ["settled-child"],
          requesterYieldBatch: true,
          rearmGeneration: 1,
        },
      };
      registryRead.listSubagentRunsForRequester.mockReturnValue([child]);
      setSubagentAnnounceDeliveryDepsForTest({
        getRuntimeConfig: () => ({}),
        loadRequesterSessionEntry: () => ({
          cfg: {},
          canonicalKey: REQUESTER_KEY,
          agentId: "main",
          entry: { sessionId: "requester-session", updatedAt: 1 },
        }),
        getRequesterSessionActivity: () => ({ sessionId: "requester-session", isActive: false }),
      });
      deliver.mockImplementation(sendSubagentAnnounceDirectly);
      const keys = [`agent:${ATTEMPT_KEY}`];
      const reservation = createAgentDedupeLifecycle({
        cfg: {},
        request: { idempotencyKey: ATTEMPT_KEY, sessionKey: REQUESTER_KEY, message: "settle" },
        runId: "original-requester-run",
        lifecycleGeneration: getAgentEventLifecycleGeneration(),
        agentDedupeKeys: keys,
        suppressVisibleSessionEffects: false,
        context,
        io: { emitAcceptance: vi.fn(), emitFinal: vi.fn() },
      });
      // Model the existing handoff while asynchronous admission is outstanding.
      // The real reservation owner writes accepted + reservationId; the real
      // service must derive in_flight/admissionPending, not a mocked RPC reply.
      reservation.reserve(REQUESTER_KEY, "main");
      if (phase === "terminal") {
        // Control only: a synthetic committed transcript final, not outbound proof.
        setGatewayDedupeEntries({
          dedupe: context.dedupe,
          keys,
          entry: {
            ts: Date.now(),
            ok: true,
            payload: {
              status: "ok",
              runId: "original-requester-run",
              result: { payloads: [{ text: "consolidated requester final" }] },
            },
          },
        });
      }
      const completeBatch = vi.fn(() => {
        child.requesterSettleWake = undefined;
      });
      try {
        const settled = await withPluginRuntimeGatewayRequestScope(
          { context, client: createSyntheticPluginRuntimeClient(), isWebchatConnect: () => false },
          () =>
            maybeWakeRequesterAfterAllChildrenSettled({
              requesterSessionKey: REQUESTER_KEY,
              settledEntry: child,
              transitionBatch: (_batch, state) => {
                child.requesterSettleWake = state;
              },
              completeBatch,
            }),
        );
        expect(deliver).toHaveBeenCalledOnce();
        expect(deliver).toHaveBeenCalledWith(
          expect.objectContaining({
            directIdempotencyKey: ATTEMPT_KEY,
            sourceTool: "subagent_settle",
            requireVisibleReply: true,
          }),
        );
        if (phase === "pending") {
          expect(context.dedupe.get(keys[0]!)?.payload).toMatchObject({
            status: "accepted",
            reservationId: reservation.reservationId,
          });
          expect.soft(completeBatch).not.toHaveBeenCalled();
          expect.soft(settled).toBe(false);
          expect(child.requesterSettleWake).toBeDefined();
        } else {
          expect(settled).toBe(true);
          expect(completeBatch).toHaveBeenCalledWith(
            [child],
            1,
            expect.objectContaining({
              delivered: true,
              requesterVisibleFinalDelivered: true,
            }),
          );
          expect(child.requesterSettleWake).toBeUndefined();
        }
      } finally {
        reservation.clearUnaccepted();
        context.dedupe.clear();
      }
    },
  );
});

leilei3167 and others added 8 commits September 12, 2026 03:26
Do not credit delivery on nonterminal gateway responses
(in_flight / admission pending). Retain completion-handoff
ownership across retries and successor requester runs, keep
settle-wake attempts on the same idempotency key, and release
retention when announce/settle batches retire.

Also split oversized settle-wake tests so max-lines ratchets pass.
completion_handoff_pending is healthy in-flight Gateway work, not an
ambiguous failure. Schedule same-key observation backoffs without
incrementing replayCount or retiring via the failure budget; only
terminal evidence or the lifecycle deadline should complete the batch.
Keep completion_handoff_pending outside the failure replay budget, but
bind observations to delivery.deadlineAt or the announce hard-expiry
clock so stuck admission cannot retain the batch/handoff forever.
Literal tuple indexes avoid noUncheckedIndexedAccess on the
completion_handoff_pending observation path.
Move runAnnounceAgentCall into a sibling module and split pending
handoff settle-wake coverage into its own test file so oxlint
max-lines stays under the production/test limits.
…e batches

Add goslingmanagment's composition regression for openclaw#136820: a required-visible
requester-settle wake must keep custody while the exact-key admission
reservation is still accepted/pending, and only retire after terminal evidence.

Co-authored-by: leilei3167 <[email protected]>
- Split settle-wake helpers to stay under max-lines (640 LOC)
- Mock getLatestLiveSubagentRunByChildSessionKey in replay/outbox tests
- Fix retainedMachine locator in cloud-dispatch e2e typecheck
- Add agents-announce tsgo shard; exclude announce tests from agents-other

Co-authored-by: leilei3167 <[email protected]>
@cursor
cursor Bot force-pushed the fix/subagent-inflight-handoff-pending-credit branch from 576ddcb to db10482 Compare September 12, 2026 03:27
@leilei3167 leilei3167 closed this Sep 12, 2026
@leilei3167

Copy link
Copy Markdown
Contributor Author

Closing this PR; not pursuing it further. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Subagent completion replay credits an in-flight handoff as delivered before terminal evidence

3 participants