Repository navigation
fix(subagents): keep in-flight announce handoffs retryable - #136820
leilei3167 wants to merge 8 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@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. |
|
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 reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherSubagent 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]
Decision needed
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
Findings
Agent review detailsSecurityNone. PR surfaceSource +310, Tests +1214. Total +1524 across 20 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 41861b8055af. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (23 earlier review cycles; latest 8 shown)
|
9d3acb8 to
9ca094a
Compare
706c367 to
dad3692
Compare
#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]>
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]>
Current-main regression: canonical admission replay retires a required-visible settle batchThis adds a runnable composition case to #136820, beyond the historical release/deadline evidence already posted on #136513. Source baseline: New proof: the fixture does not mock an 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.tsOn unchanged main production: 1 failed / 1 passed. In the pending case the reservation remains 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.tsThe 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 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 mainimport { 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();
}
},
);
}); |
7359f30 to
6bd6b32
Compare
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]>
… main rebase 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]>
576ddcb to
db10482
Compare
|
Closing this PR; not pursuing it further. Thanks. |
What Problem This Solves
Fixes #136513
A duplicate subagent completion handoff using the same idempotency key can get
status: "in_flight"(withadmissionPending) 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
completion_handoff_pending,terminal: true) so custody stays open and same-attempt media fallback stays suppressed.terminalon the completion direct-primary dispatch branch so a retryable pending result does not fall through to steer fallback.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.clearSubagentPendingDeliveryandsuspendPendingFinalDelivery).import/firstinsubagent-announce-direct-delivery.ts(file comment + all imports before re-exports).completion_handoff_pendingout of the settle-wake failure replay budget: schedule same-key observation backoffs without spendingreplayCount/completeBatchon the third pending observation.delivery.deadlineAtwhen present, otherwise the announce hard-expiry clock (ANNOUNCE_COMPLETION_HARD_EXPIRY_MS); past expiry retires viacompleteBatch(requester settle wake expired) and releases the handoff identity.Evidence
Pending settle-wake fix (tip
9dd9517792b):completion_handoff_pendingstays outsidescheduleSameKeyReplay/ failure budget. Same attempt key observes on 30s then 120s backoffs without incrementingreplayCount. Pending observations now persistdeadlineAtfromdelivery.deadlineAt(min across the batch) ornow + ANNOUNCE_COMPLETION_HARD_EXPIRY_MS; past that boundcompleteBatchwithrequester settle wake expiredclears 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).