Skip to content

fix(memory): remove interrupted Dreaming sessions after Gateway restart - #117885

Merged
steipete merged 4 commits into
mainfrom
codex/issue-78458-dreaming-startup-cleanup
Aug 2, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/issue-78458-dreaming-startup-cleanup

Conversation

@steipete

@steipete steipete commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #78458.

What Problem This Solves

Fixes an issue where restarting Gateway during a Dreaming cycle left completed or interrupted Dreaming child sessions visible permanently in the Control UI and session listings.

Why This Change Was Made

Give the memory plugin ownership of bounded Dreaming-session reconciliation during Gateway startup and one deferred age-safe follow-up. Freeze both evaluation clocks at Gateway startup so slow initialization, delayed callbacks, and same-millisecond admissions can never delete sessions created after startup. Use canonical SQLite session/node/window metadata to preserve active or freshly updated sessions, explicitly foreign plugin owners, unrelated users, and other logical agents sharing the same physical store; retain compatibility with previously shipped ownerless Dreaming rows. Existing normal narrative cleanup now uses the same agent-scoped owner instead of scanning every state directory. Missing agent databases are never created by cleanup, and lifecycle timers are cancelled safely on shutdown or a newer Gateway start.

User Impact

Interrupted Dreaming light, REM, deep, and consolidation child sessions disappear automatically after a Gateway restart or after their existing safe age window. Real user sessions, active Dreaming work, other plugins, and other agents remain untouched. No operator action, new configuration, schema migration, file store, or cron scheduling is required.

Evidence

  • Exact reviewed head: 3384a0967ad5cdf4d978276cb769d5713c1e467d, rebased onto the latest main without changing reviewed Dreaming behavior; the final follow-up only applies canonical formatting to an existing conformance assertion.
  • Authentic failing-first coverage seeds real canonical SQLite session state for aged/active/no-event/reused-session Dreaming children; owned, legacy-ownerless, and explicitly foreign plugin sessions; ordinary user sessions; historical windows; missing cold-start databases; multiple configured agents; and shared physical stores.
  • Real hosted child-Gateway process E2E starts Gateway, observes actual authenticated WebSocket sessions.list, terminates and restarts the process against the same state, and proves old Dreaming children are removed while active, foreign-owned, and unrelated user sessions survive. Dreaming and cron scheduling are disabled during the scenario; no fake startup hook or direct cleanup call is used.
  • Hosted focused lifecycle/startup/narrative suites: 54 passed; sibling Gateway ownership, plugin SDK, Dreaming, and consolidation suites: 92 passed; actual authenticated Gateway restart E2E: 1 passed — 147 total scenarios passed.
  • Hosted exact-final real Gateway restart, owner lint, focused regression, and extension production/test typecheck proof: https://github.com/openclaw/openclaw/actions/runs/30736627375 — command exit 0; Testbox stopped after completion.
  • Hosted exact-final storage-conformance proof: https://github.com/openclaw/openclaw/actions/runs/30737563085 — both public and SQLite lifecycle adapters, cleanup races, active-memory and plugin SDK siblings, 159 memory-owner scenarios, actual authenticated Gateway process restart, targeted core lint, and core-test typechecks all passed. Existing conformance fixtures now use timestamp-preserving replacement for intentionally old sessions; normal upsert deliberately refreshes session timestamps, so weakening production freshness checks would incorrectly delete active work.
  • Required red-main repair: the latest main introduced duplicate loadPluginRegistryHandle keys in src/plugins/cli.test.ts, simultaneously breaking required lint and test TypeScript gates. This PR removes only the obsolete first mock, preserving the existing last-definition behavior and the correct activate: false loader contract. Exact rebased hosted proof https://github.com/openclaw/openclaw/actions/runs/30738360646 passed targeted core lint, plugin CLI/loader owners, 219 session/config scenarios, 159 memory scenarios, real authenticated Gateway restart, and the complete official pnpm check:test-types core/extension/root lanes; command exit 0 and Testbox stopped.
  • Existing plugin SDK surface, API-baseline, schema, export, declaration, formatting, package boundaries, all five production/test TypeScript lanes, and full core lint: passed. Final targeted plugin lint additionally verifies the exact submitted source.
  • Fresh independent owner/security/lifecycle review and structured gpt-5.6-sol xhigh autoreview with --max-priority P2: no actionable P0/P1/P2 findings; final conformance-fix correctness confidence 0.99.
  • ClawSweeper rank-up disposition: exact-head lint and production/test typechecks are green. Maintainer explicitly accepts cleanup of previously shipped ownerless Dreaming rows only when their canonical Dreaming prefix, logical agent, strictly pre-startup activity timestamp, and age threshold all match; explicitly foreign-owned, active/fresh, post-startup, other-agent, and unrelated user sessions remain protected.
  • No new SQLite schema/version, config/default, environment variable, dependency, file-state store, plugin SDK export, or compatibility fallback.
  • AI-assisted implementation and review.

@openclaw-barnacle openclaw-barnacle Bot added extensions: memory-core Extension: memory-core size: XL maintainer Maintainer-authored PR labels Aug 2, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 2, 2026, 4:10 AM ET / 08:10 UTC.

ClawSweeper review

What this changes

The PR makes the Memory Core plugin reconcile stale Dreaming child sessions at Gateway startup and extends shared SQLite lifecycle cleanup with agent and plugin-owner filtering.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep this PR open for the requested maintainer decision. Current main only runs Dreaming artifact cleanup from the narrative path and its Gateway-start hook reconciles cron state, so it does not address interrupted child sessions left after a restart; the proposed owner-boundary repair is plausible and has strong reported Gateway-restart proof, but it intentionally reclaims aged ownerless legacy session rows and changes the shared plugin cleanup contract.

Priority: P2
Reviewed head: 3384a0967ad5cdf4d978276cb769d5713c1e467d
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has strong reported real restart proof and a coherent owner-boundary design, with merge readiness intentionally held for the durable legacy-row policy decision.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides after-fix hosted evidence of an authenticated real Gateway restart against persisted state and reports that old Dreaming children are removed while protected sessions remain; redact any private runtime details if additional artifacts are posted.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides after-fix hosted evidence of an authenticated real Gateway restart against persisted state and reports that old Dreaming children are removed while protected sessions remain; redact any private runtime details if additional artifacts are posted.
Evidence reviewed 6 items Current main does not perform restart cleanup: The current Gateway-start handler stores gateway context and reconciles Dreaming cron state, then starts cron retry/reconciliation timers; it does not invoke Dreaming session cleanup.
Existing cleanup is not a restart recovery path: Current main defines Dreaming artifact scrubbing inside the narrative module, where it scans agent directories and calls lifecycle cleanup only while that narrative flow runs.
Current shared cleanup lacks plugin-owner filtering: The current SQLite lifecycle cleanup accepts the generic lifecycle parameters and forwards only segment/marker/age criteria into its plan, so the branch’s optional plugin-owner boundary is a meaningful shared contract addition.
Findings None None.
Security None None.

How this fits together

Memory Core schedules and runs Dreaming work through Gateway lifecycle hooks, while session entries and transcripts persist in each agent’s SQLite state. The cleanup path determines which stale Dreaming records disappear from session listings and which active, foreign-plugin, or other-agent records remain.

flowchart LR
  A[Gateway restart] --> B[Memory Core startup hook]
  B --> C[Configured Dreaming agents]
  C --> D[SQLite session lifecycle cleanup]
  D --> E{Age, agent, and owner filters}
  E -->|stale Dreaming child| F[Remove session and transcript artifacts]
  E -->|active or foreign state| G[Preserve stored session]
  F --> H[Gateway session listings]
  G --> H[Gateway session listings]
Loading

Decision needed

Question Recommendation
Should Gateway startup reclaim aged ownerless legacy Dreaming rows, alongside explicitly Memory-Core-owned stale rows, to repair sessions persisted by earlier releases? Accept bounded legacy reconciliation: Land the PR’s age-, agent-, and ownership-scoped cleanup so older ownerless Dreaming rows are repaired automatically after restart.

Why: This is a durable-session cleanup policy with intentional upgrade effects; source and tests can establish mechanics, but they cannot decide whether ownerless historical rows should remain eligible for automatic deletion.

Before merge

  • Resolve merge risk (P1) - The PR deliberately permits cleanup of aged ownerless legacy Dreaming rows. That upgrade behavior is compatible with repairing already-persisted stale sessions, but it is a maintainer policy choice because those records are durable user-visible session state.
  • Resolve merge risk (P1) - The PR head is behind current main, although GitHub reports it as mergeable; exact-head CI and the merge result should be refreshed after the maintainer accepts the cleanup policy.
  • Complete next step (P2) - A protected maintainer label and the deliberate policy for durable ownerless legacy sessions require an explicit human acceptance before merge.
Agent review details

Security

None.

PR surface

Source +148, Tests +871. Total +1019 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 209 61 +148
Tests 6 880 9 +871
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 1089 70 +1019

Review metrics

Metric Value Why it matters
Shared lifecycle cleanup contract 1 optional plugin-owner filter added The new filter changes which persisted plugin session records a generic cleanup operation may reclaim, so its compatibility semantics need explicit approval.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.conformance.test.ts, serialized state: src/config/sessions/session-accessor.lifecycle-types.ts, serialized state: src/config/sessions/session-accessor.sqlite-cleanup-race.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-lifecycle-state.ts, serialized state: src/config/sessions/session-accessor.sqlite-lifecycle.ts, serialized state: src/plugin-sdk/session-store-runtime.ts, and 14 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #78458
Summary: This PR directly targets the reported Gateway-restart persistence of Dreaming child sessions and is the candidate fix for the canonical issue.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept the bounded legacy cleanup policy (recommended)
    Approve the age- and ownership-filtered reconciliation after confirming that reclaiming ownerless historical Dreaming rows is the intended upgrade behavior.
  2. Narrow the legacy-row policy before merge
    Change the branch only if maintainers decide ownerless historical rows need an explicit migration or operator-owned recovery path rather than automatic startup cleanup.
  3. Pause the durability-policy change
    Close or defer this branch if the repository does not want Gateway startup to make persistent-session retention decisions for legacy rows.

Technical review

Best possible solution:

Keep the Memory Core plugin as the lifecycle owner, land the bounded startup and deferred reconciliation only after explicitly accepting the documented policy for aged ownerless legacy Dreaming rows, and retain the agent/plugin/freshness protections as the canonical shared cleanup contract.

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

Yes, at source level: current main runs cleanup from the Dreaming narrative path, while the Gateway-start path only reconciles cron state. Restarting after an interrupted child run can therefore retain the persisted child session until another narrative cleanup happens.

Is this the best way to solve the issue?

Yes, with a maintainer-owned policy confirmation: the plugin owns Dreaming lifecycle timing, while core receives a generic agent/plugin ownership filter instead of Dreaming-specific logic.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs stale session-listing state after an interrupted Dreaming run with a bounded, non-emergency blast radius.
  • merge-risk: 🚨 compatibility: The shared plugin-facing lifecycle cleanup contract gains a new ownership filter and changes upgrade behavior for ownerless historical rows.
  • merge-risk: 🚨 session-state: Gateway startup can delete persisted Dreaming session entries and their lifecycle artifacts based on age and ownership metadata.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides after-fix hosted evidence of an authenticated real Gateway restart against persisted state and reports that old Dreaming children are removed while protected sessions remain; redact any private runtime details if additional artifacts are posted.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix hosted evidence of an authenticated real Gateway restart against persisted state and reports that old Dreaming children are removed while protected sessions remain; redact any private runtime details if additional artifacts are posted.

Evidence

What I checked:

  • Current main does not perform restart cleanup: The current Gateway-start handler stores gateway context and reconciles Dreaming cron state, then starts cron retry/reconciliation timers; it does not invoke Dreaming session cleanup. (extensions/memory-core/src/dreaming.ts:1017, 86a95b459c94)
  • Existing cleanup is not a restart recovery path: Current main defines Dreaming artifact scrubbing inside the narrative module, where it scans agent directories and calls lifecycle cleanup only while that narrative flow runs. (extensions/memory-core/src/dreaming-narrative.ts:817, 86a95b459c94)
  • Current shared cleanup lacks plugin-owner filtering: The current SQLite lifecycle cleanup accepts the generic lifecycle parameters and forwards only segment/marker/age criteria into its plan, so the branch’s optional plugin-owner boundary is a meaningful shared contract addition. (src/config/sessions/session-accessor.sqlite-lifecycle.ts:107, 86a95b459c94)
  • Feature-history owner signal: Blame attributes the current Dreaming Gateway-start hook and current narrative cleanup to the same recent Memory Core change by Peter Steinberger, making that author the strongest routing candidate for the lifecycle and ownership decision. (extensions/memory-core/src/dreaming.ts:1017, 57c6f7622133)
  • Reported after-fix behavior proof: The PR body reports an authenticated child-Gateway restart E2E against persisted state, preserving active, foreign-owned, and unrelated sessions while removing aged Dreaming children; it also links exact-head hosted validation runs. (test/dreaming-startup-cleanup.e2e.test.ts:1, 3384a0967ad5)
  • Local branch-inspection limitation: The checkout is a promisor clone missing required PR objects. Attempting the exact base-to-head diff required a remote fetch, which failed because github.com could not resolve; this review therefore uses the supplied PR patches and metadata plus directly inspected current main.

Likely related people:

  • steipete: Current-main blame attributes both the Gateway-start Dreaming lifecycle and the existing narrative cleanup to Peter Steinberger’s recent Memory Core work. (role: recent area contributor and current behavior author; confidence: high; commits: 57c6f7622133; files: extensions/memory-core/src/dreaming.ts, extensions/memory-core/src/dreaming-narrative.ts, src/config/sessions/session-accessor.sqlite-lifecycle.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-02T07:19:47.462Z sha d631985fbbb61ea0a154109c8f87303f906c9781 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-02T07:40:33.021Z sha 8be9c5fc1528ab145eb7b437ccead26e93e15122 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-02T07:59:35.441Z sha ee288a9 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/issue-78458-dreaming-startup-cleanup branch from 8be9c5f to ee288a9 Compare August 2, 2026 07:53
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Aug 2, 2026
@steipete
steipete merged commit f5c985d into main Aug 2, 2026
134 of 135 checks passed
@steipete
steipete deleted the codex/issue-78458-dreaming-startup-cleanup branch August 2, 2026 08:17
@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to yetval/openclaw that referenced this pull request Aug 2, 2026
…r-117788-empty-startup-race

* commit '9517b10778ba69b94471cb1f122a5f1e19aa22a4':
  fix(hooks): show eventless status consistently (openclaw#116127)
  refactor(cli): consolidate security-sensitive regression fixtures (openclaw#114411)
  perf(plugins): list from installed metadata (openclaw#117900)
  fix(memory): remove interrupted Dreaming sessions after Gateway restart (openclaw#117885)
  test(gateway): reuse startup plugin metadata snapshot (openclaw#117897)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
…rt (openclaw#117885)

* fix(memory): clean interrupted Dreaming sessions after Gateway restart

* test(sessions): preserve historical timestamps in lifecycle fixtures

* test(plugins): remove duplicate registry handle mock from main

* style(sessions): format lifecycle conformance assertion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-core Extension: memory-core maintainer Maintainer-authored PR 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. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

Dreaming: spawned sessions not cleaned up after Gateway restart

1 participant