Skip to content

[Bug]: memory-core dreaming narrative fails with "no low surrogate in string" API 400 — clampDiaryContextEntry truncates mid-surrogate-pair (fix on main, missing from v2026.7.1) #107815

Closed

Description

@OpenClawKobian99

Bug type

Behavior bug (incorrect output/state without crash)

Beta release blocker

No

Summary

The memory-core dreaming/narrative generation step can fail its underlying LLM API call with 400 The request body is not valid JSON: no low surrogate in string, causing every configured fallback model to fail identically and the pipeline to write a placeholder fallback diary entry ("A memory trace surfaced, but details were unavailable in this run.") instead of a real narrative.

Root cause: clampDiaryContextEntry() in extensions/memory-core/src/dreaming-narrative.ts truncates recent diary entries to RECENT_DIARY_CONTEXT_MAX_CHARS (360) characters using a plain UTF-16-code-unit slice. If the cut lands between the two code units of a surrogate pair (e.g. inside an emoji such as 🗞️ or 📊, which commonly appear in assistant-authored diary/report text), the resulting string ends in a lone, unpaired surrogate. When that corrupted string is JSON-encoded into the API request body, the request is rejected outright with a 400 before the model ever runs — so the same corrupted context defeats every model in the fallback chain identically (observed: primary model, then two configured fallback models, all failing with the same error class at slightly different byte offsets, consistent with the same bad substring appearing after differently-sized per-model system prompts).

This affects any install where DREAMS.md diary text contains multi-code-unit Unicode characters (most colorful emoji) near a 360-character diary-entry boundary. On several long-running workspaces on the same install we checked, this was close to a 100% fallback rate, since the assistant's own reports/diary text commonly include emoji.

Note on fix status: A fix for this exact pattern appears to already exist on main — commit 6a3834d41d ("fix(memory-core): use truncateUtf16Safe for diary context truncation", PR #102524, merged 2026-07-09), which replaces the raw .slice() in clampDiaryContextEntry with truncateUtf16Safe() from openclaw/plugin-sdk/text-utility-runtime (part of a broader surrogate-safety sweep across many subsystems around the same date — see #97805 and the batch of truncateUtf16Safe migration PRs merged 2026-07-09, e.g. #102551, #102591, #102525, #102592, #102590, #102567, #102593, #102513, #102547). However, fetching the actual file content at the latest tagged release v2026.7.1 (2026-07-13, after the fix commit date) still shows the unsafe .slice(), not truncateUtf16Safe. So either the fix hasn't been backported/released yet, or there's a release-branch divergence worth checking — anyone currently on the latest release tag is still affected.

Steps to reproduce

  1. Run OpenClaw with the bundled memory-core plugin and dreaming enabled (default) on a release where clampDiaryContextEntry still uses raw .slice() (confirmed present from v2026.6.10 through the current v2026.7.1 release tag).
  2. Let normal usage generate DREAMS.md diary entries containing emoji (e.g. from assistant-authored reports/summaries that later get referenced back into diary text).
  3. Let the dreaming/narrative cron run over several nights.
  4. Grep the gateway log for no low surrogate in string and memory-core: narrative generation ended with status=error.

Expected behavior

Diary-context truncation should be surrogate-pair-safe (as truncateUtf16Safe already is elsewhere in the codebase), so a 360-char cutoff never produces an invalid JSON payload, and narrative generation isn't defeated by its own context-prep step.

Actual behavior

Log excerpt (run/session IDs are random and host/path redacted):

model_fallback_decision candidate_failed requestedModel=claude-opus-4-8 attempt=1/3
  errorPreview: "API Error: 400 The request body is not valid JSON: no low surrogate in string: line 1 column 1672 (char 1671)"

model_fallback_decision candidate_failed candidateModel=claude-sonnet-5 attempt=2/3
  errorPreview: "API Error: 400 The request body is not valid JSON: no low surrogate in string: line 1 column 1736 (char 1735)"

model_fallback_decision candidate_failed candidateModel=claude-sonnet-4-6 attempt=3/3, fallbackStepFinalOutcome=chain_exhausted
  errorPreview: "API Error: 400 The request body is not valid JSON: no low surrogate in string: line 1 column 12864 (char 12863)"

memory-core: narrative generation ended with status=error (FallbackSummaryError: All models failed (3): ...) for deep phase; writing fallback diary entry.

All three configured fallback models fail identically — consistent with a malformed request body rather than a model- or provider-specific issue.

OpenClaw version

2026.6.10 — also confirmed present (via direct file inspection of extensions/memory-core/src/dreaming-narrative.ts at each tag) in v2026.6.11, v2026.7.1-beta.1, and the latest v2026.7.1.

Operating system

macOS (Darwin 25.5.0, arm64)

Install method

npm global install, OpenClaw Gateway running as a LaunchAgent

Provider / routing chain

claude-cli provider, dreaming/narrative lane, 3-step fallback chain (opus-4-8 → sonnet-5 → sonnet-4-6) — all three steps fail identically, which is itself evidence the request body (not the model) is at fault.

Related issues

Suggested fix

If not already resolved by getting commit 6a3834d41d / PR #102524 into a release: apply the same truncateUtf16Safe treatment already used elsewhere in the codebase to clampDiaryContextEntry in extensions/memory-core/src/dreaming-narrative.ts, and confirm it's actually included in the release branch — it appears to be present on main but not in the v2026.7.1 tag as of this report.

Activity

  1. added
    P2Normal backlog priority with limited blast radius.
    impact:data-lossCan lose, corrupt, or silently drop user/session/config data.
    impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.
    on Jul 16, 2026
  2. clawsweeper commented on Jul 16, 2026

    @clawsweeper
    Contributor

    Thanks for the context here. I did a careful shell check against current main, and this is already implemented.

    Close as implemented on current main: the diary-context boundary now preserves UTF-16 surrogate pairs, with focused regression coverage; the fix is main-only relative to v2026.7.1.

    So I’m closing this as already implemented rather than keeping a duplicate issue open.

    Review details

    Best possible solution:

    Keep the canonical UTF-16-safe implementation and regression test on main, include commit 6a3834d in the next release, and avoid a separate duplicate code change.

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

    Yes for affected releases: a normalized diary entry with a surrogate pair crossing the 360-code-unit cutoff produces a lone surrogate under the tagged raw-slice implementation. Current main no longer follows that failing path.

    Is this the best way to solve the issue?

    Yes. Reusing truncateUtf16Safe through the plugin SDK at the memory-core owner boundary is narrower and safer than adding local truncation logic or provider-specific request repair.

    Security review:

    Security review: This is issue triage without a proposed patch security review.

    AGENTS.md: found and applied where relevant.

    What I checked:

    Likely related people:

    • lsr911: Authored the focused merged change that replaced the unsafe diary-context slice with the shared UTF-16-safe helper. (role: introduced fix; confidence: high; commits: 6a3834d41d0c; files: extensions/memory-core/src/dreaming-narrative.ts, extensions/memory-core/src/dreaming-narrative.test.ts)
    • steipete: Recent history shows repeated maintenance and refactoring of the dreaming-narrative implementation and its plugin-SDK boundaries. (role: recent area contributor; confidence: high; commits: f3d2ae895a26, a644e30; files: extensions/memory-core/src/dreaming-narrative.ts)
    • vincentkoc: History connects this contributor to memory-core SDK boundary work and multiple dreaming-narrative fixes and mergers. (role: adjacent owner and merger; confidence: medium; commits: b78713a, 346e38e, 079eb18; files: extensions/memory-core/src/dreaming-narrative.ts)
    • vignesh07: The Dream Diary and simplified dreaming sweep behavior appears to date to the original implementation commit. (role: introduced behavior; confidence: medium; commits: 61e61cc; files: extensions/memory-core/src/dreaming-narrative.ts)

    Codex review notes: model internal, reasoning high; reviewed against 968c6581b645; fix evidence: commit 6a3834d41d0c, main fix timestamp 2026-07-09T08:49:22Z.

  3. locked as resolved and limited conversation to collaborators on Sep 3, 2026
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

    P2Normal backlog priority with limited blast radius.impact:data-lossCan lose, corrupt, or silently drop user/session/config data.impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions