Skip to content

fix(sessions): keep conversations usable after delegated recovery fails - #176087

Closed
enki wants to merge 3 commits into
openclaw:mainfrom
enki:fix/retire-unrecoverable-delegated-turn
Closed

enki wants to merge 3 commits into
openclaw:mainfrom
enki:fix/retire-unrecoverable-delegated-turn

Conversation

@enki

@enki enki commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes a Gateway restart permanently blocking a conversation when its interrupted turn came from another session and the sender's authority cannot be restored.

User Impact

When no reply, harness completion, or independent run remains owed, recovery ends only the old input. The session keeps its identity, transcript and working context and accepts a fresh authenticated message. Recovery never replays the delegated request or claims that its result was delivered. There is no schema or configuration change.

Why This Change Was Made

Reuse the guarded, atomic interruption settlement introduced for unrestorable requester inputs in #174177. Record one local notice and terminal source/run identities, including a source-only claim whose operational delivery ID has already been cleared. Later startup must not turn that settled interruption back into recoverable work.

Pending final delivery, owed harness completion and independent unretired run fences retain their existing owners and blocking behavior. Exhausted attempts and message-tool-only authority failures retain their explicit recovery path. Existing tombstones are not automatically cleared. This deliberately narrows whole-session tombstoning only for an interrupted input without remaining custody; maintainer security review is requested for that policy change.

Related: #161719. Builds on merged #173579's explicit in-place Resume; it does not duplicate that API or restore old sender authority. #173747 explicitly leaves this delegated-authority gap unresolved. The separate archived-Main reset remedy is #176086.

The unchanged pending-final action classifier moves to its existing delivery module so the coordinator stays within its strict file limit; no lint rule is suppressed.

Behavior decision

The review asks whether an unrestorable delegated input may retire without disabling its conversation. I recommend conditional retirement once no other work or delivery obligation remains. Losing authority for the interrupted request should keep that request inert; it need not prevent an independently authenticated future request.

#150702 deliberately prohibits delegated dispatch after sender authority is lost. This patch preserves that prohibition: no replay, synthesized sender authority, or System-authorized followup. #174177 supplies the precedent for retiring an unrestorable input while preserving its conversation.

The custody checks keep existing blocking when a final, harness completion, or independent unretired execution remains. Otherwise the existing guarded transaction records one local interruption and terminal identities. New work still requires fresh authentication. The remaining owner choice is requiring manual session recovery even after conclusive non-executing settlement. Earlier settlement precedent supports this extension; it does not already approve the delegated-input case.

Current upstream conflict repair

Refreshed head cabf35a82b6be78d46adcb442629a206dfa5b029 merges the prior PR head with pinned upstream 00575becc9fce53efc73b319a16fa71e6f4123b9, preserving both parent histories. Conflict resolution uses upstream's extracted completion-checkpoint owner and the PR's shared pending-delivery classifier. It removes duplicate retired helpers and migrates fresh authenticated follow-up coverage to current controller admission. A small test-target helper extraction keeps the merged shutdown suite within its existing line limit, preserving store incarnation and configured agent identity.

Fresh checks pass: all four selected startup/delivery/native/shutdown suites (222 tests across three canonical shards; 222.92 seconds), production core types, owner Gateway-server and agents-sessions test types, scoped typed lint, formatting, and whitespace. After the fixture extraction, the complete shutdown suite passed again (27 tests; 11.20 seconds wrapper wall), with owner test types and scoped lint. Independent P0–P2 review found no actionable issue in the full PR diff, including the helper extraction; a subsequent local expression hoist is behavior-preserving. Unprovided unchanged upstream dependencies and actual runtime execution were outside independent review coverage.

New-head CI passed on this refreshed head. Prior Gateway/native recovery captures retain their original source qualifications and are not new runtime captures on this merged head. Pending final delivery, harness completion, and independent recovery obligations remain guards against early settlement. No delegated authority is recreated; the behavior decision above remains for maintainer review.

Evidence

Synthetic production-owner regression: actual shutdown marking → recovery's SQLite notice/settlement → next startup → visible-turn admission in the same canonical Main session. Before the fix, the delegated case produces a session-wide tombstone. Afterward, no delegated dispatch occurs, one notice remains, source/run IDs are terminal without delivery evidence, the next startup does not replay it, and a fresh visible turn is admitted without reset or identity rotation. A source-only variant separately reproduced next-startup resurrection before its terminal identity was preserved.

Current revision and regression checks

Current head b66816d9c9199c8f12cd73949a36e8f7c6642740 records a cycle-derived terminal bookkeeping identity when neither saved run ID exists. Second-startup marking no longer rediscovers that settled input. Existing source/operational IDs retain their semantics; the fallback receipt grants no execution authority and requires no schema change.

The two failing native controls now assert interrupted settlement and terminal receipts while retaining no-startTurn and zero-automation-effect checks. 191 recovery/native cases pass (179 recovery-owner and 12 native controls). The no-ID second-startup regression failed before this repair. Core production types, focused changed-test types, scoped typed lint, formatting, diff checks, and fresh complete-candidate independent P0–P2 review pass. The canonical runtime build passes on this exact commit. Current-head broad CI remains separate.

Captured real Gateway and latest-stable upgrade evidence

Runtime proof on candidate b66816d9: official latest-stable 2026.10.4 CLI wrote synthetic history, followed by the unchanged stable shutdown marker on an offline delegated claim lacking surviving authority and saved run IDs. Candidate Doctor/startup preserved the exact history and physical session, settled it as interrupted without a tombstone, and did not replay the old input. A fresh authenticated turn then traversed the real Gateway, OpenAI SDK loopback transport, and actual filesystem read tool to a correlated final reply (two HTTP requests).

Captured real agent.wait after an authenticated reset at the prepared-effect boundary returned status: error, Error: Chat admission ended or was cancelled; submit a new turn. No additional provider/tool I/O occurred. The test-only pause retained the unchanged production guard. Actual Gateway logs capture the read-only rejection (FORBIDDEN, missing scope: operator.write) and invalid-token handshake rejection (failurePhase: auth, failureCause: unauthorized, reason: token_mismatch) before I/O. Provider responses were scripted; this is not an external-provider or live-outage claim. Gateway/provider cleanup completed.

The captured terminal result and selected saved RPC/log observations are below. Identifiers/messages belong only to disposable synthetic fixtures; no operator Gateway, private conversations, credentials, or external model provider were used. Comparison booleans are harness assertions against the full saved objects; error strings are copied from the actual Gateway/agent responses. The latest-stable fixture qualification is explicit rather than claiming an actual provider turn was killed in the first process.

{
  "schema": 1,
  "candidate": "b66816d9c9199c8f12cd73949a36e8f7c6642740",
  "capturedTerminalOutput": {
    "syntheticOnly": true,
    "head": "b66816d9c9199c8f12cd73949a36e8f7c6642740",
    "stableVersion": "2026.10.4",
    "transport": "Real Gateway + authenticated WebSocket RPC + loopback HTTP/OpenAI SDK; provider wire responses scripted; real read-tool filesystem I/O",
    "externalProviderContacted": false,
    "stableGatewayReady": true,
    "stableOfficialCliWroteHistory": true,
    "stableGatewayStopped": true,
    "stableShutdownMarkerApplied": true,
    "candidateDoctorSucceeded": true,
    "candidateGatewayReady": true,
    "authenticatedOwner": true,
    "stableIdentityAndExactHistoryRetained": true,
    "oldUnownedDelegatedInputNotReplayed": true,
    "recoverySettledWithoutSessionTombstone": true,
    "readonlyCallerRejectedBeforeIo": true,
    "unauthenticatedCallerRejectedBeforeIo": true,
    "actualProviderReadToolOffered": true,
    "actualReadReceiptReachedNextProviderRequest": true,
    "freshAuthenticatedTurnProviderFinal": true,
    "actualPreparedOwnerReassigned": true,
    "stalePreparedInputRejectedBeforeProviderOrToolIo": true,
    "passed": true,
    "gatewayStopped": true,
    "providerStopped": true,
    "fixtureRemoved": true,
    "providerRequests": 2
  },
  "actualRpcReadbacks": {
    "sessions.describe": {
      "archived": false,
      "status": "interrupted",
      "activeRunIds": []
    },
    "chat.history": {
      "samePhysicalSessionId": true,
      "retainedOriginalMessagesExactly": true,
      "recoveryNotice": [
        {
          "type": "text",
          "text": "This interrupted turn could not resume after the Gateway restarted: delegated recovery sender authority is unavailable. Your session and transcript are preserved. Send a new authenticated message to continue."
        }
      ],
      "providerFinal": {
        "role": "assistant",
        "stopReason": "stop",
        "content": [
          {
            "type": "text",
            "text": "SYNTHETIC_MAIN_RESET_USABLE_8429"
          }
        ]
      }
    },
    "agent.waitAfterActualReset": {
      "status": "error",
      "error": "Error: Chat admission ended or was cancelled; submit a new turn."
    }
  },
  "observer": {
    "ownerLoaded": true,
    "guardAnchorCount": 1
  },
  "qualifications": [
    "Official latest stable 2026.10.4 CLI created synthetic history. Its unchanged canonical shutdown marker then marked an offline synthetic delegated claim with no surviving source authority and no saved run IDs; this was not an actual provider turn interrupted in the first process. Candidate Doctor/startup loaded and settled that persisted state.",
    "Actual SDK HTTP transport and filesystem read tool were exercised. Provider wire responses were scripted on loopback; no external provider was contacted.",
    "A test-only loader paused the prepared synthetic request immediately before the unchanged production admission-currentness assertion. Actual authenticated sessions.reset aborted that admission; the original assertion rejected before provider/tool I/O.",
    "Client exception objects were not serialized; actual Gateway log records capture the read-only chat.send FORBIDDEN/missing operator.write error and unauthorized/token_mismatch handshake rejection. Only those error fields are reproduced."
  ],
  "capturedGatewayNegativeErrors": {
    "chat.send": {
      "errorCode": "FORBIDDEN",
      "errorMessage": "missing scope: operator.write"
    },
    "connect": {
      "failurePhase": "auth",
      "failureCause": "unauthorized",
      "reason": "token_mismatch"
    }
  }
}

