Skip to content

fix(agents): keep delivering reply when post-turn compaction fails - #94928

Closed
openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/94688-post-turn-compaction-delivery
Closed

openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/94688-post-turn-compaction-delivery

Conversation

@openperf

@openperf openperf commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Problem: Issue Codex/OpenAI fixed session can generate the reply successfully, then fail in post-turn compaction and surface the whole turn as UNAVAILABLE #94688 reports that in a long-lived CLI-backed (Codex/OpenAI) fixed session, the assistant reply is generated and written into the live session transcript, but the post-turn CLI compaction that runs afterwards can fail with CLI transcript compaction failed for openai/gpt-5.4: Summarization failed: Connection error.. When that happens the whole turn is surfaced as a post-turn error and channel delivery is skipped, so a user-visible success is turned into a delivery/runtime failure after the fact — the already-generated reply is discarded unless the caller separately salvages it from the transcript.
  • Root Cause: In agentCommandInternal (src/agents/agent-command.ts), the post-run try block runs three steps in order, all before the outer catch that re-throws: (1) persist the CLI turn transcript — wrapped in its own best-effort try/catch that only warns; (2) runCliTurnCompactionLifecycle — not guarded; it throws on compaction failure (CLI transcript compaction failed … / CLI native harness compaction failed …); (3) persist pendingFinalDelivery and call deliverAgentCommandResult. Because compaction sits before delivery inside the same try, a compaction throw jumps straight to the outer catch, which calls emitLifecyclePostTurnError (emitting a lifecycle error event with the compaction message) and re-throws. Delivery never runs, and the reply that already exists in result.payloads and the transcript is dropped. The transcript-persistence step immediately above is deliberately best-effort, but the compaction step that follows it is not — and post-turn compaction is pure future-turn context maintenance, with no bearing on the validity of the reply just produced. That asymmetry is the bug.
  • Fix: Make post-turn compaction best-effort relative to delivery, but only when a reply actually exists. The runCliTurnCompactionLifecycle call is wrapped in a try/catch that, on failure, checks whether the completed run produced deliverable assistant text (result.meta.finalAssistantVisibleText or a non-error payload with text). If a reply exists, it logs and continues so the reply is delivered (mirroring the transcript-persistence guard directly above). If there is no deliverable reply, the compaction error is re-thrown and stays fatal — a no-reply turn whose only signal is a compaction failure must not be reported as an empty success with an oversized/uncompacted session. On the delivered path sessionEntry keeps its pre-compaction value, which is what the lifecycle returns for a no-op anyway. The guard covers throws from every compaction engine (context-engine summarization and native harness).
  • Boundary rationale: the decision lives in the turn-lifecycle owner (agentCommandInternal), not in the compaction helper. runCliTurnCompactionLifecycle keeps its honest throw-on-failure contract; the lifecycle owner — which owns turn ordering, the already-generated reply, and delivery — is the right place to decide that post-turn maintenance is non-fatal to delivery of an existing reply while remaining fatal for an empty turn.
  • What changed:
    • src/agents/agent-command.ts — wrap the post-turn runCliTurnCompactionLifecycle call in a try/catch; warn and proceed to delivery when a deliverable reply exists, otherwise re-throw. A comment records the invariant.
    • src/agents/agent-command.compaction-rotation.test.ts — add two regression tests: (1) a compaction failure after a generated reply still delivers and the turn settles as lifecycle end (never error); (2) a compaction failure on a no-reply turn stays fatal and skips delivery.
  • What did NOT change (scope boundary):
    • The compaction lifecycle itself (runCliTurnCompactionLifecycle and the compactCliTranscript / native-harness paths) is unchanged; it still throws to signal compaction failure. Only the turn-lifecycle owner now treats that failure as non-fatal to delivery.
    • Transcript persistence, pendingFinalDelivery durability, delivery, and the rotated-successor session bookkeeping are unchanged.
    • No attempt is made to repair the underlying compaction Connection error or to change retry/rotation behavior; that is upstream/transient and out of scope.
    • Config surface unchanged (no schema, defaults, doctor migrations, or docs/reference/config).
    • Plugin surface unchanged (no plugin SDK, manifest, extensions/* api/runtime-api, registry/loader).
    • Gateway protocol unchanged.

Reproduction

  1. A long-lived CLI-backed fixed session (e.g. openai/gpt-5.4 room brain) generates an assistant reply; the reply is written into the live transcript and exists in result.payloads.
  2. OpenClaw then runs post-turn CLI compaction for that session.
  3. The compaction summarization call fails transiently (Summarization failed: Connection error.), so runCliTurnCompactionLifecycle throws CLI transcript compaction failed for openai/gpt-5.4: ….
  4. Before this PR: the throw escapes to the outer catch, which emits a lifecycle error event and re-throws; deliverAgentCommandResult never runs, so the already-generated reply is not delivered and the turn surfaces as unavailable.
  5. After this PR: the throw is caught at the compaction call site, logged as a warning, and the turn proceeds to persist the pending final delivery and deliver the reply; only context compaction (a future-turn optimization) was skipped.

Real behavior proof

Behavior addressed (#94688): when a CLI-backed turn has already generated and persisted its reply, a subsequent post-turn compaction failure no longer reclassifies the turn as failed/unavailable; the reply is delivered and only compaction is skipped.

Real environment tested (Linux, Node 22 — Vitest against the production agentCommandInternal post-run path): the real turn-lifecycle code in src/agents/agent-command.ts driving transcript persistence, the post-turn compaction call, and deliverAgentCommandResult, with runCliTurnCompactionLifecycle made to throw the exact reported error and the real delivery ordering exercised.

Exact steps or command run after this patch: pnpm test src/agents/agent-command.compaction-rotation.test.ts; pnpm tsgo:core; oxfmt --write and node scripts/run-oxlint.mjs on the two changed files.

Evidence after fix (Vitest output for the touched test file):

 Test Files  1 passed (1)
      Tests  5 passed (5)

Observed result after fix: with the post-turn compaction lifecycle throwing CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error. after a generated reply, agentCommand resolves instead of rejecting, deliverAgentCommandResult is invoked exactly once, deliverySucceeded: true, and the lifecycle settles as end (never error). For a turn with no deliverable reply, the same compaction failure is re-thrown: agentCommand rejects and delivery is never called.

What was not tested: the live gateway round-trip on the reporter's deployment with a real network Connection error during compaction. The turn-lifecycle ordering, the reply-gated delivery path, and the no-reply fatal path are covered deterministically against the production agentCommandInternal; an end-to-end gateway repro with a real transient summarization failure was not driven.

Repro confirmation: the reply-present test fails on the unpatched tree (agentCommand rejects with the exact error, delivery never reached) and passes with the fix (delivery reached). The no-reply test fails if the catch is left unconditional (the failure is swallowed into an empty success) and passes with the reply gate (failure stays fatal, no delivery). Both cover the production change.

Risk / Mitigation

  • Risk: Swallowing a compaction failure could hide a session that genuinely needs compaction, letting context keep growing. Mitigation: the soft-fail only applies when a reply was actually generated; a no-reply turn keeps the failure fatal. The failure is still logged (Post-turn CLI compaction failed … delivering reply without compaction: <error>), and compaction is retried on the next turn; the prior behavior already failed the whole turn instead of compacting, so this strictly improves delivery without removing any compaction that previously succeeded.
  • Risk: Keeping the pre-compaction sessionEntry on failure could skip a needed session-store update. Mitigation: on a compaction throw there is no successful compaction (no rotated session id, no recorded tokens) to persist; the lifecycle would have returned the same pre-compaction entry for a no-op, so no successful state is lost.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • Agents / runtime
  • Sessions / storage

Linked Issue/PR

Fixes #94688

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jun 19, 2026
@clawsweeper

clawsweeper Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 21, 2026, 11:21 PM ET / 03:21 UTC.

Summary
The PR wraps post-turn CLI compaction in agentCommandInternal with a deliverable-reply gate and adds compaction-rotation regression tests for reply-present, media-only, and no-reply failure paths.

PR surface: Source +14, Tests +136. Total +150 across 2 files.

Reproducibility: yes. Source inspection of current main shows transcript persistence succeeds, compaction is awaited, and final delivery is only reached afterwards; forcing runCliTurnCompactionLifecycle to throw reproduces the skipped-delivery path without needing live network failure.

Review metrics: 2 noteworthy metrics.

  • Failure semantics: 1 guarded catch added. The diff changes one post-turn maintenance failure from fatal to warning-only continuation when deliverable content exists.
  • Sibling candidates: 5 open sibling PRs found. Maintainers need one canonical fix path before merge to avoid duplicate or conflicting compaction semantics.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #94688
Summary: This PR is a candidate fix for the canonical post-success compaction failure issue; several sibling PRs attempt the same user-visible repair at different layers.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] Merging intentionally changes a terminal post-turn compaction failure into warning-only continuation when outbound content is deliverable, so a later turn may proceed from an uncompacted or oversized session until recovery runs again.
  • [P1] Several open sibling PRs target the same canonical issue; landing more than one could create divergent behavior across agentCommandInternal, cli-compaction, and the Codex app-server collector.
  • [P1] The PR body provides deterministic lifecycle proof but not a live forced provider/network compaction failure; maintainers may still want live proof before accepting the session-state behavior change.

Maintainer options:

  1. Land This Lifecycle Fix As Canonical (recommended)
    If maintainers accept reply-preserving soft-fail semantics, use this PR as the canonical fix and close or supersede sibling candidates after it lands.
  2. Ask For Live Failure Proof
    If deterministic lifecycle tests are not enough, require a forced live or Crabbox compaction-failure run that shows the generated reply still reaches delivery.
  3. Keep Compaction Fail-Closed
    If maintainers want every post-turn compaction failure to remain fatal, pause this PR and keep the linked issue open for a recovery or rotation design.

Next step before merge

  • No automated repair is needed; maintainers need to choose the canonical overlapping fix and explicitly accept or reject the reply-preserving compaction soft-fail semantics.

Security
Cleared: The diff changes agent runtime error handling and focused Vitest coverage only; no dependency, workflow, secret, permission, package, or supply-chain surface changed.

Review details

Best possible solution:

Land one canonical lifecycle-owner fix that preserves generated reply delivery while keeping empty/no-reply compaction failures fatal, then close or supersede the sibling candidates after merge.

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

Yes. Source inspection of current main shows transcript persistence succeeds, compaction is awaited, and final delivery is only reached afterwards; forcing runCliTurnCompactionLifecycle to throw reproduces the skipped-delivery path without needing live network failure.

Is this the best way to solve the issue?

Yes, contingent on maintainer acceptance of the behavior change. Keeping runCliTurnCompactionLifecycle fail-closed and putting the reply-preserving exception in agentCommandInternal is narrower than helper-level sibling fixes that could swallow no-reply failures.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a1828110704f.

Label changes

Label justifications:

  • P1: The PR targets a real Codex/OpenAI fixed-session workflow where an already-generated assistant reply can be hidden as unavailable after post-turn compaction fails.
  • merge-risk: 🚨 compatibility: Existing fail-closed post-turn compaction behavior becomes warning-only continuation when a deliverable reply exists.
  • merge-risk: 🚨 session-state: A delivered turn can leave context/session compaction undone until a later recovery or compaction attempt.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor proof gate does not apply to this member-authored PR; the body still includes deterministic production-lifecycle Vitest output, but not live forced provider-network failure proof.
Evidence reviewed

PR surface:

Source +14, Tests +136. Total +150 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 36 22 +14
Tests 1 138 2 +136
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 174 24 +150

What I checked:

  • Repository policy read: Root AGENTS.md and scoped src/agents/AGENTS.md were read fully; the review applied the session-state compatibility, deep PR review, and Codex-source inspection requirements. (AGENTS.md:1, a1828110704f)
  • Current main failure ordering: Current main persists the CLI transcript, then awaits runCliTurnCompactionLifecycle before pending final delivery is built, so a compaction throw can still bypass delivery after content exists. (src/agents/agent-command.ts:2223, a1828110704f)
  • Delivery happens after compaction: deliverAgentCommandResult is loaded and called only after the compaction block and pending final delivery setup, confirming the source-level reproduction path. (src/agents/agent-command.ts:2293, a1828110704f)
  • Compaction helper remains fail-closed: The current helper throws on terminal native-harness and context-engine compaction failures, so this PR keeps the helper contract intact and scopes the exception to the lifecycle owner. (src/agents/command/cli-compaction.ts:623, a1828110704f)
  • Latest release still affected: The latest release tag v2026.6.9 resolves to c645ec4555c017931de0e35ad9847dffae2741ef and still has compaction before final delivery setup. (src/agents/agent-command.ts:2218, c645ec4555c0)
  • PR head change: At PR head, the compaction call is guarded, deliverable outbound payloads allow delivery to proceed, and empty/no-reply turns rethrow the compaction error. (src/agents/agent-command.ts:2239, e85004a14428)

Likely related people:

What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 19, 2026
A CLI-backed turn persists its assistant reply to the live transcript, then
runs post-turn compaction. A compaction throw (e.g. 'CLI transcript compaction
failed: Summarization failed: Connection error.') escaped to the outer catch,
which re-threw before delivery — discarding an already-generated reply and
surfacing the turn as unavailable. Guard the post-turn compaction call: when a
deliverable reply exists, warn and continue to delivery; otherwise keep the
failure fatal so a no-reply turn is not reported as an empty success.

Fixes openclaw#94688
@openperf
openperf force-pushed the fix/94688-post-turn-compaction-delivery branch from c234de2 to e85004a Compare June 19, 2026 12:22
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jun 22, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 11, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S stale Marked as stale due to inactivity 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.

Codex/OpenAI fixed session can generate the reply successfully, then fail in post-turn compaction and surface the whole turn as UNAVAILABLE

1 participant