Repository navigation
fix(memory-core): avoid cubic MMR similarity rescans - #113359
Conversation
|
Codex review: needs maintainer review before merge. Reviewed July 28, 2026, 12:37 PM ET / 16:37 UTC. ClawSweeper reviewWhat this changesThis PR changes Memory Core’s maximal-marginal-relevance reranker to cache each candidate’s greatest similarity to already selected chunks, replacing repeated rescans, and adds a ranking-equivalence regression test. Merge readinessThis PR appears to be a focused, well-evidenced availability fix, but the required local source, history, and current-main review could not be completed because the read-only command sandbox failed to start. Keep it open for a refreshed current-head maintainer review rather than making a merge or close verdict from supplied context alone. Priority: P1 Review scores
Verification
How this fits togetherMemory Core retrieves hybrid-search candidates, then reranks them for diversity before returning memory chunks to an agent. This PR changes that in-memory reranking step, which affects gateway responsiveness during broad searches but not persisted memory data or configuration. flowchart LR
A[Memory search query] --> B[Hybrid candidate retrieval]
B --> C[MMR diversity reranking]
C --> D[Running similarity maximum]
D --> E[Ranked memory chunks]
E --> F[Agent search result]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -12, Tests +68. Total +56 across 2 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Refresh the branch onto current main, preserve the running-maximum algorithm and reference-ranking regression, then merge only after focused Memory Core review and required checks pass on that exact head. Do we have a high-confidence way to reproduce the issue? Unclear: the supplied report provides a concrete broad-search scenario, benchmark, and reference implementation, but a high-confidence current-main source review could not be run because the command sandbox failed. Is this the best way to solve the issue? Unclear: the running-maximum approach is plausibly equivalent and is supported by supplied benchmark and regression evidence, but the current code, callers, and feature history could not be independently inspected. AGENTS.md: unclear because the file could not be read completely. Codex review notes: model internal, reasoning high; reviewed against a88c4283ad48. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
Real behavior proofAdding inspectable artifacts per the review request. Everything below is reproducible; the one non-reproducible measurement is labeled as such. 1. Reproducible benchmark (primary evidence)Self-contained — synthetic pools, no private data. Save as // Reproducible benchmark for the MMR running-max optimization.
//
// Run: npx tsx extensions/memory-core/src/memory/mmr.bench.ts
//
// Compares the previous algorithm (recompute max-similarity-to-selected from
// scratch on every selection round) against the current running-max
// implementation, across candidate-pool sizes. Both produce identical
// rankings; only the work differs. Synthetic corpus so anyone can reproduce.
import { applyMMRToHybridResults } from "./mmr.js";
import { jaccardSimilarity, tokenize } from "./tokenize.js";
type Item = { path: string; startLine: number; endLine: number; score: number; snippet: string };
// Build a pool with heavy token overlap between candidates — the shape that
// makes diversity re-ranking expensive (shared vocabulary across documents).
function makePool(size: number): Item[] {
const topics = ["strategy", "systems", "collaboration", "trust", "understanding", "creative"];
return Array.from({ length: size }, (_, i) => ({
path: `/doc-${i}.md`,
startLine: i,
endLine: i,
score: 1 - i / (size * 2),
snippet: [
topics[i % topics.length],
topics[(i + 1) % topics.length],
topics[(i + 2) % topics.length],
`shared context paragraph ${i % 7}`,
`distinct token ${i}`,
].join(" "),
}));
}
// The pre-optimization algorithm, preserved for comparison: for every
// selection round, rescan every remaining candidate against every already
// selected item. O(n^3) in pool size.
function legacyMmrRerank(items: Item[], lambda: number): Item[] {
const tokenCache = new Map(items.map((it) => [it.path, tokenize(it.snippet)]));
const maxScore = Math.max(...items.map((i) => i.score));
const minScore = Math.min(...items.map((i) => i.score));
const range = maxScore - minScore;
const selected: Item[] = [];
const remaining = new Set(items);
while (remaining.size > 0) {
let best: Item | null = null;
let bestScore = -Infinity;
for (const candidate of remaining) {
let maxSim = 0;
for (const sel of selected) {
maxSim = Math.max(
maxSim,
jaccardSimilarity(tokenCache.get(candidate.path)!, tokenCache.get(sel.path)!),
);
}
const normalized = range === 0 ? 1 : (candidate.score - minScore) / range;
const mmr = lambda * normalized - (1 - lambda) * maxSim;
if (mmr > bestScore || (mmr === bestScore && candidate.score > (best?.score ?? -Infinity))) {
best = candidate;
bestScore = mmr;
}
}
if (!best) break;
selected.push(best);
remaining.delete(best);
}
return selected;
}
function timeIt(fn: () => unknown): number {
const t0 = performance.now();
fn();
return performance.now() - t0;
}
const LAMBDA = 0.5;
const SIZES = [40, 80, 120, 160, 200];
console.log(`node ${process.version}`);
console.log(`lambda=${LAMBDA}, synthetic pools with overlapping token sets\n`);
console.log("pool | before (rescan) | after (running-max) | speedup | ranking");
console.log("-----|-----------------|---------------------|---------|--------");
for (const size of SIZES) {
const pool = makePool(size);
// warm both paths so we compare steady-state, not JIT warmup
legacyMmrRerank(pool, LAMBDA);
applyMMRToHybridResults(pool, { enabled: true, lambda: LAMBDA });
let before = Infinity;
let after = Infinity;
for (let run = 0; run < 3; run++) {
before = Math.min(before, timeIt(() => legacyMmrRerank(pool, LAMBDA)));
after = Math.min(
after,
timeIt(() => applyMMRToHybridResults(pool, { enabled: true, lambda: LAMBDA })),
);
}
const legacyOrder = legacyMmrRerank(pool, LAMBDA).map((i) => i.path);
const currentOrder = applyMMRToHybridResults(pool, { enabled: true, lambda: LAMBDA }).map(
(i) => i.path,
);
const identical =
legacyOrder.length === currentOrder.length &&
legacyOrder.every((p, idx) => p === currentOrder[idx]);
console.log(
`${String(size).padStart(4)} | ${before.toFixed(1).padStart(13)}ms | ${after
.toFixed(1)
.padStart(17)}ms | ${(before / after).toFixed(1).padStart(6)}x | ${
identical ? "identical" : "DIFFERS"
}`,
);
}Verbatim output: Superlinear growth before, near-linear after, and the ranking is identical at every size — the equivalence and the speedup demonstrated in the same run. 2. Test suite — this PR branch (adapted to current
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
The “Persistent data-model change detected” flag does not apply here. This change only updates the in-memory MMR reranking loop and its behavioral test; it does not read or write persisted schemas, configuration, embeddings, or metadata. No persisted state is touched, so there is no migration or upgrade-compatibility surface. |
* origin/main: (561 commits) refactor(plugins): reuse prepared channel discovery (openclaw#114942) fix(discord): reject mismatched reply context (openclaw#114716) fix(auto-reply): keep fast approval result private fix(auto-reply): satisfy approval boundary checks fix(imessage): unblock text approval fallback fix(imessage): keep approval test resets internal fix(gateway): narrow channel approval runtime types fix(imessage): resolve approval controls safely fix(imessage): harden native approval polls feat(imessage): add native poll approval controls fix(mac): bound node worker crash retries (openclaw#114974) fix(channels): keep running-channel connectivity tri-state (openclaw#114970) feat(ui): expand the Lobsterdex with 14 palettes, lore tooltips, and a collection page (openclaw#114959) fix(agents): honor models.providers auth mode pin in credential eligibility (openclaw#114944) fix(apps): fence stale mobile delivery state test(pr): provide ripgrep surface in review harness (openclaw#114958) fix(code-mode): bound and simplify worker lifecycles (openclaw#114945) fix(mattermost): prevent hook-controlled preview leaks fix(tool-display): avoid recursive search summaries (openclaw#114933) perf(catalog): memoize probes and single-flight identical list requests (openclaw#114961) ...
* origin/main: (150 commits) fix: preserve skill proposals across apply crashes and workspace moves (openclaw#114535) fix(qa): run maturity Docker scenarios through the aggregate scheduler (openclaw#114447) refactor(cli): unify configured model rows onto the shared row pipeline (openclaw#115239) fix(ui): stop modal autofocus steal after the open animation (openclaw#115168) fix(process): preserve long supervisor timeout deadlines (openclaw#115230) fix(slack): preserve pasted inbound tables (openclaw#115163) fix(codex): restore trajectory capture for canonical session targets (openclaw#115220) refactor(qa): make scenario selection taxonomy-owned (openclaw#114055) feat(plugins): match shared models across vendor-namespaced catalog ids (openclaw#115210) fix(ios): forgetting a paired gateway does nothing (openclaw#114083) test(ui): share pauseVirtualClock e2e helper and de-flake marquee hover-delay asserts (openclaw#115203) fix(docs): preserve pure fenced translation chunks (openclaw#115204) fix: keep shared web and TUI chats synchronized under load (openclaw#115191) fix(auto-reply): require a directed turn for the no-visible-reply fallback fix(auto-reply): attest source-routed message-tool sends via the dedupe route matcher fix(auto-reply): attest message-tool source replies in every delivery mode and gate eligibility on resolved settlement fix(auto-reply): bound turn-ledger settlement and treat started sends as conservatively visible fix(auto-reply): abort-aware fallback settlement and straggler drain in turn ledger fix(auto-reply): keep turn-ledger types module-local test(auto-reply): fix type-check errors in turn-ledger corner tests ...
|
Maintainer verification on
The first CI attempt had two unrelated 120s timeouts in watcher/self-heal tests under the concurrent memory shard; neither file is changed by this PR, and the full Memory Core run is green. I retried only that failed shard. |
* origin/main: (62 commits) feat(macos): enable Computer Control by default and diagnose stale Accessibility grants (openclaw#115280) fix(qa): restore full-stack scenarios and truthful suite exits (openclaw#115290) feat(memory): backfill past sessions from Control UI (openclaw#115266) docs: link macOS onboarding pages to app download (openclaw#111361) feat(skills): shared authoring standards make learned skills routable (openclaw#115103) fix(matrix): suppress previews for modifying hooks fix: prevent node gateway hangs and runaway local inference (openclaw#115248) refactor(ui): adopt @lit/task across remaining page surfaces (openclaw#115274) fix(slack): cap chat.update edit text at the 4000-char limit, not the 8000 send limit (openclaw#115027) [AI-assisted] docs: recommend Node 26 in quickstart, landing, and platform install docs (openclaw#115064) refactor(workboard): tidy Control UI card execution helpers (openclaw#115195) perf(agents): amortize history-limit eviction with hysteresis (openclaw#115273) (openclaw#115281) fix: schema-version refusal blames a downgrade that never happened and cannot identify the stale install (openclaw#115232) fix: restore Fish completion after global CLI options (openclaw#115222) refactor(agents): collapse the client-tool catalog branch (openclaw#115212) fix(macos): signed rebuild no longer stalls on app shutdown (openclaw#103957) fix(agents): prevent repeated Code Mode output across waits (openclaw#115213) refactor(ui): split Profile (identity) from Usage (statistics) (openclaw#115245) fix(channels): report a channel that cannot receive as unhealthy instead of connected (openclaw#115229) fix(cli): reject malformed infer model refs (openclaw#115225) ...
|
Refreshed the PR onto current main and pushed exact head Maintainer proof on that head:
Remote proof: https://github.com/openclaw/openclaw/actions/runs/30381776842 The earlier two 120s GitHub failures were runner-topology timeouts in unchanged Memory Core tests. Both passed on the refreshed full-suite run; the PR now includes main's compact CI topology. |
|
The exact-head CI failure on Pushed Proof on a four-core-constrained, two-process reproduction:
Remote proof: https://github.com/openclaw/openclaw/actions/runs/30383776395 |
|
Thanks for refreshing onto main and taking the CI topology on directly. Flagging the remaining red on
The 240s per-test limits went to the self-heal and watcher-config tests; this is a third file with the same shape. One piece of context that may argue for a broader fix: the other shard in that same job, Two options, and I'd defer to whichever fits the repo's conventions:
Happy to push either — just say which and I'll do it. To be explicit: none of this touches the MMR change itself, and I appreciate you running the independent verification on it. |
|
Replaced the per-test timeout experiment with the canonical fix at exact head Exact failed-shard reproduction under a four-core CPU cap, original 120s test limits, serial plan:
Remote shard proof: https://github.com/openclaw/openclaw/actions/runs/30385100338 |
|
Final exact head: The compact full-suite failure on the prior head was an unrelated Four-core exact group proof:
Remote proof: https://github.com/openclaw/openclaw/actions/runs/30388565844 |
* origin/main: (61 commits) perf(ui): debounce event-driven session list refreshes and right-size child paging (openclaw#115374) feat(talk): support GPT-Live realtime voice over ChatGPT OAuth (openclaw#115226) feat(system-agent): guide gateway configuration in Ask OpenClaw (openclaw#115363) fix(agents): make overflow recovery append-only via branch-and-reappend (openclaw#115271) (openclaw#115310) fix(macos): bound websocket ping so a dropped pong cannot orphan its continuation (openclaw#115362) fix(codex): isolate native hook relay startup (openclaw#115078) fix(ci): stop reviving superseded pull request workflows (openclaw#115378) feat(openshell): add workspace selection (openclaw#114952) fix(skills): persist workshop apply reason; correct Skill Workshop docs (openclaw#114471) fix: agent stops replying when a session transcript has no header row (openclaw#115080) perf(usage): stale-while-revalidate caches for usage.status and sessions.usage (openclaw#115369) fix(discord): reject invalid UTF-8 probe responses (openclaw#111734) feat(gateway): add memory.search operator method (openclaw#115346) fix(android): keep welcome action reachable with large text (openclaw#111747) fix(gateway): validate doctor memory agent ids (openclaw#115365) refactor: harden shell completion and shard Control UI E2E (openclaw#115332) fix(ui): anchor the thread branches menu to its trigger button (openclaw#115352) perf(sessions): incremental snapshot revalidation and shallow list projections (openclaw#115359) refactor(sessions): consolidate entry state (openclaw#115299) feat(ui): swap three plain Lobsterdex palettes for balloon, ascii, and portal (openclaw#115308) ...
|
Merged via squash.
|
…etwork-none * origin/main: (74 commits) fix(ui): make Control UI ownership and permissions reliable (#115364) feat(system-agent): host memory import in Ask OpenClaw (#115376) fix(chat): preserve literal Markdown image examples (#113904) refactor(chat): keep web and terminal sessions synchronized (#115377) fix(ui): order model picker by provider strength (#115380) feat(ui): make Memory settings a destination page with live overview and dreams (#115383) docs(security): fix warning line wrap (#115388) fix(memory-core): avoid cubic MMR similarity rescans (#113359) fix(discord): preserve code-leading reasoning chunks (#103166) fix(slack): protect outbound hooks from previews fix(ui): keep explicit navigation ahead of chat canonicalization (#115366) fix(exec): safely cancel pending node approvals (#115373) fix: make Code Mode reliable across gateway and provider lifecycles (#115379) perf(ui): debounce event-driven session list refreshes and right-size child paging (#115374) feat(talk): support GPT-Live realtime voice over ChatGPT OAuth (#115226) feat(system-agent): guide gateway configuration in Ask OpenClaw (#115363) fix(agents): make overflow recovery append-only via branch-and-reappend (#115271) (#115310) fix(macos): bound websocket ping so a dropped pong cannot orphan its continuation (#115362) fix(codex): isolate native hook relay startup (#115078) fix(ci): stop reviving superseded pull request workflows (#115378) ... # Conflicts: # CHANGELOG.md
* fix(memory): avoid cubic MMR similarity rescans * style(memory-core): oxfmt mmr.test.ts * test(memory-core): allow packed CI integration tests * fix(ci): serialize targeted memory-core tests * fix(ci): pin agentic cli worker count --------- Co-authored-by: Vincent Koc <[email protected]>
Fixes #113358
What Problem This Solves
mmrRerankrecomputed each remaining candidate's Jaccard similarity against every previously selected item on every selection round — O(rounds × candidates × selected × tokens), effectively cubic in candidate-pool size. On a mature corpus withhybrid.mmr.enabled=trueandcorpus=all(manager candidate pools up to 200), this synchronously blocked the gateway event loop for 2–5 minutes at ~100% CPU; the search's own 75s timeout could not fire because its timer lives on the same starved loop. Full analysis, reproduction recipe, and profiles in #113358.How
Running-max formulation: each candidate keeps its maximum similarity to the selected set in a
Map; when an item is selected, each remaining candidate is compared against only the newly selected item and its running max is updated. Exact same MMR semantics at O(n²).Ranking Equivalence
The new test
preserves the reference MMR ranking while caching running similaritiescompares the production path against a from-scratch reference implementation (the pre-optimization recompute-every-round algorithm) across λ ∈ {0, 0.3, 0.5, 0.7, 0.95} on a 24-item pool with overlapping token sets — orderings are identical.Evidence
The benchmark script is self-contained (synthetic pools, no private data) and can be run by anyone to verify both the speedup and the ranking equivalence. Full script + verbatim output are in a comment on this PR.
Cubic growth before, near-linear after, identical rankings at every pool size (node v25.9.0, lambda=0.5).
Field Observation (Not Independently Reproducible)
On the deployment where this was found, the isolated MMR stage measured ~1,841ms at a 200-candidate pool before the change and ~31.7ms after. Those figures came from an ad-hoc script against a private corpus that no longer exists on disk, so they are reported as a field observation only — the reproducible benchmark above is the evidence for review. Real chunk text is substantially longer than the synthetic snippets, which is why absolute timings there exceed the synthetic run while the scaling shape matches.
Testing
extensions/memory-core/src/memory/mmr.test.ts: 5/5 on this branch (main's existing suite + the new equivalence regression).release/2026.7.1(27/27 there, full build green); running in production on our deployment since — three consecutive formerly-seizing broad searches now complete in seconds with the MMR stage at 31–773ms.