The recovery admission policy and final-effect evidence still require maintainer security review; no owner approval is claimed.

@clawsweeper

clawsweeper Bot commented Oct 18, 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.

@enki
enki marked this pull request as ready for review October 18, 2026 05:20
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 18, 2026
@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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and 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 18, 2026
@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR retires an unrestorable delegated input without blocking its conversation when no execution, completion, or delivery custody remains.

Example: A delegated turn in agent:main:main is interrupted by a Gateway restart and its sender authority cannot be restored.

  • Before: Recovery tombstones the entire session, preventing subsequent messages.
  • After: With no remaining custody, recovery records one local interruption notice and terminal receipt, preserving the session for a fresh authenticated message.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The supplied runtime and upgrade evidence resolves the previous proof gaps, and both prior findings are fixed; readiness remains capped by the unresolved recovery-policy decision.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Captured exact-head evidence exercises candidate Doctor/startup settlement, preserved session identity and history, and a fresh authenticated Gateway request through SDK HTTP and a real filesystem read tool; old delegated work remains inert, unauthorized callers are rejected, and an authenticated reset invalidates prepared admission before further I/O. Responses were scripted on loopback, and the latest-stable delegated claim was constructed offline rather than interrupted during a provider turn.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A restart during delegated work can prevent the conversation from accepting any later message.
Reason: The user benefit is concrete, but changing the area owner's intentional terminal outcome requires an explicit recovery-policy decision.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: it addresses a current session lockout and resolves both prior findings, but its change to the intentional recovery policy still needs owner approval.

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

Decision needed

  • Question: May delegated recovery retire only the interrupted input when no delivery, completion, or independent execution custody remains, allowing a fresh authenticated turn in the same session?
  • Recommendation: Approve conditional turn retirement: Accept the narrow settlement while preserving delegated no-replay, remaining custody, and fresh-turn authorization.
  • Why: The prior security policy intentionally retained whole-session blocking, and no recorded owner approval extends requester-only settlement to this delegated-input case.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

Gateway restart recovery reads persisted session claims, transcript provenance, and delivery ownership, then settles interrupted work or dispatches an authorized continuation.

flowchart TD
  A[Gateway restart] --> B[Persisted session claims]
  B --> C[Recovery coordinator]
  C --> D[Source and custody checks]
  D --> E[Atomic interruption settlement]
  D --> F[Existing custody owner]
  E --> G[Fresh authenticated turn]
Loading

Technical review

Best possible solution:

Reuse the existing atomic interruption settlement for inputs without remaining custody, preserving the conversation and requiring current Gateway authorization for subsequent work.

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

Current-main source and registered recovery controls establish the tombstone path, corroborated by official-release field and lab reports; this read-only review did not execute a reproduction.

Is this the best way to solve the issue?

The implementation reuses the existing settlement owner, preserves distinct custody, and fixes startup rediscovery without new storage machinery; its deliberate policy change requires owner acceptance.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 173962bdc5bc.

Provenance checked

  • Delegated-source refusal and whole-session tombstoning changes intended behavior with a stated reason (6b5fb4b: Prevent delegated requests and unverified internal inputs from executing or dispatching without surviving sender authority, accepting a continuity tradeoff.)
  • Atomic local interruption settlement keeps the original intent (ce9d859: Settle definitively unrestorable requester inputs once while preserving their session, transcript, and captured results for fresh authenticated work.)
  • Pending-final classifier relocation keeps the original intent (71382da: Batch delivery-owner checks through the existing worker while retaining custody precedence and settlement semantics; the PR moves this classifier unchanged.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit ce9d859 adds src/agents/main-session-recovery/main-session-restart-recovery-failure.ts:56 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ce9d859d68ab; files: src/agents/main-session-recovery/main-session-restart-recovery-failure.ts)

PR surface

Source +65, Tests +89, Docs +11. Total +165 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 107 42 +65
Tests 3 114 25 +89
Docs 2 18 7 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 239 74 +165

Root-cause cluster

Relationship: same_root_cause
Canonical: #161719
Summary: This PR addresses the canonical delegated-input tombstone problem; saved-input recovery and repair of already archived sessions are adjacent work.

Members:

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 security-boundary.
  • remove status: 📣 needs proof: Current PR status no longer selects a status label.

Label justifications:

  • P1: Release reports establish restart-triggered session lockouts that reject subsequent messages, heartbeats, and scheduled work.
  • merge-risk: 🚨 security-boundary: The patch replaces an intentional session-wide refusal after delegated authority loss with eligibility for a fresh authenticated turn.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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-18T05:38:59.554Z sha 821cbe3 :: needs real behavior proof before merge. :: [P2] Preserve a terminal identity when both saved run IDs are absent | [P2] Update the native recovery controls for the new settlement outcome

Reviewed October 18, 2026, 2:33 AM ET / 06:33 UTC (Revision 2).

@enki

enki commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Published b66816d9c919: fixes no-ID second-startup resurrection and the two failing native controls, preserving authority/no-effect assertions. All 191 recovery/native cases, targeted types/lint/format, fresh full P0–P2 review and exact-commit runtime build pass.

The body now embeds captured results from official latest-stable CLI state → stopped-state shutdown marker → candidate Doctor/startup → fresh authenticated Gateway/SDK/read-tool final. It also includes actual FORBIDDEN/token-mismatch errors and the stale prepared-input rejection after canonical reset, with no extra provider/tool I/O. Provider wire responses are scripted; the offline legacy-claim setup and source pin are explicit. All state is synthetic; no operator Gateway was changed.

@steipete — please review the narrow per-input settlement policy and final-effect evidence. Pending delivery/completion/independent execution custody still retains its existing blocking owner; old delegated authority is never restored. Maintainer security/policy approval remains required.

@clawsweeper

clawsweeper Bot commented Oct 18, 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-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Oct 18, 2026
@enki

enki commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

Response to the behavior decision in the current review.

The body now answers the delegated-recovery question against #150702 and #174177. The recommendation retires only the unauthorized old input, without replay or replacement authority, and retains blocking while other execution/delivery custody remains. Fresh work still requires independent authentication; the policy extension is explicit.

Source-linked rationale and remaining choice.

@steipete

Copy link
Copy Markdown
Contributor

Thank you, @enki. Your design and credit are retained in the maintainer rewrite #176682, rebased onto the session-controller cutover. The rewrite route was used because the tooling cannot refresh unsigned incoming heads. Leaving this PR open for the lead's landing/closure decision.

@steipete

Copy link
Copy Markdown
Contributor

Thank you @enki — this landed as #176682 (squash d6ec4c7), a maintainer rewrite of your change onto current main after the session-controller cutover, with you as co-author on the commit. It keeps your design: an interrupted input whose delegated sender can't be restored is retired with one local notice only when no other delivery, harness completion, or run is still owed. The rewrite also clears stale processing state when the controller retires and stops generic restart recovery from replaying started cron occurrences. Closing this one as landed via #176682.

@steipete steipete closed this Oct 19, 2026
@enki

enki commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Conflicts are resolved at cabf35a82b6be78d46adcb442629a206dfa5b029 against pinned upstream 00575becc9fce53efc73b319a16fa71e6f4123b9. New-head CI passed. The PR body records fresh focused tests, owning typechecks, lint and independent review, with older runtime evidence kept source-qualified. Please reassess the current integration and the explicit Behavior decision argument. This is a recommendation backed by code and evidence; it does not claim maintainer approval.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper could not start a re-review for this item.
Reason: re-review requires an open issue or PR.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants