Skip to content

fix(agents): avoid extra finalization after a source reply is delivered - #174948

Merged
vincentkoc merged 9 commits into
mainfrom
test-code-mode-reply-refresh-32aed
Oct 17, 2026
Merged

vincentkoc merged 9 commits into
mainfrom
test-code-mode-reply-refresh-32aed

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes an unnecessary model finalization request after the message tool has already delivered the source reply.

Related: #119057

User Impact

An already-delivered reply should finish without generating another answer. Missing replies still recover, and pending delivery remains protected. No configuration, schema or protocol changes are required; this does not supersede the remaining work in the related PR.

Why This Change Was Made

Finalizer admission used the external observer's raw missing result even after canonical terminal preparation had reconciled committed message-tool delivery. It now consumes prepared.replyDeliveryState; source delivery and artifact filtering remain separate and unchanged. Eleven focused owner controls cover delivered, pending, missing and progress-only evidence, including absent observers and explicit observation conflicts.

Two composition cases exercise ordinary source-turn admission, the real reply recorder and SQLite receipt, real embedded attempt execution and deferred runner handoff, then a distinctly rebuilt message tool:

  • Confirmed delivery holds the transport acknowledgement after its effect. The old attempt must settle before rebuilding; the successor must execute and return already_delivered without another send.
  • A proven pre-dispatch refusal must clear its reservation so the successor can send once.

The provider stream, transport, prepared runtime/plugin catalogs and auth are scripted fixture inputs. Harness selection, context-engine ownership, prepared tool authority, subscription, transcript persistence, finalization, Code Mode, delivery receipts and tool disposal remain real. Uncertain delivery outcomes, restart recovery and live channel/plugin installation are outside this test.

Evidence

  • Repaired candidate: f0eb0bb996d974b3f895f048e937da7f6c9fe9e6, tree 997e3ae5a2336aebf7cfb596b89af57ac86144be. It preserves prior signed history and merges only the already-tested main input 5b7749ae5bdbefbdb9cbc58778c20e3f8a181625, placing the fix in the extracted canonical helper. The two-attempt assertion is unchanged; no fixture delivery observer or extra-attempt allowance masks the failure.
  • Repaired CI 38998473168 succeeded: 40 successful jobs, 26 intentional skips, no failures. It executed merge 849b20dd4c3ef6f9fbd20d2d1cbe9c609ed92ae3 with main parent 7d3a763f92e2febeeacd943597673600b4bb17c3. Both real composition cases passed in job 117296468336, including the unchanged strict two-attempt and receipt/effect/drain assertions; all 11 new owner controls passed in job 117296468266, alongside existing finalization controls. Generation cleanup and shard exit 0 were verified. Production/test types, selected lint and ratchets passed. An independent reviewer consumed the actual retained case records, not just aggregate status.
  • Relevant before/after source comparison found no changes to finalizer admission, terminal preparation, observer, refresh or message execution contracts in the CI base drift; unrelated automatic-media helper removals did not affect these no-media fixtures. This is scoped regression evidence across explicitly identified merge inputs, not a globally matched benchmark. Both repaired cases assert two successful attempts, distinct rebuilt-tool execution, one physical effect and a delivered terminal receipt. Refusal asserts two transport calls; confirmed delivery asserts one and a successor already_delivered result. Post-fix scripted provider-call counts and operation identities were not emitted on passing tests and remain unreported rather than inferred.
  • Determining failure: CI 38997238376 at head 8aa3a96bb934ef4fde4377c69e138fda665e175e, merge 83ec4c138a1e89159ee0df37a224c0b03e748dd2, main parent 5b7749ae5bdbefbdb9cbc58778c20e3f8a181625. Confirmed delivery passed. Refusal passed distinct rebuilt-tool execution after old-attempt drain, cleared reservation, one physical effect, committed delivered-terminal receipt, one original user message and drained Code Mode runtime; it then failed solely at three successful attempts versus two. Immutable successor facts already recorded final source delivery. The third operation was tools-disabled settled-tool-finalization, not a repeated send. Refusal accounting: 4 scripted provider calls, 2 message-tool calls on distinct instances, 2 transport calls and 1 physical effect. Production/test types, selected lint and ratchets passed. These are deterministic fixture counts, not a live-model benchmark.
  • Fresh scoped autoreview of the owner repair found no actionable P0-P2 findings. Independent review additionally corrected the progress-only controls to omit explicit delivery state, so they exercise marker-only authority, and verified the resolved canonical-helper merge. Current-head ClawSweeper review reports no findings and no before-merge actions; its scripted-proof/live-entry-point limitation remains disclosed.
  • Independent source review completed. Autoreview identified the Vitest 5 iteration-context mismatch; the test now uses the inspected it.for contract, with incremental review of the correction.
  • Initial focused native run: https://github.com/openclaw/openclaw/actions/runs/38991352344. Both cases failed before transport because the standalone fixture omitted the session MCP scheduler binding. The fixture now uses the canonical test scheduler and disposes MCP runtimes before state cleanup; this correction passed independent review.
  • The corrected focused attempt was stopped while queued, per the native capacity policy; no test ran in that attempt.
  • PR CI at 040ce3a7: https://github.com/openclaw/openclaw/actions/runs/38992225698. Both cases failed before transport because the fast provider mock omitted an export consumed by the real attempt. Production/test types and general/core/plugin lint passed. The correction restored the real provider runtime, provider handles and runtime-plan builder locally, and preserved the plugin-tools module exports.
  • PR CI at 902d1c07: https://github.com/openclaw/openclaw/actions/runs/38993038026. Both cases again failed before transport, at the fast context-engine registry mock. A complete review of the active base/fast mock graph also found that mocked harness selection bypassed logical-turn initialization and prepared tool authority. The coherent correction restored context initialization, registry and harness selection together, retaining the real-attempt observer. Independent review verified the exact correction and unchanged assertions/cleanup.
  • PR CI at 2988497fff8d: https://github.com/openclaw/openclaw/actions/runs/38993812435. Both cases resolved before the parked-refresh gate; the helper did not expose the returned semantic result. Production/test types and general/core/plugin lint passed. The independently reviewed diagnostic correction preserved original rejections, expectations, timeouts and cleanup.
  • Diagnostic CI at 1e2602170842: https://github.com/openclaw/openclaw/actions/runs/38994648295. Both cases failed with normal ok/stop settlement: one real message invocation and transport call, but the scripted provider selected final instead of waiting. The real provider boundary strips private tool-result details and may append runtime context after a result. The corrected fixture matches the prior call ID and parses its visible JSON control; only a successful waiting result with its returned top-level run ID permits wait, and only completed prior work permits a new-generation exec. Production/test types and general/plugin lint passed; core lint found an unsafe diagnostic string coercion, now limited to Error/string values. Independent review accepted the exact correction.
  • CI at 89f5c6057f0b: https://github.com/openclaw/openclaw/actions/runs/38995717965 tested merge 9b2f652f26e99879d713f2fd9c11c9994030fa7a with main parent 9dd47e67ded4986aabe211c62b5c26fc9eec0299. Both cases failed at the strict result-ID assertion before deferred refresh parked. Source inspection confirmed that the Responses normalizer rewrites the fixture's invalid call- IDs in both assistant calls and tool results. The correction emits valid call_ IDs and also requires the matching provider-visible assistant call ID/name before the existing exact result/control checks. Independent review accepted the exact correction; production/test types and selected lint passed on that prior input.
  • CI at a9bf3fcbaa8b: https://github.com/openclaw/openclaw/actions/runs/38996416401 tested merge 3a8f7918785a1998ca7d53f76a1cd5b610107dac with main parent a5959e02d46c5551bc2dc4bc92f7e459c99741a8. The confirmed-delivery composition passed, including the rebuilt tool's already_delivered result and exactly one effect. The refusal case returned without a semantic error but failed at three successful attempts versus the expected two; later receipt/effect checks did not execute. Production/test types, selected lint and ratchets passed. The subsequent independently reviewed diagnostic-only update recorded actual invocation operation/tool restriction and immutable return facts, and moved unchanged domain assertions before the unchanged attempt-count assertion; its determining evidence is recorded above.
  • Earlier CI runs flagged an unrelated update-command-service-maintenance-native.test-support.ts mock-export violation in their merge inputs. The ratchet passed on the 89f5c6057f0b merge input; this PR did not change that fixture or waive its check.
  • The earlier native checkout-provisioning disk hold cleared after available capacity changed. Native review initialization succeeded for this exact head; preparation and merge still require their own guarded admission. No unrelated cleanup or gate override was used.
  • Native reuse qualification of the task-owned dependency donor refused its workspace-source link. No install or manual link was performed in the source checkout; normal PR CI is the corrected proof route.
  • Pinned formatting, native commit content guard and git diff --check passed. Main-relative production delta: +3/-2 (net +1, including two invariant-comment lines); tests and registration: +666. No build/package/import boundary changed.

Focused files: src/agents/embedded-agent-runner/run.plugin-runtime-refresh-delivery.integration.test.ts and src/agents/embedded-agent-runner/run/settled-turn-finalization.test.ts, plus existing selected finalization/delivery siblings. Normal exact-head PR CI is the admitted execution route.

@vincentkoc vincentkoc self-assigned this Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 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: M labels Oct 17, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review October 17, 2026 01:45
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper clawsweeper Bot removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR uses reconciled reply-delivery state to avoid an unnecessary finalization request after a source reply is delivered.

Example: A rebuilt message tool sends “The result.” to refreshchat conversation C123 after a pre-dispatch refusal.

  • Before: The runner records successful delivery but an absent observer reports missing, allowing a third, tools-disabled finalization attempt.
  • After: Finalizer admission consumes the reconciled delivered state and finishes after the two ordinary attempts.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused owner repair is coherent and has no actionable findings; available behavioral evidence is limited to fixture-backed composition and CI job results.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its real-runner composition uses scripted provider and transport inputs, with successful exact-head changed-test jobs but no independently inspected shipped-entry-point demonstration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An agent can make another model request after its message tool has already delivered the source reply.
Reason: The maintainer-authored repair restores agreement between existing delivery preparation and finalizer admission without adding configuration or changing delivery policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current-main mismatch between recorded delivery and finalizer admission. The production repair resolves the prior finding without weakening the two-attempt assertion; no actionable introduced defect was found.

Priority: P2
Reviewed head: f0eb0bb996d974b3f895f048e937da7f6c9fe9e6

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No supplied shipped Gateway or CLI trace demonstrates the repaired delivered-reply path; detailed CI logs were inaccessible, so the repaired per-scenario results were not independently verified.
Agent review details

How this fits together

The embedded runner combines attempt delivery facts and optional delivery observations before deciding whether a settled tool turn needs a final model answer.

flowchart TD
  A[Settled embedded attempt] --> C[Canonical terminal preparation]
  B[Optional delivery observer] --> C
  C --> D[Reconciled delivery state]
  D --> E[Finalizer admission]
  E --> F[Finish delivered or pending turn]
  E --> G[Recover missing answer]
Loading

Technical review

Best possible solution:

Use canonical prepared delivery state for finalizer admission while preserving missing-reply recovery and separate source-artifact custody.

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

Current main exposes the path directly: absent observation resolves to missing, terminal preparation reconciles delivered attempt evidence, but finalizer admission still consumes the raw missing value; no target code was executed during review.

Is this the best way to solve the issue?

The repair belongs at the existing shared admission owner and reuses its canonical prepared fact, avoiding a second delivery policy or relaxed regression assertion.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 86ad4c4ec0bd.

Provenance checked

  • Shared settled-turn finalizer admission keeps the original intent (acd2763: The helper extraction let core decide whether finalization needs context before requesting expensive harness capture.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit acd2763 adds src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:109 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: acd27635ccdc; files: src/agents/embedded-agent-runner/run/settled-turn-finalization.ts)
  • Vincent Koc: Raw commit f6f939a adds src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:291 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f6f939a8ebc6; files: src/agents/embedded-agent-runner/run/settled-turn-finalization.ts)

PR surface

Source +1, Tests +666. Total +667 across 4 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 3 2 +1
Tests 3 666 0 +666
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 669 2 +667

Review metrics

Metric Value Why it matters
Production versus test growth Production +3/-2; tests +665/-0 The larger test addition covers distinct receipt persistence, deferred refresh, old-attempt settlement, and rebuilt-tool behavior that helper controls alone cannot establish.

Labels

Label changes:

  • add P2: An unnecessary model request after successful delivery adds avoidable latency and provider work in a bounded agent workflow.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove P3: Current review triage priority is P2, so this older priority label is no longer current.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: An unnecessary model request after successful delivery adds avoidable latency and provider work in a bounded agent workflow.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-17T03:18:05.531Z sha 8aa3a96 :: needs changes before merge. :: [P2] [P2] Separate refresh attempts from isolated finalization

Reviewed October 16, 2026, 11:29 PM ET / October 17, 2026, 03:29 UTC (Revision 2).

@vincentkoc vincentkoc changed the title chore(agents): cover source reply receipts across deferred refresh fix(agents): avoid extra finalization after a source reply is delivered Oct 17, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Please review current head f0eb0bb996d974b3f895f048e937da7f6c9fe9e6, including the production finalizer-admission repair and its 11 owner controls.

Disposition of the prior-head finding: the third finalizer is supported when delivery is genuinely missing, but the captured successor already returned sourceReplyDeliveryState: delivered and replyOperation.sourceReplyDelivered: true. Canonical terminal preparation reconciles that custody before payload construction; finalizer admission incorrectly consumed the raw optional observer's missing value instead. The fix uses prepared.replyDeliveryState in the extracted owner and leaves source/artifact filtering unchanged. Allowing an optional third attempt would conceal this demonstrated mismatch, so the strict two-attempt assertion is retained. Missing and progress-only delivery still qualify for finalization; pending delivery does not.

Fresh exact-head CI is running. No repaired runtime pass or landing clearance is claimed yet.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@vincentkoc
vincentkoc merged commit 6598571 into main Oct 17, 2026
161 of 163 checks passed
@vincentkoc
vincentkoc deleted the test-code-mode-reply-refresh-32aed branch October 17, 2026 03:39
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…ed (openclaw#174948)

* chore(agents): cover source reply receipts across deferred refresh

* chore(agents): preserve real provider owners in refresh fixture

* chore(agents): restore real refresh fixture lifecycle owners

* chore(agents): expose early refresh fixture settlement

* chore(agents): follow visible refresh fixture controls

* chore(agents): use stable Responses fixture call IDs

* chore(agents): expose refresh attempt ownership in assertions

* fix(agents): avoid finalizing an already delivered source reply
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant