Skip to content

fix(active-memory): bound assembled recall context - #110898

Merged
steipete merged 5 commits into
openclaw:mainfrom
joeykrug:fix/active-memory-bounded-recall-context
Oct 16, 2026
Merged

steipete merged 5 commits into
openclaw:mainfrom
joeykrug:fix/active-memory-bounded-recall-context

Conversation

@joeykrug

@joeykrug joeykrug commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Related: #88077, #92013

What Problem This Solves

Fixes oversized Active Memory recall context overwhelming a small local model or spending the recall deadline on old conversation text.

User Impact

Recall context is bounded to 4,000 UTF-16 code units in all query modes. The current request takes priority over history. full mode considers all available history within that limit and drops older material first. When the current request alone exceeds the limit, recall retains its beginning and end with an explicit middle-omission marker. The original request delivered to the answering model is unchanged.

Why This Change Was Made

The existing query owner now assembles and bounds one recall context. It keeps the producer-owned current-request contract and independent bounded search seed, and removes the old PR's envelope-marker parsing and extra diagnostics plumbing. No new setting or schema is added.

Thanks @joeykrug for diagnosing and reproducing the oversized recall requests. All contributor commits are retained; this update merges current main and modernizes the repair around the current query owner.

Evidence

Budget calibration on macOS with Qwen3:4b: an exact captured Gateway recall envelope used 3,744 prompt tokens with a 4K query, leaving 3,936 tokens in an 8K window after a 512-token output reserve. Denser controls explain the conservative cap: a 12K Chinese query plus the plugin instructions/tools used 9,436 tokens, and a 6K emoji query used 7,997; oversized native inputs could silently truncate. A character cap is a best-effort bound, not a universal token guarantee.

Baseline through the real Gateway assembled a 12,097-character query. A deterministic recall-model fixture exercised the real memory_search/embeddinggemma path, then the real main Qwen model answered with the seeded phrase. Focused tests reproduced six size failures while all 13 existing/under-limit cases passed (30.01s wall).

The same 19 focused query tests pass on the fix with the explicit Node runtime (92.88s wall). The first default-Bun attempt stalled before assertions and was stopped; it is not counted as product evidence. Prompt snapshot generation passed (63.67s), with zero generated-file delta; these static snapshots do not render dynamic Active Memory queries. The measured real-envelope query saving is 1,333 prompt tokens (5,077 to 3,744).

Production: +41/−30 lines (net +11). Tests: +91/−2. The new limit and UTF-16-safe head/tail logic require the remaining growth after merging duplicate full/recent assembly. Isolated Codex review reports no actionable P0–P2 finding.

Fixed-head Gateway boundary proof: the same 12,097-unit current request produced exactly 4,000 units, retained the quoted sentinel and ending question, and completed in 10.744s. The first recall request had no answer; the real memory_search result contained the seeded phrase; the deterministic recall-model fixture then returned its grounded summary (2.912s recall), and the real LM Studio Gemma 4 E4B answering model returned the phrase. The tool used the real Nomic embedding backend. An initial proof-relay JSON forwarding bug was repaired and the isolated synthetic index rebuilt before this successful run; that failed harness attempt is not counted as product proof.

Full build passed (1,831.09s wall, including SDK exports and UI). Scoped type-aware lint passed (2,212.93s including waiting for the build lock and declaration preparation). Production extension types passed (14.99s), test extension types passed (16.47s).

Fully native control also passed with LM Studio Gemma 4 E4B and Nomic embeddings, using the existing explicit tools.toolSearch: false option in isolated proof config. Gemma itself called memory_search; the first recall request lacked the phrase and the subsequent tool result contained it. Both captured requests held the exact 4,000-unit query, quote, and final question. Recall completed in 9.639s and the complete answering request in 14.250s. With default Tool Search, this model first sent an invalid search argument shape and returned no relevant memory; that model/tool-selection limitation is recorded separately from the bounded-query behavior. No production tool-publication policy changes are included.

Formatting, line-cap, assertion safety, timeout-race, mock-export, config/docs, plugin inventory, and diff checks passed. Max-lines reports the same pre-existing suppression in ui/src/pages/chat/components/chat-message.test.tsx; this file is byte-identical to tested base b62a8f8dab531b3909fa63ef74b28f45d2fda5b9, where the identical failure was already reproduced (18.09s). Local validation is macOS-only; cross-platform coverage comes from PR CI.

Exact-head CI passed all query-limit cases and all 266 config-shard tests. CI test-types is red from the inherited Codex session-binding test rename mismatch introduced by #173951: three call sites retain names that their imports now alias. The exact CI base has the same file blob as the previously verified failing base; this PR does not change that file.

joeykrug added 3 commits July 18, 2026 14:45
… current request

Production event.prompt envelopes reached 609K-693K UTF-16 chars and drove
30s blocking-hook timeouts (openclaw#88077, openclaw#92013). buildQuery now bounds the
complete model-facing recall context: the current user request survives
verbatim (event.prompt stays the current-turn source), generated
<conversation_context> blocks keep only a sanitized newest tail with tool
traces dropped, quoted-reply channel sections are preserved, and the
memory_search query is seeded from the bounded request while keeping its
480-char clamp as defense in depth. Recall start logs gain queryCharsRaw=
and queryBounded= when bounding engages.
…emission

Adversarial review: a request containing the literal </conversation_context>
could redirect the lastIndexOf split and drop the real current request
(falling back to the stale envelope head — the same stale-query class that
sank the messageMaxChars attempt). Split on the projection's exact joint
emission instead; quoting either marker alone can no longer move the split.
Also: cite the real reply-target producer and drop recognizers that had no
producer in-tree, cover '[unserializable payload omitted]', and make the
oversized-envelope test builders linear.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L labels Jul 18, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Bounds assembled Active Memory recall context to 4,000 UTF-16 units, prioritizing the current request over older history.

Example: A current request contains 12,097 UTF-16 units, including quoted context and an ending question.

  • Before: Recall receives the oversized request.
  • After: Recall receives 4,000 units retaining the beginning and ending question, with an explicit omission marker.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repair with native Gateway evidence, meaningful boundary regressions, resolved prior findings, and passing exact-head validation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied fixed-head Gateway observation exercises the changed query owner with an oversized request, native Gemma recall, real Nomic-backed memory_search, and the answering model; captured requests retain the quote and final question within 4,000 units and the answer contains the seeded phrase.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Oversized recall context can overwhelm a small local model or consume the blocking recall deadline.
Reason: The focused repair has demonstrated user value, and the area contributor’s recorded implementation explicitly adopts bounded history and current-request priority.

Merge readiness

✅ Ready for maintainer review

This PR retains useful size protection absent from main, resolves the earlier correctness findings, and has sufficient Gateway proof and passing exact-head CI.

Priority: P2
Reviewed head: 849488e8e851e5c7f50bf52b493331a33505cb34

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Active Memory prompt-build hook combines the admitted request with eligible conversation history, sends it to a recall subagent, and supplies the resulting memory summary to the answering model.

flowchart LR
A[Admitted request and history] --> B[Prompt build hook]
B --> C[Bounded recall query]
C --> D[Recall subagent]
D --> E[Memory search]
E --> D
D --> F[Answering model]
Loading

Technical review

Best possible solution:

Land the focused query-owner repair with its documented, intentionally bounded history behavior.

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

Current-main source directly exposes unbounded current requests and full-history assembly; the supplied baseline Gateway observation records a 12,097-unit query, and no target code was executed during this review.

Is this the best way to solve the issue?

The repair belongs in the existing query owner, avoids content-derived request boundaries, preserves the independent search seed, and uses existing UTF-16 slicing helpers without adding configuration or persistence.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 11c24cfd6dbd.

Provenance checked

  • Full-history recall changes intended behavior with a stated reason (b83726d: The original feature offered configurable full-history recall for continuity; later helper extraction preserved that behavior.)
  • Recent-history assembly and current-request handling changes intended behavior with a stated reason (c87941e: The helper extraction preserved query formatting and current-message priority; subsequent refactors consolidated equivalent selection logic.)
  • Tuning documentation changes intended behavior with a stated reason (4c41c26: The task-page split retained existing query-mode guidance; this PR updates that guidance to match the newly chosen bound.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change: The pinned introduced diff changes only query assembly, its regression coverage, and the tuning guide; it preserves the independent search seed and existing producer-owned request handling. (extensions/active-memory/query.ts:23, 849488e8e851)
  • Main still lacks the bound: Current main returns genuine current requests without a total size limit and includes every supplied turn in full mode, so the central protection remains distinct work. (extensions/active-memory/query.ts:25, 11c24cfd6dbd)
  • Recorded direction and prior findings: The area contributor’s repair commit explicitly chooses current-request priority within one bounded query. The updated guide explains the full-mode tradeoff; delimiter inference is removed, and insufficient header space now returns the intact current request. These address the three earlier findings. (extensions/active-memory/query.ts:76, cc4cc1106a39)
  • Supplied production behavior proof: The updated body records a native isolated Gateway run with Gemma and Nomic embeddings: both captured recall requests contained the bounded 4,000-unit query, the quote and final question survived, memory_search returned the seeded phrase, and the answering model returned it. (849488e8e851)
  • Exact-head validation: The exact reviewed head has successful openclaw/ci-gate, production types, test types, lint, docs, and changed-test checks. GitHub reports the head cleanly mergeable; cancelled auto-response runs are not failed required validation. (849488e8e851)
  • Feature history and original intent: The original Active Memory feature introduced deliberate full-history recall; subsequent extraction and rename preserved it. The present repair explains its intentional change. Some historical blobs were unavailable locally, so the original introduction was independently inspected through GitHub’s commit patch. (extensions/active-memory/index.ts:1019, b83726d13e33)

Likely related people:

  • Peter Steinberger: Raw commit c87941e adds extensions/active-memory/active-memory-query.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c87941e523f2; files: extensions/active-memory/active-memory-query.ts)

PR surface

Source +11, Tests +89, Docs +9. Total +109 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 41 30 +11
Tests 1 91 2 +89
Docs 1 13 4 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 145 36 +109

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +41/−30 lines; tests +91/−2 lines The modest production growth implements bounded assembly and UTF-16-safe head/tail preservation while consolidating recent and full assembly.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Oversized recall inputs can exhaust local-model context or recall deadlines, while the answering turn retains its existing fallback.
  • merge-risk: 🚨 compatibility: Existing full-mode users will receive the newest history fitting the cap instead of all history; the repair commit explicitly chooses this tradeoff and the tuning guide documents it.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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 (3 earlier review cycles)
  • reviewed 2026-09-27T00:39:37.533Z sha 95e1167 :: blocked before merge. :: [P1] Preserve the documented full-conversation mode | [P2] Stop locating the current request with a user-quotable delimiter
  • reviewed 2026-10-12T16:41:52.193Z sha 95e1167 :: blocked before merge. :: [P1] Preserve the documented full-conversation mode | [P2] Use producer-owned boundaries instead of user-quotable delimiters | [P3] Reserve assembly overhead before bounding the current request
  • reviewed 2026-10-16T01:53:08.176Z sha 95e1167 :: blocked before merge. :: [P1] Preserve the documented full-conversation mode | [P2] Use producer-owned boundaries instead of user-quotable delimiters | [P3] Reserve assembly overhead before bounding the current request

Reviewed October 16, 2026, 5:23 AM ET / 09:23 UTC (Revision 4).

@joeykrug

Copy link
Copy Markdown
Contributor Author

Real after-fix behavior proof added to the PR body Evidence section: an isolated source gateway built from this branch processed the same 620,391-char envelope shape as a live /v1/responses (webchat-channel) turn — queryChars=24680 queryCharsRaw=620391 queryBounded=true searchQueryChars=66, recall completed status=ok summaryChars=211 within the 30s hook budget that the production before-logs exhausted. Setup and replica limitations documented in the body.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 4, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 13, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 28, 2026
@clawsweeper clawsweeper Bot removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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. labels Sep 22, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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. labels Oct 1, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
Prioritize the current request within one bounded recall query and use the remaining space for recent history. Keep the existing search seed and current-request ownership, with no new configuration or schema.

Co-authored-by: Joey Krug <[email protected]>
@steipete
steipete requested a review from a team as a code owner October 16, 2026 08:37
@steipete steipete changed the title fix(active-memory): recall sub-agent receives huge prompt envelopes; bound recall context to 25K chars fix(active-memory): bound assembled recall context Oct 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: XL and removed docs Improvements or additions to documentation size: L labels Oct 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: active-memory size: S and removed size: XL labels Oct 16, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 16, 2026
@steipete
steipete merged commit a9fe8ab into openclaw:main Oct 16, 2026
109 of 112 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
* fix(active-memory): bound recall context to 25K chars, preserving the current request

Production event.prompt envelopes reached 609K-693K UTF-16 chars and drove
30s blocking-hook timeouts (openclaw#88077, openclaw#92013). buildQuery now bounds the
complete model-facing recall context: the current user request survives
verbatim (event.prompt stays the current-turn source), generated
<conversation_context> blocks keep only a sanitized newest tail with tool
traces dropped, quoted-reply channel sections are preserved, and the
memory_search query is seeded from the bounded request while keeping its
480-char clamp as defense in depth. Recall start logs gain queryCharsRaw=
and queryBounded= when bounding engages.

* fix(active-memory): preserve native reply context when bounding

* fix(active-memory): anchor envelope split on the joint close+request emission

Adversarial review: a request containing the literal </conversation_context>
could redirect the lastIndexOf split and drop the real current request
(falling back to the stale envelope head — the same stale-query class that
sank the messageMaxChars attempt). Split on the projection's exact joint
emission instead; quoting either marker alone can no longer move the split.
Also: cite the real reply-target producer and drop recognizers that had no
producer in-tree, cover '[unserializable payload omitted]', and make the
oversized-envelope test builders linear.

Co-authored-by: Joey Krug <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 6, 2026
* fix(active-memory): bound recall context to 25K chars, preserving the current request

Production event.prompt envelopes reached 609K-693K UTF-16 chars and drove
30s blocking-hook timeouts (#88077, #92013). buildQuery now bounds the
complete model-facing recall context: the current user request survives
verbatim (event.prompt stays the current-turn source), generated
<conversation_context> blocks keep only a sanitized newest tail with tool
traces dropped, quoted-reply channel sections are preserved, and the
memory_search query is seeded from the bounded request while keeping its
480-char clamp as defense in depth. Recall start logs gain queryCharsRaw=
and queryBounded= when bounding engages.

* fix(active-memory): preserve native reply context when bounding

* fix(active-memory): anchor envelope split on the joint close+request emission

Adversarial review: a request containing the literal </conversation_context>
could redirect the lastIndexOf split and drop the real current request
(falling back to the stale envelope head — the same stale-query class that
sank the messageMaxChars attempt). Split on the projection's exact joint
emission instead; quoting either marker alone can no longer move the split.
Also: cite the real reply-target producer and drop recognizers that had no
producer in-tree, cover '[unserializable payload omitted]', and make the
oversized-envelope test builders linear.

Co-authored-by: Joey Krug <[email protected]>

(cherry picked from commit a9fe8ab)

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: active-memory merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

2 participants