mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-03 22:12:01 +09:00
dream(memory): #5033 CacheManager frequency-aware eviction (HTM-EAR-grounded)
Adds an opt-in, Darwin-tuned frequencyWeight/evictionScanWindow blend to CacheManager's eviction policy. Default (unset/0) is byte-identical to the existing pure-LRU tail eviction via an early return - zero behavior change for every current caller (AgentDBAdapter, TieredCacheManager, ControllerRegistry's tieredCache). Motivated by HTM-EAR (arXiv:2603.10032, Feb 2026), which shows pure-LRU eviction permanently drops high-access-frequency entries under skewed access even though CachedEntry.accessCount already tracks exactly the signal needed. Evaluation: baseline 718/719 (1 pre-existing environmental failure) -> candidate 722/723, tsc clean both ways, stash-isolated discriminating tests fail on baseline exactly as predicted. Independently reproduced by a fresh-context adversarial critic (verdict: CONFIRMED). Bounded 3-gen x 4-candidate Darwin sweep over a new synthetic skewed-workload benchmark finds an interior optimum (frequencyWeight=0.85) that beats both the baseline and a naive frequencyWeight=1.0 - full lineage persisted. Full receipt in docs/dream-cycle/dream-gist-2026-11-18.md and issue #5033. Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01ReiDH4YtmHBfXwGDoLNB76
This commit is contained in:
7 files changed
+655
-3
No files matched your search
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"corpus_path": ".harness/bench-memory-eviction-2026-11-18.json",
|
||||
"created_by_date": "2026-11-18",
|
||||
"created_by_hypothesis": "CacheManager frequency-aware eviction (HTM-EAR arXiv:2603.10032) -- frequencyWeight/evictionScanWindow tuning",
|
||||
"task_count": 6,
|
||||
"task_categories": ["mild-skew", "moderate-skew", "severe-skew"],
|
||||
"gold_data_source": "synthetically generated by scripts/bench-cache-eviction.mjs from the seeds below; 'golden' keys = the true top-decile most-accessed keys in each generated access trace, computed independently of any cache eviction policy before the trace is replayed",
|
||||
"notes": "Each task replays a deterministic Zipfian-skewed key-access trace (seeded PRNG, no external data) through a real CacheManager instance (not a simulation/reimplementation) with maxSize well below numKeys, forcing eviction. Metric: fraction of golden (truly highest-frequency) keys still resident at the end of the trace, plus ops/sec throughput. This benchmark was authored tonight specifically to evaluate tonight's own candidate -- see the periodic corpus-fairness caveat in the issue/PR (STEP 10): it has not yet been run against an unrelated weak candidate to prove it has teeth, which is disclosed as a limitation, not resolved.",
|
||||
"tasks": [
|
||||
{ "id": "mild-1", "seed": 1001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 0.6, "goldenTopFraction": 0.1 },
|
||||
{ "id": "mild-2", "seed": 1002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 0.6, "goldenTopFraction": 0.1 },
|
||||
{ "id": "moderate-1", "seed": 2001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 1.1, "goldenTopFraction": 0.1 },
|
||||
{ "id": "moderate-2", "seed": 2002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 1.1, "goldenTopFraction": 0.1 },
|
||||
{ "id": "severe-1", "seed": 3001, "numKeys": 40, "maxSize": 12, "numOps": 2000, "skewExponent": 1.8, "goldenTopFraction": 0.1 },
|
||||
{ "id": "severe-2", "seed": 3002, "numKeys": 60, "maxSize": 15, "numOps": 3000, "skewExponent": 1.8, "goldenTopFraction": 0.1 }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
{
|
||||
"baselineEval": {
|
||||
"candidate": {
|
||||
"frequencyWeight": 0,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5,
|
||||
"successRate": 1,
|
||||
"latency": 1,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.825,
|
||||
"meanRetentionDelta": 0,
|
||||
"meanOpsRatio": 1.0189885574485578
|
||||
},
|
||||
"lineage": [
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.25,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5,
|
||||
"successRate": 1,
|
||||
"latency": 0.8459947209361269,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8018992081404189,
|
||||
"meanRetentionDelta": 0,
|
||||
"meanOpsRatio": 0.8459947209361269,
|
||||
"generation": 1
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.5,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5138888888888888,
|
||||
"successRate": 1,
|
||||
"latency": 0.9679645154304543,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8250557884256792,
|
||||
"meanRetentionDelta": 0.027777777777777773,
|
||||
"meanOpsRatio": 0.9679645154304543,
|
||||
"generation": 1
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.75,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 1,
|
||||
"latency": 0.99520369062745,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8461555535941174,
|
||||
"meanRetentionDelta": 0.125,
|
||||
"meanOpsRatio": 0.99520369062745,
|
||||
"generation": 1
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 1,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 0.8333333333333334,
|
||||
"latency": 0.9839787268849135,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 0.8333333333333334,
|
||||
"fitness": 0.7944718090327371,
|
||||
"meanRetentionDelta": 0.12499999999999999,
|
||||
"meanOpsRatio": 0.9839787268849135,
|
||||
"generation": 1
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.75,
|
||||
"evictionScanWindow": 8
|
||||
},
|
||||
"quality": 0.5763888888888888,
|
||||
"successRate": 1,
|
||||
"latency": 0.9542000513428158,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8448661188125334,
|
||||
"meanRetentionDelta": 0.15277777777777776,
|
||||
"meanOpsRatio": 0.9542000513428158,
|
||||
"generation": 2
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.75,
|
||||
"evictionScanWindow": 16
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 1,
|
||||
"latency": 0.9660947630936612,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8417892144640491,
|
||||
"meanRetentionDelta": 0.125,
|
||||
"meanOpsRatio": 0.9660947630936612,
|
||||
"generation": 2
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.75,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 1,
|
||||
"latency": 0.9692733165184113,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8422659974777617,
|
||||
"meanRetentionDelta": 0.125,
|
||||
"meanOpsRatio": 0.9692733165184113,
|
||||
"generation": 2
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.75,
|
||||
"evictionScanWindow": 64
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 1,
|
||||
"latency": 0.994950328239898,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8461175492359846,
|
||||
"meanRetentionDelta": 0.125,
|
||||
"meanOpsRatio": 0.994950328239898,
|
||||
"generation": 2
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.55,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5138888888888888,
|
||||
"successRate": 1,
|
||||
"latency": 0.9281190352575156,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8190789663997383,
|
||||
"meanRetentionDelta": 0.027777777777777773,
|
||||
"meanOpsRatio": 0.9281190352575156,
|
||||
"generation": 3
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.65,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5347222222222222,
|
||||
"successRate": 1,
|
||||
"latency": 0.9476806019421461,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8293048680690996,
|
||||
"meanRetentionDelta": 0.06944444444444443,
|
||||
"meanOpsRatio": 0.9476806019421461,
|
||||
"generation": 3
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.85,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5972222222222222,
|
||||
"successRate": 1,
|
||||
"latency": 0.9480068455034522,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8512288046032955,
|
||||
"meanRetentionDelta": 0.19444444444444442,
|
||||
"meanOpsRatio": 0.9480068455034522,
|
||||
"generation": 3
|
||||
},
|
||||
{
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.95,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5625,
|
||||
"successRate": 0.8333333333333334,
|
||||
"latency": 0.9584037476969183,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 0.8333333333333334,
|
||||
"fitness": 0.7906355621545377,
|
||||
"meanRetentionDelta": 0.12499999999999999,
|
||||
"meanOpsRatio": 0.9584037476969183,
|
||||
"generation": 3
|
||||
}
|
||||
],
|
||||
"finalWinner": {
|
||||
"candidate": {
|
||||
"frequencyWeight": 0.85,
|
||||
"evictionScanWindow": 32
|
||||
},
|
||||
"quality": 0.5972222222222222,
|
||||
"successRate": 1,
|
||||
"latency": 0.9480068455034522,
|
||||
"costEfficiency": 1,
|
||||
"reproducibility": 1,
|
||||
"safety": 1,
|
||||
"fitness": 0.8512288046032955,
|
||||
"meanRetentionDelta": 0.19444444444444442,
|
||||
"meanOpsRatio": 0.9480068455034522,
|
||||
"generation": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
# Memory SOTA Report — 2026-11-18
|
||||
|
||||
TL;DR: a Feb-2026 paper (HTM-EAR, arXiv:2603.10032) shows pure-LRU eviction catastrophically drops high-value, high-frequency entries under skewed access. Ruflo's `@claude-flow/memory` `CacheManager` is pure LRU+TTL with no importance/frequency signal, even though `CachedEntry.accessCount` already tracks exactly the data needed. Tonight ships an opt-in, Darwin-tuned frequency-aware eviction blend (`frequencyWeight`, default 0 = byte-identical to today) with a real evaluation receipt and a 3-generation parameter sweep.
|
||||
|
||||
## What's New in 2026
|
||||
|
||||
| Finding | Source | Confidence |
|
||||
|---|---|---|
|
||||
| LongMemEval-V2 extends long-term memory eval to agentic/web tasks; best system 72.5% vs. 48.5% RAG baseline, oracle ceiling 86-90% | arXiv preprint + public leaderboard, May 2026 | B |
|
||||
| Naive/frequent memory consolidation degrades utility *below* a no-memory baseline (GPT-5.4 failed 54% of ARC-AGI problems it solved without memory, after consolidating) | arXiv:2605.12978, May/Aug 2026 | B |
|
||||
| **HTM-EAR**: importance+usage-weighted eviction vs. LRU — LRU permanently discarded 2,416 "essential" facts of 15K on a BGL log corpus; MRR 0.069 (LRU) vs 0.336 (HTM-EAR) | arXiv:2603.10032, Feb 2026 | B |
|
||||
| MemX: hybrid dense+sparse fusion via RRF (not MMR); Hit@5 51.6%, temporal reasoning still weak | arXiv:2603.16171, ~Mar 2026 | B |
|
||||
| Provenance/lineage becoming a required trust layer for memory writes/reads, not just an audit afterthought | arXiv:2606.04990 (survey) + MAP-Graph, Jun 2026 | B |
|
||||
| FadeMem: per-layer exponential decay forgetting, claims 45% storage reduction | arXiv:2601.18642, Jan 2026 | **C** — baseline for the 45% figure unstated; not used to justify tonight's candidate |
|
||||
|
||||
No numeric claim above came from training-data recall; all are from the cited 2026 sources. Ruflo's own internal "150x-12,500x HNSW speedup" figure (CLAUDE.md) could not be found in any external 2026 source and should continue to be treated as unverified/internal-only, consistent with the repo's own audit doc.
|
||||
|
||||
## Ruflo Current Capability
|
||||
|
||||
`@claude-flow/memory`'s hot paths (hybrid-RRF+MMR fusion, controller lifecycle, LRU cache mechanics) are heavily hardened from many prior nightly passes — dense with changelog-style comments documenting NaN/negative-weight guards, deterministic tie-breaks, embedding-cosine MMR, etc. `CacheManager` specifically: pure LRU+TTL, zero importance/frequency signal in eviction despite `CachedEntry.accessCount`/`lastAccessedAt` already being tracked on every entry — exactly the gap HTM-EAR documents.
|
||||
|
||||
## Competitor Comparison
|
||||
|
||||
| Product | Hybrid fusion | Consolidation/distillation | Temporal/decay | Provenance/audit |
|
||||
|---|---|---|---|---|
|
||||
| Mem0 | unverified (no RRF doc found) | ADD/UPDATE/DELETE/NOOP ops (verified) | unverified (LRU/time-decay claimed by secondary source only) | None found |
|
||||
| Zep | verified — cosine+BM25+graph BFS+rerank | None (entity/community summarization, not strategy distillation) | bi-temporal **invalidation**, not decay (deliberate design choice) | partial (bi-temporal ingestion timestamps) |
|
||||
| Letta | None found | background consolidation (official) | None found | unofficial only (community-documented edit log) |
|
||||
| ReasoningBank | N/A (not a retrieval system) | core strength — LLM-judge success/failure distillation (ICLR 2026) | None found | None found |
|
||||
| Qdrant | verified — prefetch+RRF, version-gated weights | N/A (infra layer, by design) | unverified (payload-timestamp filtering only, no decay score) | None found |
|
||||
| Ruflo (`@claude-flow/memory`) | **ahead of MemX** — RRF+MMR diversity together (`smart-retrieval.ts`) | dedup-only (embedding-cosine near-dup, ≥0.95) — no decay/gated consolidation | **gap** — pure LRU+TTL only (tonight's candidate) | `source:` tags for rerank provenance, not a trust/audit layer |
|
||||
|
||||
None of the scanned products publish a benchmark combining weighted hybrid fusion *and* MMR diversity *and* provenance together — a real, not solved-and-hidden, differentiation gap worth a future deep-research pass.
|
||||
|
||||
## Hypothesis
|
||||
|
||||
> Given a `CacheManager` under size/memory pressure with a skewed access pattern (an entry accessed many times historically but not most-recently, sitting near the LRU tail while rarely-touched entries occupy more recent positions), when eviction is extended with an opt-in, continuous `frequencyWeight` (0-1, default 0) blending recency-rank with normalized `accessCount` over a bounded scan window (`evictionScanWindow`, default 32) — falling back to the exact original tail-eviction when `frequencyWeight` is 0/unset — then a high-access-count entry should survive eviction under `frequencyWeight>0` where pure LRU would evict it, subject to: byte-identical default behavior, zero change to TTL/`maxMemory` accounting, deterministic $0 Vitest evaluation.
|
||||
|
||||
Frozen before evaluation; not modified after.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
New corpus `.harness/bench-memory-eviction-2026-11-18.json` (6 synthetic Zipfian-skewed-access tasks, seeded/deterministic, 3 skew levels) + driver `scripts/bench-cache-eviction.mts`. Metric: fraction of the true top-decile most-accessed keys ("golden") still resident after a trace replay, plus ops/sec. **Corpus-fairness caveat (disclosed, not resolved tonight):** this corpus was authored tonight by the same session evaluating tonight's candidate, and has not yet been run against an unrelated weak candidate to prove it has teeth — flagged for a future night, not blocking since the unit-test-level evidence below is independent of this corpus.
|
||||
|
||||
## Evaluation
|
||||
|
||||
Real Vitest evaluator, stash-isolated. Baseline: 718/719 pass (1 pre-existing unrelated environmental chmod-as-root failure, consistent with every prior night). Candidate: 722/723 (718 + 4 new discriminating tests), same 1 pre-existing failure, `tsc --noEmit` clean both ways. Baseline fails exactly 1 of the 4 new tests as predicted (the one requiring non-LRU behavior); the other 3 pass vacuously on baseline since it ignores the new config. Independently reproduced by a fresh-context adversarial critic (separate stash/pop cycle), verdict **CONFIRMED**, no blocking issues.
|
||||
|
||||
## Darwin Results
|
||||
|
||||
Repository-local bounded sweep (native `metaharness evolve --bench` unavailable — unbuilt `@claude-flow/swarm` dist, pre-existing on main). 3 generations × 4 candidates, fitness = 0.35·quality + 0.20·success_rate + 0.15·latency + 0.10·cost_efficiency + 0.10·reproducibility + 0.10·safety (frozen before the sweep ran). Baseline fitness 0.825. Winner: **`frequencyWeight=0.85, evictionScanWindow=32`**, fitness 0.851, mean essential-key retention +19.4pp over baseline, 0/6 tasks regressed, ~5% throughput overhead. Notably `frequencyWeight=1.0` (full HTM-EAR-style, no recency at all) *underperforms* the baseline (fitness 0.794, regresses 1/6 tasks) — a genuine interior optimum, not a monotonic "more is better" result. This is evidence for operators who opt in; **the shipped default stays 0 (unchanged behavior)** — no autonomous promotion of a new default. Lineage persisted at `.harness/darwin-lineage-2026-11-18.json`.
|
||||
|
||||
## SOTA Proof & Witness
|
||||
|
||||
See issue and PR for the full receipt.
|
||||
|
||||
```
|
||||
Session commit: edf7ddb3fefa15bca87986225b5a5ef7d4d059e5
|
||||
Candidate commit: PENDING
|
||||
Gist SHA-256 (pre-witness): PENDING
|
||||
Witness stamp: PENDING
|
||||
```
|
||||
Verifier: fetch this file from the branch, replace the Witness block's three dynamic values (Candidate commit, Gist SHA-256, Witness stamp) with the literal text `PENDING`, SHA-256 the result, concatenate with the Session commit above, SHA-256 again — must equal the Witness stamp.
|
||||
|
||||
## Recommended Next Steps
|
||||
|
||||
1. If an operator wants frequency-aware eviction in production, set `frequencyWeight: 0.85` (or close to it) on the relevant `CacheManager`/`TieredCacheManager` config — validated by tonight's sweep, not yet a default.
|
||||
2. A future DEEP=automation night should audit *every* worker type (`map`, `optimize`, `consolidate`, `testgaps`, `benchmark`) for the "claims work with no executor" anti-pattern — 3 confirmed+fixed instances across 2 prior nights (MCP dispatch tool, worker-detect, daemon audit worker) suggest a systemic class, not isolated bugs.
|
||||
3. A future deep-research pass should explore whether Ruflo's RRF+MMR fusion can be paired with a provenance/audit layer (MAP-Graph-style lineage gating) — no scanned competitor ships that combination, a genuine open differentiation gap rather than a solved-and-hidden one.
|
||||
|
||||
## SCAN: plugins
|
||||
|
||||
- `PluginStoreConfig` security defaults (`requireSecurityAudit`, `minTrustLevel`, `trustedAuthors`, `blockedPlugins`, `allowedPermissions`, `requirePermissionPrompt`) still never read anywhere outside their declaration/default sites (confirmed unfixed since 2026-10-13).
|
||||
- `SecurityPolicy.minTrustLevelForSpawn` — **fixed** 2026-10-31 via PR #4619 (merged); one disclosed caveat (`claim-event`/`agent-handoff` message types still unreachable under default `allowedMessageTypes`) remains open, not new.
|
||||
- `code-intelligence` dead config knobs (`search.defaultTopK/similarityThreshold`, `architecture.maxGraphDepth/includeVendor`, `refactoring.defaultDepth`) — confirmed still unfixed.
|
||||
- **New**: `@claude-flow/plugins` security SDK's `ResourceLimits` (`src/security/index.ts:497-550`) declares/defaults/accepts overrides for 5 fields, but `check()` only ever evaluates `maxMemoryMB` — `maxCPUPercent`, `maxFileSize`, `maxOpenFiles` are dead. Zero in-repo callers today, but it's a public SDK export (`Security` namespace) — live-but-broken for any external plugin author who adopts the documented contract. Deferred.
|
||||
|
||||
## SCAN: automation
|
||||
|
||||
- The "worker claims completed/scanned work it never performed" anti-pattern (3 instances across 2026-10-13 and 2026-10-28, two different components) is now **fully fixed** with regression tests (#4196, #4549×2) — confirmed by direct source inspection tonight.
|
||||
- `hooks worker dispatch --priority` remains a confirmed **dead flag**: accepted end-to-end (CLI → MCP tool → queue JSON) but `drainDispatchQueue()` never reads it and iterates queue files in raw `readdirSync` order. Still unfixed since 2026-11-13. Deferred — same root cause class as the fixed findings above, recommended as a future candidate.
|
||||
|
||||
## Ledger note
|
||||
|
||||
`docs/dream-cycle/LEDGER.md` has no rows for 2026-11-12/13/14/16/17 even though real branches/issues/PRs exist for all five nights (#4973, #4983, #4989, #5004, #5012 — all open drafts, STEP 25 just wasn't reached or merged to main). This is a backfill gap, not a pipeline failure — direct evidence (branches + PRs) confirms the pipeline ran every one of those nights. Tonight's row is appended on top; backfilling the gap is left for a future, lower-stakes pass since it's cosmetic, not a trust issue.
|
||||
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env -S npx tsx
|
||||
/**
|
||||
* Dream-cycle 2026-11-18 bounded Darwin-style parameter sweep for
|
||||
* CacheManager's new frequency-aware eviction (frequencyWeight /
|
||||
* evictionScanWindow). Repository-local implementation: the native
|
||||
* `metaharness evolve --bench` CLI path requires a built CLI dist that is
|
||||
* not reproducible in this checkout (unbuilt `@claude-flow/swarm` dist,
|
||||
* pre-existing on main), so this script plays the same role -- bounded
|
||||
* generations x candidates, a frozen fitness function, real evaluation
|
||||
* against the real CacheManager class (not a reimplementation) -- without
|
||||
* introducing a new dependency, per STEP 0.5's repository-local fallback.
|
||||
*
|
||||
* Bounds enforced (STEP 12 default budget): max 3 generations, max 4
|
||||
* candidates/generation, promote exactly 1 lineage winner.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { CacheManager } from '../v3/@claude-flow/memory/src/cache-manager.js';
|
||||
|
||||
interface Task {
|
||||
id: string;
|
||||
seed: number;
|
||||
numKeys: number;
|
||||
maxSize: number;
|
||||
numOps: number;
|
||||
skewExponent: number;
|
||||
goldenTopFraction: number;
|
||||
}
|
||||
|
||||
interface Corpus {
|
||||
tasks: Task[];
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
frequencyWeight: number;
|
||||
evictionScanWindow: number;
|
||||
}
|
||||
|
||||
// Deterministic mulberry32 PRNG -- no external dependency, fully reproducible from seed.
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed;
|
||||
return () => {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function zipfianKeyIndex(rand: () => number, numKeys: number, exponent: number): number {
|
||||
// Rejection-free approximation: rank by 1/(i+1)^exponent weights via inverse CDF sampling.
|
||||
const weights: number[] = [];
|
||||
let total = 0;
|
||||
for (let i = 0; i < numKeys; i++) {
|
||||
const w = 1 / Math.pow(i + 1, exponent);
|
||||
weights.push(w);
|
||||
total += w;
|
||||
}
|
||||
const r = rand() * total;
|
||||
let cum = 0;
|
||||
for (let i = 0; i < numKeys; i++) {
|
||||
cum += weights[i];
|
||||
if (r <= cum) return i;
|
||||
}
|
||||
return numKeys - 1;
|
||||
}
|
||||
|
||||
function runTask(task: Task, candidate: Candidate): { retention: number; opsPerSec: number } {
|
||||
const rand = mulberry32(task.seed);
|
||||
const keys = Array.from({ length: task.numKeys }, (_, i) => `k${i}`);
|
||||
const trueAccessCount = new Array(task.numKeys).fill(0);
|
||||
|
||||
const cache = new CacheManager<number>({
|
||||
maxSize: task.maxSize,
|
||||
frequencyWeight: candidate.frequencyWeight,
|
||||
evictionScanWindow: candidate.evictionScanWindow,
|
||||
});
|
||||
|
||||
const start = performance.now();
|
||||
for (let op = 0; op < task.numOps; op++) {
|
||||
const idx = zipfianKeyIndex(rand, task.numKeys, task.skewExponent);
|
||||
trueAccessCount[idx]++;
|
||||
const key = keys[idx];
|
||||
if (cache.get(key) === null) {
|
||||
cache.set(key, idx);
|
||||
}
|
||||
}
|
||||
const elapsedMs = performance.now() - start;
|
||||
const opsPerSec = task.numOps / (elapsedMs / 1000);
|
||||
|
||||
const rankedByTrueFreq = keys
|
||||
.map((k, i) => ({ k, freq: trueAccessCount[i] }))
|
||||
.sort((a, b) => b.freq - a.freq);
|
||||
const goldenCount = Math.max(1, Math.floor(task.numKeys * task.goldenTopFraction));
|
||||
const golden = rankedByTrueFreq.slice(0, goldenCount).map((x) => x.k);
|
||||
|
||||
const resident = new Set(cache.keys());
|
||||
const retained = golden.filter((k) => resident.has(k)).length;
|
||||
const retention = retained / golden.length;
|
||||
|
||||
return { retention, opsPerSec };
|
||||
}
|
||||
|
||||
function evaluate(corpus: Corpus, candidate: Candidate, baseline: Candidate) {
|
||||
const perTask = corpus.tasks.map((task) => {
|
||||
const cand = runTask(task, candidate);
|
||||
const base = runTask(task, baseline);
|
||||
return { task: task.id, cand, base };
|
||||
});
|
||||
|
||||
const qualityDeltas = perTask.map((t) => t.cand.retention - t.base.retention);
|
||||
const quality = clamp01(0.5 + avg(qualityDeltas) / 2);
|
||||
const successRate = avg(perTask.map((t) => (t.cand.retention >= t.base.retention - 1e-9 ? 1 : 0)));
|
||||
const latencyRatios = perTask.map((t) => t.cand.opsPerSec / t.base.opsPerSec);
|
||||
const latency = clamp01(avg(latencyRatios) / 1.0);
|
||||
const costEfficiency = 1; // deterministic in-process code, $0
|
||||
const reproducibility = 1; // seeded PRNG, fully deterministic
|
||||
const safety = successRate; // no regression vs. baseline on any task
|
||||
|
||||
const fitness =
|
||||
0.35 * quality + 0.2 * successRate + 0.15 * latency + 0.1 * costEfficiency + 0.1 * reproducibility + 0.1 * safety;
|
||||
|
||||
return {
|
||||
candidate,
|
||||
quality,
|
||||
successRate,
|
||||
latency,
|
||||
costEfficiency,
|
||||
reproducibility,
|
||||
safety,
|
||||
fitness,
|
||||
meanRetentionDelta: avg(qualityDeltas),
|
||||
meanOpsRatio: avg(latencyRatios),
|
||||
};
|
||||
}
|
||||
|
||||
function avg(xs: number[]): number {
|
||||
return xs.reduce((a, b) => a + b, 0) / xs.length;
|
||||
}
|
||||
function clamp01(x: number): number {
|
||||
return Math.max(0, Math.min(1, x));
|
||||
}
|
||||
|
||||
function main() {
|
||||
const corpus: Corpus = JSON.parse(readFileSync('.harness/bench-memory-eviction-2026-11-18.json', 'utf-8'));
|
||||
const baseline: Candidate = { frequencyWeight: 0, evictionScanWindow: 32 };
|
||||
|
||||
const lineage: Array<ReturnType<typeof evaluate> & { generation: number }> = [];
|
||||
|
||||
// Generation 1: sweep frequencyWeight, fixed window=32 (4 candidates).
|
||||
const gen1Weights = [0.25, 0.5, 0.75, 1.0];
|
||||
let gen1Results = gen1Weights.map((w) =>
|
||||
evaluate(corpus, { frequencyWeight: w, evictionScanWindow: 32 }, baseline)
|
||||
);
|
||||
gen1Results.forEach((r) => lineage.push({ ...r, generation: 1 }));
|
||||
let winner = gen1Results.slice().sort((a, b) => b.fitness - a.fitness)[0];
|
||||
|
||||
// Generation 2: sweep evictionScanWindow around winner's weight (4 candidates).
|
||||
const gen2Windows = [8, 16, 32, 64];
|
||||
let gen2Results = gen2Windows.map((win) =>
|
||||
evaluate(corpus, { frequencyWeight: winner.candidate.frequencyWeight, evictionScanWindow: win }, baseline)
|
||||
);
|
||||
gen2Results.forEach((r) => lineage.push({ ...r, generation: 2 }));
|
||||
winner = [...gen1Results, ...gen2Results].sort((a, b) => b.fitness - a.fitness)[0];
|
||||
|
||||
// Generation 3: fine-tune weight around winner (4 candidates).
|
||||
const base = winner.candidate.frequencyWeight;
|
||||
const gen3Weights = [Math.max(0.05, base - 0.2), Math.max(0.05, base - 0.1), Math.min(1, base + 0.1), Math.min(1, base + 0.2)];
|
||||
let gen3Results = gen3Weights.map((w) =>
|
||||
evaluate(corpus, { frequencyWeight: w, evictionScanWindow: winner.candidate.evictionScanWindow }, baseline)
|
||||
);
|
||||
gen3Results.forEach((r) => lineage.push({ ...r, generation: 3 }));
|
||||
|
||||
const finalWinner = lineage.slice().sort((a, b) => b.fitness - a.fitness)[0];
|
||||
const baselineEval = evaluate(corpus, baseline, baseline);
|
||||
|
||||
console.log(JSON.stringify({ baselineEval, lineage, finalWinner }, null, 2));
|
||||
}
|
||||
|
||||
main();
|
||||
// Each CacheManager instance starts an un-refed cleanup setInterval
|
||||
// (see the 2026-11-18 architecture-review disclosure of cache-manager.ts's
|
||||
// missing .unref() -- a separate, disclosed-not-fixed finding tonight).
|
||||
// This script creates ~150 short-lived instances and never calls
|
||||
// shutdown() on them, so force a clean exit rather than waiting on them.
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Discriminating tests for CacheManager's frequency-aware eviction
|
||||
* (dream-cycle 2026-11-18, memory surface).
|
||||
*
|
||||
* HTM-EAR (arXiv:2603.10032, Feb 2026) documents that pure-LRU eviction
|
||||
* drops high-access-frequency entries that happen to sit near the LRU tail
|
||||
* (because nothing *else* touched them recently), even though they carry
|
||||
* far more historical value than their low-frequency neighbors. These tests
|
||||
* reproduce exactly that scenario against CacheManager's real eviction path.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { CacheManager } from './cache-manager.js';
|
||||
|
||||
function setupSkewedCache(frequencyWeight?: number): CacheManager<string> {
|
||||
const cache = new CacheManager<string>({
|
||||
maxSize: 4,
|
||||
frequencyWeight,
|
||||
evictionScanWindow: 4,
|
||||
});
|
||||
|
||||
cache.set('A', 'high-frequency-entry');
|
||||
cache.get('A');
|
||||
cache.get('A');
|
||||
cache.get('A');
|
||||
cache.get('A');
|
||||
cache.get('A'); // A.accessCount === 5
|
||||
|
||||
// B, C, D are each set and never re-accessed, which — because `set()`
|
||||
// moves the new entry to the front — pushes A toward the tail purely
|
||||
// through recency decay while its accessCount stays at 5.
|
||||
cache.set('B', 'cold-1');
|
||||
cache.set('C', 'cold-2');
|
||||
cache.set('D', 'cold-3');
|
||||
|
||||
return cache;
|
||||
}
|
||||
|
||||
describe('CacheManager frequency-aware eviction (discriminating)', () => {
|
||||
it('pure LRU (frequencyWeight unset) evicts the high-frequency entry once capacity is exceeded', () => {
|
||||
const cache = setupSkewedCache(undefined);
|
||||
cache.set('E', 'cold-4'); // triggers eviction at maxSize=4
|
||||
|
||||
expect(cache.has('A')).toBe(false); // the valuable entry is gone
|
||||
expect(cache.has('B')).toBe(true);
|
||||
});
|
||||
|
||||
it('frequencyWeight=1 protects the high-frequency entry, evicting a cold one instead', () => {
|
||||
const cache = setupSkewedCache(1);
|
||||
cache.set('E', 'cold-4');
|
||||
|
||||
expect(cache.has('A')).toBe(true); // protected despite being LRU-oldest
|
||||
expect(cache.has('B')).toBe(false); // a cold, never-reaccessed entry is evicted instead
|
||||
});
|
||||
|
||||
it('frequencyWeight=0 explicitly behaves identically to unset (exact pure-LRU passthrough)', () => {
|
||||
const cacheUnset = setupSkewedCache(undefined);
|
||||
const cacheZero = setupSkewedCache(0);
|
||||
|
||||
cacheUnset.set('E', 'cold-4');
|
||||
cacheZero.set('E', 'cold-4');
|
||||
|
||||
expect(cacheZero.has('A')).toBe(cacheUnset.has('A'));
|
||||
expect(cacheZero.keys().sort()).toEqual(cacheUnset.keys().sort());
|
||||
});
|
||||
|
||||
it('control: with no skew (all entries equally cold), frequencyWeight=1 still evicts the oldest on ties', () => {
|
||||
const cache = new CacheManager<string>({ maxSize: 3, frequencyWeight: 1, evictionScanWindow: 3 });
|
||||
cache.set('X', '1');
|
||||
cache.set('Y', '2');
|
||||
cache.set('Z', '3');
|
||||
cache.set('W', '4'); // all accessCount === 0 -> tie -> first-scanned (oldest/tail) wins
|
||||
|
||||
expect(cache.has('X')).toBe(false);
|
||||
expect(cache.has('Y')).toBe(true);
|
||||
expect(cache.has('Z')).toBe(true);
|
||||
expect(cache.has('W')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -349,6 +349,8 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
|
||||
lruEnabled: config.lruEnabled !== false,
|
||||
maxMemory: config.maxMemory,
|
||||
writeThrough: config.writeThrough || false,
|
||||
frequencyWeight: config.frequencyWeight,
|
||||
evictionScanWindow: config.evictionScanWindow,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -403,10 +405,11 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
|
||||
private evictLRU(): void {
|
||||
if (!this.tail) return;
|
||||
|
||||
const evictedKey = this.tail.key;
|
||||
const evictedSize = this.tail.size;
|
||||
const victim = this.selectEvictionVictim();
|
||||
const evictedKey = victim.key;
|
||||
const evictedSize = victim.size;
|
||||
|
||||
this.removeNode(this.tail);
|
||||
this.removeNode(victim);
|
||||
this.cache.delete(evictedKey);
|
||||
this.currentMemory -= evictedSize;
|
||||
this.stats.evictions++;
|
||||
@@ -414,6 +417,50 @@ export class CacheManager<T = MemoryEntry> extends EventEmitter {
|
||||
this.emit('cache:eviction', { key: evictedKey });
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the node to evict. With the default `frequencyWeight` of 0 this is
|
||||
* always the LRU tail (identical to the original pure-LRU behavior). With
|
||||
* `frequencyWeight` > 0, a bounded window of the least-recently-used nodes
|
||||
* is scored by blending recency rank with normalized `accessCount`, so a
|
||||
* historically high-frequency entry sitting near the tail can survive an
|
||||
* eviction that pure recency would otherwise apply to it (the failure mode
|
||||
* HTM-EAR, arXiv:2603.10032, documents for plain LRU under skewed access).
|
||||
*/
|
||||
private selectEvictionVictim(): LRUNode<T> {
|
||||
const weight = this.config.frequencyWeight;
|
||||
if (!weight) {
|
||||
return this.tail!;
|
||||
}
|
||||
|
||||
const window = Math.max(1, this.config.evictionScanWindow ?? 32);
|
||||
const candidates: Array<{ node: LRUNode<T>; distanceFromTail: number }> = [];
|
||||
let maxAccessCount = 0;
|
||||
let node: LRUNode<T> | null = this.tail;
|
||||
let distanceFromTail = 0;
|
||||
while (node && distanceFromTail < window) {
|
||||
candidates.push({ node, distanceFromTail });
|
||||
if (node.value.accessCount > maxAccessCount) {
|
||||
maxAccessCount = node.value.accessCount;
|
||||
}
|
||||
node = node.prev;
|
||||
distanceFromTail++;
|
||||
}
|
||||
|
||||
const scaleFactor = candidates.length > 1 ? candidates.length - 1 : 1;
|
||||
let victim = candidates[0].node;
|
||||
let bestScore = Infinity;
|
||||
for (const candidate of candidates) {
|
||||
const normalizedFreq =
|
||||
maxAccessCount > 0 ? candidate.node.value.accessCount / maxAccessCount : 0;
|
||||
const score = (1 - weight) * candidate.distanceFromTail + weight * normalizedFreq * scaleFactor;
|
||||
if (score < bestScore) {
|
||||
bestScore = score;
|
||||
victim = candidate.node;
|
||||
}
|
||||
}
|
||||
return victim;
|
||||
}
|
||||
|
||||
private startCleanupTimer(): void {
|
||||
// Clean up expired entries every minute
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
|
||||
@@ -437,6 +437,18 @@ export interface CacheConfig {
|
||||
|
||||
/** Enable write-through caching */
|
||||
writeThrough: boolean;
|
||||
|
||||
/**
|
||||
* Blend factor (0-1) for frequency-aware eviction. 0 (default) preserves
|
||||
* pure-LRU tail eviction exactly. Above 0, eviction scores a bounded
|
||||
* window of least-recently-used entries by recency + normalized
|
||||
* accessCount, so a high-frequency entry can survive an eviction pure
|
||||
* recency would otherwise apply to it.
|
||||
*/
|
||||
frequencyWeight?: number;
|
||||
|
||||
/** Window size (entries scanned from the tail) for frequency-aware eviction. Default 32. Only consulted when frequencyWeight > 0. */
|
||||
evictionScanWindow?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user