Skip to content

fix(memory-core): avoid cubic MMR similarity rescans - #113359

Merged
vincentkoc merged 10 commits into
openclaw:mainfrom
christian-lallo:fix/mmr-cubic-rescan
Jul 28, 2026
Merged

vincentkoc merged 10 commits into
openclaw:mainfrom
christian-lallo:fix/mmr-cubic-rescan

Conversation

@christian-lallo

@christian-lallo christian-lallo commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #113358

What Problem This Solves

mmrRerank recomputed 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 with hybrid.mmr.enabled=true and corpus=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 similarities compares 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.

pool | before (rescan) | after (running-max) | speedup | ranking
  40 |           1.1ms |               0.3ms |    3.9x | identical
  80 |           8.8ms |               0.8ms |   11.4x | identical
 120 |          41.4ms |               1.7ms |   24.5x | identical
 160 |          95.8ms |               2.3ms |   41.1x | identical
 200 |         190.1ms |               3.6ms |   52.5x | identical

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).
  • Originally developed and verified on 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.
  • No config or API surface change; behavior identical by construction.

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 24, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 24, 2026
@clawsweeper

clawsweeper Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 28, 2026, 12:37 PM ET / 16:37 UTC.

ClawSweeper review

What this changes

This 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 readiness

⚠️ Needs maintainer review before merge - 2 items remain

This 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
Reviewed head: 23b2e40f96ac5e3a2a8a58d98dc0d8830d0a0b2e

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The reported behavior proof is strong, but independent current-head code and history review was blocked by the environment.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor supplied reproducible terminal benchmark output, a reference-ranking equivalence check, and reported after-fix production observations; the primary synthetic proof is self-contained and non-sensitive.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The contributor supplied reproducible terminal benchmark output, a reference-ranking equivalence check, and reported after-fix production observations; the primary synthetic proof is self-contained and non-sensitive.
Evidence reviewed 3 items PR evidence and scope: The supplied PR context shows a two-file patch limited to mmr.ts and mmr.test.ts, with a terminal benchmark and a reference-ranking regression test described in the PR body and contributor comment.
Related canonical report: The supplied related issue describes the same MMR rescanning event-loop blockage and this PR explicitly proposes the running-maximum repair for it.
Current review limitation: The required read-only repository inspection could not start: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted; therefore local code, history, scoped policy, and current-main behavior were not independently verified.
Findings None None.
Security None None.

How this fits together

Memory 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]
Loading

Before merge

  • Resolve merge risk (P1) - The PR is behind current main and the supplied GitHub state still showed required checks in progress; review and merge should target a refreshed head after those checks complete.
  • Complete next step (P2) - Current-head source review and pending-check completion are required before a safe merge verdict because the local inspection environment failed.
Agent review details

Security

None.

PR surface

Source -12, Tests +68. Total +56 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 15 27 -12
Tests 1 68 0 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 83 27 +56

Review metrics

None.

Stored data model

Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory/mmr.test.ts, unknown-data-model-change: extensions/memory-core/src/memory/mmr.ts, vector/embedding metadata: extensions/memory-core/src/memory/mmr.test.ts, vector/embedding metadata: extensions/memory-core/src/memory/mmr.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh mainline proof (recommended)
    Rebase or merge current main, then require the focused MMR regression and pending required checks to pass on the resulting head before merge.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Refresh the branch onto current main and verify the focused MMR regression plus required checks on the resulting head.

Technical review

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

Labels

Label changes:

  • add merge-risk: 🚨 availability: This patch changes the synchronous ranking loop implicated in gateway stalls, so its current-head validation matters before merge.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status no longer selects a status label.

Label justifications:

  • P1: The reported pre-fix MMR path can block the gateway event loop during broad memory searches.
  • merge-risk: 🚨 availability: This patch changes the synchronous ranking loop implicated in gateway stalls, so its current-head validation matters before merge.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor supplied reproducible terminal benchmark output, a reference-ranking equivalence check, and reported after-fix production observations; the primary synthetic proof is self-contained and non-sensitive.

Evidence

What I checked:

  • PR evidence and scope: The supplied PR context shows a two-file patch limited to mmr.ts and mmr.test.ts, with a terminal benchmark and a reference-ranking regression test described in the PR body and contributor comment. (extensions/memory-core/src/memory/mmr.ts:84, 23b2e40f96ac)
  • Related canonical report: The supplied related issue describes the same MMR rescanning event-loop blockage and this PR explicitly proposes the running-maximum repair for it. (extensions/memory-core/src/memory/mmr.ts:84, 23b2e40f96ac)
  • Current review limitation: The required read-only repository inspection could not start: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted; therefore local code, history, scoped policy, and current-main behavior were not independently verified.

Likely related people:

  • vincentkoc: The supplied PR commits show recent merges of main into the review branch by this contributor, but local feature-history inspection was unavailable. (role: recent area integrator; confidence: low; commits: 921b5a2f6c8f, 23b2e40f96ac; files: extensions/memory-core/src/memory/mmr.ts, extensions/memory-core/src/memory/mmr.test.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Refresh onto current main and let all required checks finish on that exact head.
  • Have a Memory Core owner confirm the running-maximum update against the current caller path.

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 (4 earlier review cycles)
  • reviewed 2026-07-24T15:52:06.982Z sha a5812bb :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-25T21:33:22.645Z sha 2b0aa01 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-25T22:16:05.056Z sha 2b0aa01 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-26T16:58:41.294Z sha 0e89c27 :: needs maintainer review before merge. :: none

@christian-lallo

Copy link
Copy Markdown
Contributor Author

Real behavior proof

Adding 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 extensions/memory-core/src/memory/mmr.bench.ts and run npx tsx extensions/memory-core/src/memory/mmr.bench.ts. It times the previous rescan algorithm against the running-max implementation and asserts the rankings match at every pool size. (Not committed, to keep the diff limited to the fix + its regression test.)

// 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:

$ npx tsx extensions/memory-core/src/memory/mmr.bench.ts
node v25.9.0
lambda=0.5, synthetic pools with overlapping token sets

pool | before (rescan) | after (running-max) | speedup | ranking
-----|-----------------|---------------------|---------|--------
  40 |           1.1ms |               0.3ms |    3.9x | identical
  80 |           8.8ms |               0.8ms |   11.4x | identical
 120 |          41.4ms |               1.7ms |   24.5x | identical
 160 |          95.8ms |               2.3ms |   41.1x | identical
 200 |         190.1ms |               3.6ms |   52.5x | identical

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 main)

$ npx vitest run extensions/memory-core/src/memory/mmr.test.ts

 RUN  v4.1.9 <checkout>

 Test Files  1 passed (1)
      Tests  5 passed (5)
   Start at  15:45:52
   Duration  296ms (transform 157ms, setup 182ms, import 20ms, tests 41ms, environment 0ms)

Includes the new preserves the reference MMR ranking while caching running similarities regression, which compares the production path against a from-scratch reference implementation across lambda values 0, 0.3, 0.5, 0.7, 0.95.

3. Test suite — original development branch (release/2026.7.1)

The change was developed and soaked against the 2026.7.1 release line, where the module exported mmrRerank directly and the suite is larger:

$ node --version
v25.9.0
$ pnpm --version
11.2.2
$ sw_vers -productName && sw_vers -productVersion && uname -m
macOS
26.5.1
arm64
$ git branch --show-current && git rev-parse --short=12 HEAD
release/2026.7.1
8c9cb67f4e19

$ pnpm exec vitest run extensions/memory-core/src/memory/mmr.test.ts

 RUN  v4.1.9 <checkout>

 Test Files  1 passed (1)
      Tests  27 passed (27)
   Start at  15:56:24
   Duration  191ms (transform 101ms, setup 86ms, import 14ms, tests 30ms, environment 0ms)

Exit code 0. Only the checkout path is redacted; deprecation and build-plugin timing warnings preceding the summary are omitted as they carry no behavioral evidence.

4. Note on the production figures

The PR body previously presented a benchmark table from the deployment where this was found (~1,841ms → ~31.7ms at a 200-candidate pool). Those measurements were real but came from an ad-hoc script against a private corpus that no longer exists, so they cannot be independently reproduced and have been relabeled as a field observation rather than evidence. The reproducible benchmark in §1 is what the review should rest on. Real chunk text is much longer than the synthetic snippets, which accounts for the larger absolute timings in the field while the scaling shape matches.

@christian-lallo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 24, 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: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 25, 2026
@christian-lallo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 25, 2026
@christian-lallo

Copy link
Copy Markdown
Contributor Author

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.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Jul 26, 2026
@vincentkoc vincentkoc self-assigned this Jul 28, 2026
* 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
  ...
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed 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. labels Jul 28, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Maintainer verification on 23b2e40f96ac5e3a2a8a58d98dc0d8830d0a0b2e:

  • reviewed the full MMR caller path and sibling exact/non-exact search paths; the running maximum is the correct owner-boundary fix and preserves ranking semantics
  • focused MMR regression: 5/5 passed across lambda 0, 0.3, 0.5, 0.7, and 0.95
  • full Memory Core: 78 files / 1,201 tests passed
  • deterministic 200-candidate benchmark: 209.377 ms reference vs 4.431 ms optimized (47.25x)
  • full build and full check passed; fresh autoreview is clean (0.97)

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)
  ...
@vincentkoc

Copy link
Copy Markdown
Member

Refreshed the PR onto current main and pushed exact head 91906d583b342bb1bef3383b30b22a7638354969.

Maintainer proof on that head:

  • full Memory Core suite: 79 files, 1,211 tests passed
  • scoped changed checks passed: formatting, extension production/test typechecks, lint, plugin boundaries, dependency/config guards, database-first guard, and runtime import-cycle check
  • focused MMR reference coverage passed across multiple lambda values
  • fresh pre-land review found no actionable issues (0.98 confidence)

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.

@vincentkoc

Copy link
Copy Markdown
Member

The exact-head CI failure on 91906d5 was isolated to two unchanged integration tests exceeding Vitest's global 120s cap when co-scheduled on a 4-vCPU worker (135.1s and 134.9s). Assertions and production behavior were not involved.

Pushed 9a35b713ad5d675ab00303f59a079b73e439b797 with per-test 240s limits for only those two integration tests, matching the existing Memory Core packed-CI precedent.

Proof on a four-core-constrained, two-process reproduction:

  • self-heal test: 3/3 passed; long case 80.5s
  • watcher config: 29/29 passed; long case 80.5s
  • MMR: 5/5 passed
  • scoped formatting, production/test types, lint, boundaries, database-first, and import-cycle checks passed
  • fresh review: no actionable issues (0.99 confidence)

Remote proof: https://github.com/openclaw/openclaw/actions/runs/30383776395

@christian-lallo

Copy link
Copy Markdown
Contributor Author

Thanks for refreshing onto main and taking the CI topology on directly.

Flagging the remaining red on 9a35b713 — it looks like the same class you just patched, but in a file outside that fix's scope.

checks-node-changed-2 (job) fails on:

extensions/memory-core/src/memory/manager.legacy-migration-cleanup.test.ts
Duration 175.61s → exit 1

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, extensions/memory-core/src/tools.citations.test.ts, passed at 100.31s — 83% of the 120s global cap. So the long tail of Memory Core integration tests generally sits close to the ceiling under 4-vCPU co-scheduling, and per-file limits may need extending again as timings drift.

Two options, and I'd defer to whichever fits the repo's conventions:

  • extend the same 240s per-test treatment to manager.legacy-migration-cleanup.test.ts, or
  • a suite-level testTimeout for Memory Core integration tests, which would stop this recurring

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.

@vincentkoc

Copy link
Copy Markdown
Member

Replaced the per-test timeout experiment with the canonical fix at exact head b5a8c8db03dd7dc23ad8097e0d597a1cbcf8c280: changed-test chunks containing Memory Core targets now set planConcurrency: 1, matching the existing compact-suite serialization policy. No test timeouts are changed in the final diff.

Exact failed-shard reproduction under a four-core CPU cap, original 120s test limits, serial plan:

  • all 12 target files passed
  • 211 tests passed across the shard
  • the three previously timing-out integration tests completed in 84s, 43s, and 51s
  • planner/runner tests: 32/32 passed
  • formatting, script declarations, extension/script/test types, extension/script lint, boundaries, and database-first/import-cycle checks passed
  • full branch autoreview: clean (0.96 confidence)

Remote shard proof: https://github.com/openclaw/openclaw/actions/runs/30385100338
Remote final check proof: https://github.com/openclaw/openclaw/actions/runs/30386258461

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Jul 28, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Final exact head: a33445210c2c564252c5101213491dcf4710db49.

The compact full-suite failure on the prior head was an unrelated agentic-cli child-process timeout: a three-worker group on a 4-core runner starved one TSX child past its 75s deadlock guard. The final patch pins that existing process-heavy compact group to the planner's established two-worker budget.

Four-core exact group proof:

  • CLI config: 179 files, 3,569 passed, 49 skipped
  • CLI process config: 4 files, 61 passed
  • previously killed unknown-command case passed in 35.7s
  • planner/runner tests: 53/53 passed
  • all scoped format, declarations, types, lint, boundaries, database-first, and import-cycle checks passed
  • final full-branch autoreview: clean (0.94 confidence)

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)
  ...
@vincentkoc
vincentkoc merged commit 811444d into openclaw:main Jul 28, 2026
120 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 28, 2026
…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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 29, 2026
* 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]>
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 merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

memory-core: MMR diversity re-ranking does O(n³) work and blocks the event loop for minutes on broad searches over large corpora

2 participants