openclaw - ✅(Solved) Fix Dreaming: session sprawl, missing model override, no auto-cleanup [1 pull requests, 1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
openclaw/openclaw#65963Fetched 2026-04-14 05:39:34
View on GitHub
Comments
1
Participants
2
Timeline
2
Reactions
1
Author
Participants
Timeline (top)
commented ×1cross-referenced ×1

Fix Action

Fixed

PR fix notes

PR #65589: feat(memory-core): dreaming circuit breaker to prevent runaway cost and data corruption

Description (problem / solution / changelog)

Summary

  • Adds a DreamingBudgetEnforcer module to the memory-core plugin that prevents dreaming runaway loops from burning unbounded API costs and corrupting daily notes
  • Implements three independent safety layers: per-cycle deduplication, sliding-window cost circuit breaker, and confidence-gated candidate filtering
  • Includes an integration helper (filterCandidatesThroughEnforcer) showing exactly how the enforcer plugs into the existing dreaming.ts pipeline
  • Covers all functionality with 51 unit tests including boundary conditions, persistence round-trips, and edge cases

Motivation

Issue #65550 documents a real production incident where the dreaming system entered an uncontrolled loop:

  • 94 LLM subagent sessions spawned in 65 minutes
  • $4.35 burned on API calls producing entirely garbage output
  • 302 lines of dream fragments overwrote real daily notes (data corruption)
  • All candidates had confidence: 0.00, recalls: 0 — zero-value entries that should never have been processed
  • 76 of 94 sessions reprocessed the same stale data with no deduplication

Root causes identified:

  1. No per-cycle deduplication — same candidates reprocessed in tight loops
  2. No cost tracking or budget cap — no awareness of accumulated API spend
  3. No candidate quality gate — zero-confidence entries passed through to expensive LLM calls

Users' only recourse is disabling dreaming entirely (dreaming.enabled: false), losing the long-term memory consolidation feature that is a core differentiator of OpenClaw.

Design

DreamingBudgetEnforcer (dreaming-budget.ts)

A stateful class instantiated at the start of each dreaming cycle with three guard methods:

LayerMethodWhat it prevents
DeduplicationshouldSkipDuplicate(snippet)Same content processed twice (SHA-256 fingerprint of normalized text)
Cost breakerisBudgetExceeded(nowMs?)Cumulative API cost exceeding configurable budget ($1.00/60min default)
Quality gateshouldSkipLowQuality(candidate)Zero-confidence/zero-recall candidates reaching LLM calls

Plus a composite checkCandidate() that runs all three checks in priority order (budget > quality > dedup).

Persistence: Budget state is saved to memory/.dreams/dreaming-budget.json via atomic write (temp file + rename) so it survives SIGUSR1 restarts. Uses the same file I/O patterns as short-term-promotion.ts.

Configuration: All thresholds are configurable via the plugin config schema under dreaming.budget:

{
  "dreaming": {
    "budget": {
      "maxCostUsd": 1.0,
      "windowMs": 3600000,
      "minConfidence": 0.05,
      "minRecalls": 1
    }
  }
}

Integration guide (dreaming-budget-integration.ts)

Documents the 6 exact integration points in the existing dreaming.ts pipeline with code snippets showing where each enforcer call is inserted. Also exports filterCandidatesThroughEnforcer() — a helper that filters ranked promotion candidates through all three safety layers and returns a breakdown of skip reasons.

Test plan

  • 51 vitest unit tests covering:
    • Fingerprinting: consistency, normalization, uniqueness, format validation
    • Deduplication: first/second encounter, case variants, cross-instance independence
    • Quality gate: zero confidence, zero recall, NaN, negative, custom thresholds
    • Cost breaker: under/over budget, latching behavior, window reset, default cost, invalid values
    • Composite check: priority ordering (budget > quality > dedup)
    • Persistence: save/load round-trip, missing file, corrupt JSON, wrong version, restart survival
    • Integration filter: valid candidates, duplicates, low quality, budget exceeded, empty list
    • Boundary conditions: exactly-at-threshold for confidence/cost, latch persistence through window expiry, state immutability
  • Verify existing dreaming.test.ts tests still pass after integration
  • Manual test: enable dreaming with budget.maxCostUsd: 0.10 and verify the cycle halts at the budget with a warning log

Closes #65550

Changed files

  • extensions/memory-core/src/dreaming-budget-integration.ts (added, +167/-0)
  • extensions/memory-core/src/dreaming-budget.test.ts (added, +541/-0)
  • extensions/memory-core/src/dreaming-budget.ts (added, +245/-0)

Code Example

{
  plugins: {
    entries: {
      "memory-core": {
        config: {
          dreaming: {
            enabled: true,
            frequency: "0 3 * * *",
            model: "anthropic/claude-sonnet-4-20250514"  // <-- new
          }
        }
      }
    }
  }
}

---

openclaw sessions purge --kind dreaming
openclaw sessions purge --older-than 24h --kind dreaming
RAW_BUFFERClick to expand / collapse

Problem

Dreaming creates a pair of sessions (narrative-light + narrative-rem) per memory chunk per cycle. With the default 0 */4 * * * frequency, this produces ~90+ session pairs per day, all using the agent's default model (in our case, claude-opus-4-6).

These completed dreaming sessions:

  • Clog the session picker UI — 184 out of 261 sessions were dreaming artifacts
  • Have no auto-cleanupopenclaw sessions cleanup marks them all as keep
  • Cannot use a cheaper model — no dreaming.model config knob exists
  • Cannot be bulk-purged — no openclaw sessions purge or --kind filter exists

What We Had to Do

  1. Manually parse sessions.json with a Python script to remove 184 dreaming entries
  2. Manually delete 184 .jsonl transcript files
  3. Reduce frequency from every-4h to daily (0 3 * * *) as the only lever available

Suggestions

1. Auto-purge completed dreaming sessions

Dreaming sessions are ephemeral by nature. Once consolidation completes (output written to DREAMS.md / memory/.dreams/), the session should be removed from the store automatically — or at minimum, openclaw sessions cleanup should treat them as purgeable.

2. Add dreaming.model config

Allow overriding the model used for dreaming sessions:

{
  plugins: {
    entries: {
      "memory-core": {
        config: {
          dreaming: {
            enabled: true,
            frequency: "0 3 * * *",
            model: "anthropic/claude-sonnet-4-20250514"  // <-- new
          }
        }
      }
    }
  }
}

Memory consolidation is summarization + pattern extraction. Sonnet or Haiku handle this well — Opus is overkill and expensive for background maintenance.

3. Add burst control (maxSessions or batchSize)

Each cycle fans out into dozens of parallel light+rem session pairs (one per ingested narrative chunk). A config like dreaming.maxSessions or dreaming.batchSize would let users cap the concurrency.

4. Filter dreaming sessions from the session picker

The session picker / openclaw sessions output should either:

  • Hide dreaming sessions by default (show with --include-dreaming)
  • Or group/collapse them under a single "Dreaming" entry

5. Add openclaw sessions purge CLI

A command like:

openclaw sessions purge --kind dreaming
openclaw sessions purge --older-than 24h --kind dreaming

Would make manual cleanup trivial instead of requiring direct JSON surgery.

Environment

  • OpenClaw 2026.4.11 (769908e)
  • Agent model: claude-opus-4-6
  • Dreaming frequency was 0 */4 * * * (now changed to 0 3 * * *)
  • 184 dreaming sessions accumulated in ~21 hours

extent analysis

TL;DR

Implement auto-purge for completed dreaming sessions and consider adding a dreaming.model config to reduce resource usage.

Guidance

  • Review the suggestions provided, particularly auto-purging completed dreaming sessions and adding a dreaming.model config, to mitigate the issue of clogged session picker UI and excessive resource usage.
  • Consider implementing burst control (maxSessions or batchSize) to limit the concurrency of dreaming sessions.
  • Evaluate the need for filtering dreaming sessions from the session picker UI to improve user experience.
  • Explore the possibility of adding an openclaw sessions purge CLI to simplify manual cleanup.

Example

{
  plugins: {
    entries: {
      "memory-core": {
        config: {
          dreaming: {
            enabled: true,
            frequency: "0 3 * * *",
            model: "anthropic/claude-sonnet-4-20250514"  
          }
        }
      }
    }
  }
}

This example demonstrates how to override the model used for dreaming sessions, potentially reducing resource usage.

Notes

The provided suggestions and examples are based on the issue description and may require further modification or testing to ensure compatibility with the specific OpenClaw version and environment.

Recommendation

Apply workaround: Implement auto-purge for completed dreaming sessions and consider adding a dreaming.model config to reduce resource usage, as these changes can help mitigate the issue without requiring a version upgrade.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING