Skip to content

[Bug] Restart recovery resumes a completed 70-day-old conversation after the run-outcome refactor #166300

Open

Description

@hannesrudolph

Bug type

Regression (worked before, now fails)

Beta release blocker

No

Summary

After an update from 2026.9.7 to 2026.9.8, startup recovery automatically resumed a conversation whose last human turn and final assistant reply were over 70 days old. The pre-update row retained a legacy failed outcome and an unmatched recovery-run fence. The new claim-based discovery and observation logic promoted that residue into a fresh recovery cycle, and the transcript policy did not stop dispatch despite a final assistant message at the tail.

This was a real production activation, not just a sidebar showing stale Working state. The agent read an external service again and sent a new reply to the old Telegram topic without new user input.

OpenClaw version

  • Previous deployed build — 2026.9.7 at 9d2ebf6
  • Affected deployed build — 2026.9.8 at 10334ec
  • Narrow A/B parent — df73bb1
  • Triggering change — PR #165733, merged 2026-10-06T17:54:36Z
  • Latest upstream checked — c39d9b0. The recovery directory and restart-recovery-state module are unchanged from the affected build at that revision.

Operating system

macOS 27.0 arm64, Node 26.7.0

Install method

Managed Git-source installation, LaunchAgent-supervised Gateway, SQLite-backed per-agent sessions. The update was run through the normal managed update path. No Gateway restart or production state edit was performed during this investigation.

Model

Model identity omitted. The defect is in pre-model recovery admission. The deterministic reproduction performs no model calls.

Provider / routing chain

Original July conversation used the native Codex runtime and its canonical transcript mirror. October recovery dispatched through the current OpenAI-backed default runtime, then delivered to the original Telegram topic. The conversation was also visible through Control UI.

Additional provider/model setup details

The original final message has stopReason=stop and __openclaw.mirrorOrigin=codex-app-server. The resume-policy probe below returns resume with forceRestartSafeTools=false both with and without the fullAccess argument. No provider failure is required to reproduce the admission change.

Steps to reproduce

Observed production sequence

  1. Retain a legacy main-session row with the state shown below and a canonical transcript ending in a final assistant reply.
  2. Leave the conversation untouched. In this incident, the last human interaction was 2026-07-28T02:10:10.948Z and the final assistant reply was 2026-07-28T02:10:58.661Z, both still July 27 in the user's timezone.
  3. Update and restart from the previous deployed build to the affected build.
  4. Startup recovery selects the retained run fence, appends an internal main_session_restart_recovery input, launches a new model turn, and sends to the original topic.

Minimal deterministic state-boundary reproduction

Save the following as proof.ts in each prepared source checkout and run pnpm exec tsx proof.ts with OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH pointed at private test-only paths. Use the production transitionMainSessionRecovery export from src/agents/main-session-recovery/main-session-recovery-state.ts. Supply the same synthetic fixture to each pinned revision. No production database is required.

import { transitionMainSessionRecovery } from "./src/agents/main-session-recovery/main-session-recovery-state.js";

const entry = {
  sessionId: "synthetic-session",
  updatedAt: 1785261520638,
  lastInteractionAt: 1785204610948,
  startedAt: 1785204611567,
  endedAt: 1785212469570,
  status: "failed",
  abortedLastRun: true,
  restartRecoveryRuns: [{
    runId: "synthetic-old-run",
    lifecycleGeneration: "synthetic-old-generation"
  }],
  restartRecoveryTerminalRunIds: ["synthetic-channel-source"]
};
const result = transitionMainSessionRecovery(entry, {
  kind: "observe",
  cycleId: "synthetic-current-cycle",
  lifecycleGeneration: "synthetic-current-generation",
  sessionKey: "agent:main:main"
});
console.log(result, entry.mainRestartRecovery);

The fixture preserves the important production mismatch — the retained runtime-run ID is not one of the terminal channel-source IDs. Identity values are synthetic. The actual pre-update row had 16 terminal channel-source IDs, none matching its single retained runtime-run ID.

These fields were absent, not null, in the pre-update row — mainRestartRecovery, lifecycleRunId, activeWriterRunId, lastRunId, pendingFinalDelivery, restartRecoveryDeliveryRunId, restartRecoveryDeliverySourceRunId, restartRecoveryTerminalDeliveryEvidence, and lastRunError.

For the second boundary, call resolveMainSessionResumePolicy from main-session-restart-recovery-resume-policy.ts with a synthetic user message followed by an assistant text message having stopReason=stop and the Codex mirrorOrigin metadata. Leave expectedSourceTurnId and the optional delivery/hook receipt fields undefined. Test fullAccess=false and true.

Expected behavior

A historical failed row with ambiguous unmatched recovery residue must not, by itself, become authority to restart a completed conversation during an upgrade.

Reconcile the exact source turn, canonical final output, runtime completion, and delivery evidence before dispatch. Settle a proven completed obligation without starting a model turn. If surviving legacy state cannot establish unfinished work, preserve the evidence for explicit recovery rather than assuming the user wants the historical task restarted.

This must not discard genuine interrupted turns, yielded child continuations, or owed final delivery. Age alone is not sufficient evidence either to replay or to drop work.

Actual behavior

  • An immutable pre-migration backup from 2026-10-06T18:39:45Z still contained the failed row and July timestamps above.
  • The next canonical transcript input after the July final was the October synthetic recovery message. Its provenance was internal_system with sourceTool=main_session_restart_recovery and senderIsOwner=false.
  • The gap from the final reply to synthetic input was 70 days, 16 hours, 33 minutes.
  • Startup diagnostics named the same retained runtime-run ID as the interrupted run being resumed.
  • The agent made fresh read-only calls to an external service, composed a new answer, and sent it to the old Telegram topic. No external-service write was observed in this resumed turn.

Logs

Sanitized October 6 timeline. IDs and local paths are deliberately omitted or replaced.

18:38:02.100Z admission closed — restart (SIGTERM from update.run)
18:43:57.155Z marked 1 startup-orphaned main session(s) for restart recovery
18:44:03.673Z canonical internal recovery input timestamp
18:44:10.531Z Telegram resumption notice send succeeded to original topic
18:44:10.532Z started interrupted main session <affected-session>
18:44:10.532Z recovery candidate
  interruptedRunIds = [<same-old-runtime-run-from-backup>]
  decision = started
  reason = dispatch_started
  nextOwner = main-lane
18:44:10.549Z startup recovery complete
  started=1 settled=1 failed=0 skipped=3
18:45:17.898Z Telegram final reply send succeeded to original topic
18:45:18.017Z recovery terminal status=ok reason=completed

The generic marked-1 startup log does not identify its row, so it is not being used as proof that this particular session was newly marked there. The per-candidate dispatch log and pre-update backup establish the affected identity.

The same recovery pass settled a different session with reason=terminal-evidence. There is no claim that every old session resumed.

Screenshots, recordings, and evidence

Production-boundary A/B

Production evidence was inspected through bounded session history, Gateway logs, and a private copy of the immutable pre-migration database. No raw transcript files were scanned and no live database was edited.

Probe using identical legacy fixture Parent revision Affected revision
isMainSessionRecoveryPending before observe false true
observe view inactive recoverable
mainRestartRecovery after observe absent newly created
Final-text tail resume policy, fullAccess=false resume, no restart-safe restriction resume, no restart-safe restriction
Final-text tail resume policy, fullAccess=true resume, no restart-safe restriction resume, no restart-safe restriction
Matching terminal runtime fence control inactive inactive
Genuine interrupted-cycle control recoverable recoverable

Both state-boundary assertion runs passed with the expected before/after results, taking 4.09 seconds on the parent and 3.95 seconds on the affected revision. The parent and affected production modules were executed from separate pinned source trees with isolated state/config paths, synthetic identities, and no external delivery adapter. This proves the changed eligibility/state transition and the final-tail policy behavior. It is not a mock-Gateway end-to-end replay. The production logs independently establish actual dispatch and Telegram delivery.

Pinned source trace

  1. Discovery and candidate selection now reads session summaries across outcomes. The parent scanned only running rows and separately rejected non-running entries.
  2. Recovery-claim predicate treats an unmatched restartRecoveryRuns entry as a surviving claim.
  3. Observation transition creates a new aggregate for that claim plus abortedLastRun=true, without the old running-status gate. A terminal failed outcome does not settle an unmatched fence.
  4. Transcript resume policy recognizes specific correlated delivery/silent receipts, but plain terminal assistant text including the Codex mirror shape still resolves to resume. That policy behavior predates the triggering change.

Attribution limits

  • PROVEN — PR refactor(sessions): persist run outcomes only; liveness comes from the run registry #165733 changes the same retained legacy state from inactive to recoverable. It is also the affected deployed commit.
  • PROVEN — the October activation came from startup restart recovery, not new human input, cron, or a subagent completion.
  • PROVEN AT THE HISTORICAL SOURCE BOUNDARY — the July fail_recovery transition produces the retained failed/aborted/no-aggregate/unmatched-runtime-fence state. Its cleanup records the source ID but leaves the runtime fence. See the historical producer investigation below.
  • NOT YET PROVEN IN THIS INCIDENT — the exact July interruption/refusal that invoked that transition, or an alternative writer producing the same tuple, and the later metadata write that advanced updatedAt. The old endedAt is 2026-07-28T04:21:09.570Z and updatedAt is 2026-07-28T17:58:40.638Z. Neither the July residue nor that later metadata write is attributed to the October PR.
  • NOT YET PROVEN — whether the missing correlation is solely a native Codex settlement defect or also affects other legacy runtime/delivery combinations.

Historical producer investigation added October 6

The original report stopped at the October activation boundary. Further investigation recovered the retired source-host archive, compared its session metadata with the October pre-update backup, and exercised the July source path.

Additional retained production evidence

  • The September 16 retired-host snapshot already contains the same failed outcome, aborted flag, single runtime fence, 16 terminal source IDs, and July start/end/update timestamps. The later host migration and October update did not originate this tuple.
  • The archived native thread binding matches the affected canonical session and native transcript thread. Its runtime fingerprint records OpenClaw 2026.7.2-beta.3 and Codex app-server 0.144.6 on macOS 26.5.1. Its historyCoveredThrough and store timestamp are 2026-07-28T02:10:59.140Z, shortly after the mirrored final at 02:10:58.661Z.
  • The binding timestamp is an important boundary, not proof of successful channel delivery or complete Gateway lifecycle settlement. In the July source, coverage is written only on the completed-turn path, after context-engine finalization and the agent-end hook, and before lifecycle emission. This rules against treating a hypothetical pre-binding context-engine hang as the demonstrated incident cause.
  • The archived config audit corroborates beta.3 CLI use through July 28 at 01:29Z, and beta.5 at 06:27Z. The upstream beta.3 tag's peeled commit is d111bef0eed5aefb1e7c5ac59801c1f0924495f1. That is the tested historical source baseline; the archived version string alone is not a deployed-build hash.
  • runtimeMs is absent in both inspected snapshots. There is no saved pending-final receipt, run error, or recovery aggregate. The original per-run lifecycle trace and delivery receipt have not survived in the inspected evidence.

Concrete residue-producing path

At the historical baseline, ordinary assistant tails without correlated delivery evidence fail recovery with the reason transcript tail is not resumable. The failure branch calls the recovery failure transition.

The July fail_recovery transition writes failed status and abortedLastRun=true, stamps endedAt and updatedAt, clears pending-final/delivery metadata, and removes mainRestartRecovery. It does not remove restartRecoveryRuns or populate lastRunError.

Its claim-cleanup helper records the source ID as terminal. It records the runtime ID only if explicitly given terminalRunId, which fail_recovery does not supply. This is a concrete mechanism for retaining a runtime fence alongside terminal channel-source hashes.

Git blame identifies 0a868179e4c70d34dd5ae9968e2e86c650c7cd0a from PR #96230 as the source of that failure branch. Its material behavior remains present at c3713317b86bdef97d2cfbf47d543ff9cce3bb6e shortly before the original turn. This is historical code provenance, not proof that a specific deployment or production branch invocation was logged.

Why a mirrored final is not enough to locate the original interruption

Native finalization mirrors the native result before completing host bookkeeping. The completed binding-coverage checkpoint then precedes lifecycle emission. With deferTerminalLifecycle, the native terminal event becomes finishing, and active-run cleanup occurs after further awaited work. Thus the saved native completion and binding checkpoint do not establish when the core run became idle or when the channel delivery settled.

Additional scoped reproduction

Six source-extracted policy/state controls passed in approximately 0.57 seconds under Node 26.7.0, with extracted Git blob identities checked. An ordinary completed assistant tail was rejected as nonresumable; a user tail remained resumable. Applying interruption and fail_recovery with distinct synthetic source/runtime IDs produced failed status, abortedLastRun=true, no aggregate, 16 terminal source IDs, and one unmatched runtime fence. Stale-cycle rejection and matched/unmatched terminal-event controls were included.

A separate fake-adapter test of the actual finalizeCodexAttempt ordering passed in approximately 0.36 seconds. Gating awaited post-mirror finalization demonstrated that a native completed result can be mirrored before any terminal host lifecycle event. That test proves an ordering window only. It does not reproduce the production stall location, and the archived binding shows production advanced beyond the particular gate used in that test. No real provider, Gateway, database, or channel was exercised by these additional tests.

Alternatives and remaining evidence gap

  • The live terminal-pending cleanup is another failed/aborted writer, but it recomputes runtimeMs and does not itself remove mainRestartRecovery. It does not alone explain the inspected row. The report does not exclude a multi-writer sequence for which intermediate snapshots are missing.
  • The legacy importer can copy an already-poisoned incoming entry. It does not independently establish why the original fence remained, and it preserves an existing finite updatedAt rather than automatically using import time.
  • fail_recovery initially writes equal endedAt and updatedAt. The later 17:58 update therefore needs a separate metadata writer or an already-changed imported source. Its exact writer is not established.
  • Retention was checked on both the current host and the retired source-host archive. The archived native log database begins August 25; session-state events begin August 17; the archived identity audit begins September 6; the earliest retained stability bundle is July 31. July configuration audit survives but contains no per-run lifecycle trace. Exact-run searches of the retained Gateway/stability/ingress logs found no original-run entry. This is a documented historical coverage gap, not an access denial.
  • The decisive missing evidence is the July 28 04:21 recovery warning marked interrupted main session failed with its reason, plus the preceding shutdown marker and exact runtime/source correlation. Without it, the failure transition is a reproduced, strongly matching producer, not a directly observed production invocation.

Additional acceptance requirement

Terminal failure of a recovery obligation must retire or explicitly terminalize that exact obligation's source and runtime fences together, without consuming a newer or independent run. Test the historical failed-recovery output through a later upgrade/startup pass, not only a hand-constructed post-upgrade row. Preserve unknown-delivery evidence and legitimate interrupted work rather than blanket-clearing all retained fences.

Impact and severity

High for affected conversations because a routine update can reactivate an old task without new user intent, perform fresh tool work, incur cost, and send an unsolicited reply. The observed external-service operations were reads only; no claim of duplicated external mutations is made.

Frequency is one directly observed resumed conversation on this Gateway. In the pre-update agent snapshot, one row matched abortedLastRun=true plus an unmatched restartRecoveryRuns fence, and it was this affected session. The deterministic state-boundary fixture reproduces the eligibility change. Fleet-wide prevalence is unknown.

Additional information

Related but not duplicate

  • #111862 and #118873 concern stale recovery metadata blocking new foreground admission. This report concerns automatic execution without new input, with a failed legacy outcome and an unmatched fence.
  • #112732 concerns recovery fan-out, worker/memory pressure, and stale work. This incident is a single completed conversation being made eligible by the October outcome refactor, not a concurrency limit defect.
  • Open PR #166294 addresses an empty uncharged aggregate. This row instead had no aggregate and one unmatched run fence, so that patch does not cover the demonstrated shape.

Scoped acceptance criteria

  • Upgrade a legacy failed row with the demonstrated fence/source mismatch and a completed canonical turn without dispatching fresh model or tool work.
  • Cover native Codex mirrored finals and ordinary canonical finals while preserving source/run identity correlation. Do not treat an arbitrary earlier assistant message as proof a newer run finished.
  • Keep genuine interrupted work, unknown side-effect reconciliation, pending final delivery, and current yielded-child ownership recoverable exactly once.
  • Ensure ambiguous historical residue is visible for explicit recovery rather than silently reinterpreted as fresh execution authority.
  • Add an integration regression at the startup discovery → observe → transcript policy → dispatch boundary. Assert zero new model calls, tool calls, resumption notices, and final sends for the completed legacy fixture, with positive controls for genuine unfinished work.
  • Log the eligibility evidence and settlement reason without private message contents.

No raw chat text, account IDs, session IDs, credentials, private database copies, or user filesystem paths are included in this report.

Activity

  1. added
    bug
    on Oct 6, 2026
  2. added
    P1
    clawsweeper:needs-maintainer-review
    clawsweeper:no-new-fix-pr
    clawsweeper:source-repro
    impact:message-loss
    impact:session-state
    issue-rating: 🦞 diamond lobster
    on Oct 6, 2026
  3. clawsweeper commented on Oct 6, 2026

    @clawsweeper
    Contributor

    Codex review: this still needs some work. Reviewed October 6, 2026, 6:03 PM ET / 22:03 UTC.

    Summary
    Current main still permits the reported legacy state to become recoverable and reach fresh dispatch. Related cleanup work covers different state shapes, and the MEMBER-authored report requires explicit maintainer handling.

    Reproducibility: yes. the supplied failed/aborted fixture with an unmatched runtime fence deterministically reaches recoverable observation in unchanged current source, and the transcript policy permits continuation. This review did not execute tests or reproduce production dispatch.

    Regression provenance
    Regression provenance — verified: source commit 10334ec913d7 by Peter Steinberger; canonical PR #165733 (blame-to-merge-commit).

    Root-cause cluster
    Relationship: canonical
    Canonical: #166300
    Summary: This issue owns the demonstrated completed-conversation activation; neighboring residue and crash-loop work addresses distinct recovery failures.

    Members:

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

    Maintainer decision needed

    Question Recommendation
    Which correlated completion evidence is sufficient to settle these legacy failed fences, and should records lacking that evidence remain available only for explicit recovery? Reconcile exact obligations: Settle proven completed obligations and retain unresolved legacy evidence for visible explicit recovery, with positive controls for interrupted work and owed delivery.

    Why: The retained row lacks the correlation needed to distinguish completed historical work from an unfinished obligation; an automatic repair must not silently choose replay or discard.

    Next step
    Have the recovery owner approve the legacy correlation contract and oversee a startup-boundary repair; MEMBER authorship and unresolved obligation evidence exclude automatic fix dispatch.

    Review details

    Best possible solution:

    Reconcile exact obligations before dispatch, terminalize their source and runtime fences together, and expose ambiguous residue for explicit recovery while preserving genuine continuations and delivery custody.

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

    Yes: the supplied failed/aborted fixture with an unmatched runtime fence deterministically reaches recoverable observation in unchanged current source, and the transcript policy permits continuation. This review did not execute tests or reproduce production dispatch.

    Is this the best way to solve the issue?

    Unclear: exact-obligation reconciliation is the appropriate owner boundary, but the evidence contract needs approval before implementation. An age cutoff, blanket fence cleanup, or arbitrary assistant-final check would lose legitimate recovery.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • Legacy source, runtime, and delivery identities are not fully correlated; treating any assistant final as completion or clearing unmatched fences wholesale could discard genuine interrupted work or owed delivery.
    • The historical failure transition is a strongly matching reported producer, but the exact July production invocation and subsequent metadata writer remain unproven.

    Codex review notes: model internal, reasoning medium; reviewed against 91236e8c9501.

    Label changes

    Label changes:

    No label changes.

    Label justifications:

    • P1: A reported production update reactivated completed work, executed fresh service reads, and sent an unsolicited channel reply.
    • impact:session-state: Historical recovery residue is promoted into a new conversation execution cycle.
    • impact:message-loss: Recovery generated and delivered an unsolicited reply to the old Telegram topic without new user input.
    Evidence reviewed

    What I checked:

    • Complete captured report inspected: Read the full issue body through REST, including the omitted historical investigation and acceptance criteria. Its SHA-256 matches the supplied snapshot: d4514b9b59cb7fd49e90b4cd3235a4c23d0951d163e8ae736fcae7e56d7045b8. The report supplies production dispatch/delivery traces and pinned state-boundary A/B observations; it explicitly distinguishes a matching historical residue producer from an unproven production invocation.
    • Unmatched fence remains a recovery claim: hasMainSessionRecoveryClaim accepts a retained runtime fence whose ID is absent from terminal IDs. The supplied failed/aborted fixture therefore has a claim despite lacking an aggregate or delivery receipt. This is an OpenClaw-owned admission defect; establishing it does not depend on the Codex dependency's runtime contract. (src/config/sessions/restart-recovery-state.ts:550, 91236e8c9501)
    • Observation creates a fresh cycle: observe creates an aggregate from a claim plus abortedLastRun=true. Both terminal-only cleanup and completed-outcome settlement require every retained runtime fence to have a matching terminal fact, so the reported source/runtime mismatch survives and becomes recoverable. (src/agents/main-session-recovery/main-session-recovery-state.ts:348, 91236e8c9501)
    • Startup discovery and transcript policy permit dispatch: recoverStore reads summaries across outcomes and selects aborted rows with surviving claims. The resume policy recognizes correlated terminal delivery and silent-hook facts, but an ordinary completed assistant tail without those facts returns resume with forceRestartSafeTools=false. (src/agents/main-session-recovery/main-session-restart-recovery-resume-policy.ts:446, 91236e8c9501)
    • Relevant change verified against recorded parent: The raw commit records parent df73bb1. Its patch replaces the running-status observation gate with hasMainSessionRecoveryClaim and removes the corresponding running-only discovery restriction. GitHub verifies this commit as the merged outcome refactor at refactor(sessions): persist run outcomes only; liveness comes from the run registry #165733. This establishes the admission change, not the historical production residue's origin. (src/agents/main-session-recovery/main-session-recovery-state.ts:350, 10334ec913d7)
    • Still present on reviewed main: The comparison from the affected commit to reviewed main produces no changes in the recovery directory or restart-recovery-state module. The latest official release is v2026.9.8, published October 3, before the October 6 refactor; the report concerns a managed Git-source build carrying that version, rather than proving the regression shipped in that release. (src/agents/main-session-recovery/main-session-recovery-state.ts:350, 91236e8c9501)

    Likely related people:

    • Peter Steinberger: Raw commit 10334ec adds src/agents/main-session-recovery/main-session-recovery-state.ts:350 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 10334ec913d7; files: src/agents/main-session-recovery/main-session-recovery-state.ts)
    • zhangguiping-xydt: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
    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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1bugclawsweeper:needs-maintainer-reviewclawsweeper:no-new-fix-prclawsweeper:source-reproimpact:message-lossimpact:session-stateissue-rating: 🦞 diamond lobster

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions