Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

perf(console): memory health analysis computed once per probe result, per-entry key work hoisted; bench-health.mjs

ruv4355f7bd8b8c
diff --git a/plugins/ruflo-console/hooks/data/memory-health.ts b/plugins/ruflo-console/hooks/data/memory-health.ts
index a27411189a..125185964f 100644
--- a/plugins/ruflo-console/hooks/data/memory-health.ts
+++ b/plugins/ruflo-console/hooks/data/memory-health.ts
@@ -99,10 +99,10 @@ const sizeClose = (a: number, b: number): boolean => Math.abs(a - b) <= SIZE_RAT
export type PairKind = 'exact' | 'near' | null
/** How two entries relate: the same normalised key and size (exact), similar key words and a close size (near), or not. */
-export function pairKind(a: HealthEntry, b: HealthEntry, tokensA: ReadonlySet<string>, tokensB: ReadonlySet<string>): PairKind {
+export function pairKind(a: HealthEntry, b: HealthEntry, tokensA: ReadonlySet<string>, tokensB: ReadonlySet<string>, normA: string = normaliseKey(a.key), normB: string = normaliseKey(b.key)): PairKind {
if (a.namespace === b.namespace && a.key === b.key) return null
- if (normaliseKey(a.key) === normaliseKey(b.key) && normaliseKey(a.key) !== '') return a.size === b.size ? 'exact' : 'near'
+ if (normA === normB && normA !== '') return a.size === b.size ? 'exact' : 'near'
return sizeClose(a.size, b.size) && jaccard(tokensA, tokensB) >= NEAR_JACCARD ? 'near' : null
}
@@ -145,7 +145,9 @@ function findClusters(entries: readonly HealthEntry[], pairCap: number): { clust
return root
}
+ // Per-entry work done once, not once per pair: the profile put the per-pair normaliseKey regex at the top of the cost.
const tokens = entries.map(entry => keyTokens(entry.key))
+ const norms = entries.map(entry => normaliseKey(entry.key))
let compared = 0
let reached = n
const pairKinds: { a: number; b: number; kind: 'exact' | 'near' }[] = []
@@ -163,7 +165,7 @@ function findClusters(entries: readonly HealthEntry[], pairCap: number): { clust
const entryA = entries[i]
const entryB = entries[j]
- const kind = entryA === undefined || entryB === undefined ? null : pairKind(entryA, entryB, tokens[i] ?? new Set(), tokens[j] ?? new Set())
+ const kind = entryA === undefined || entryB === undefined ? null : pairKind(entryA, entryB, tokens[i] ?? new Set(), tokens[j] ?? new Set(), norms[i], norms[j])
if (kind !== null) pairKinds.push({ a: i, b: j, kind })
}
diff --git a/plugins/ruflo-console/hooks/views/memory-health.ts b/plugins/ruflo-console/hooks/views/memory-health.ts
index 97d61265b5..2ee064644f 100644
--- a/plugins/ruflo-console/hooks/views/memory-health.ts
+++ b/plugins/ruflo-console/hooks/views/memory-health.ts
@@ -91,6 +91,25 @@ function consolidateRows(ctx: Ctx): RenderElement[] {
]
}
+/**
+ * The analysis is O(pairs) (up to PAIR_CAP, ~100 ms at the cap) and the view renders every frame, so it is computed once per
+ * probe result and per minute (the stale cutoff is the only thing the clock changes), never per frame.
+ */
+const reports = new WeakMap<HealthSample, { minute: number; report: HealthReport }>()
+
+export function reportFor(sample: HealthSample, nowMs: number): HealthReport {
+ const minute = Math.floor(nowMs / 60_000)
+ const cached = reports.get(sample)
+
+ if (cached !== undefined && cached.minute === minute) return cached.report
+
+ const report = analyseHealth(sample, nowMs)
+
+ reports.set(sample, { minute, report })
+
+ return report
+}
+
/** The health section's rows, or one honest line when the probe has not answered. */
export function healthRows(ctx: Ctx, now: () => number = () => ctx.nowMs): RenderElement[] {
const result = ctx.state.probes.get(HEALTH_PROBE)
@@ -100,7 +119,7 @@ export function healthRows(ctx: Ctx, now: () => number = () => ctx.nowMs): Rende
if (sample.entries.length === 0) return [text(ctx, ' no entries to analyse: store one, or import your Claude memories (IMPORT CLAUDE)', { dimColor: true })]
- const report = analyseHealth(sample, now())
+ const report = reportFor(sample, now())
const total = live<{ total?: number }>(ctx.state.probes.get('memory'))?.total
return [
diff --git a/plugins/ruflo-console/scripts/bench-health.mjs b/plugins/ruflo-console/scripts/bench-health.mjs
new file mode 100644
index 0000000000..5fdc136003
--- /dev/null
+++ b/plugins/ruflo-console/scripts/bench-health.mjs
@@ -0,0 +1,80 @@
+// @ts-check
+/**
+ * Memory health benchmark (ADR-457): the probe reader, the analysis (analyseHealth) and the view's rows (healthRows) at 1k and
+ * 10k entries, with a recording kit (the engine's layout is not in it). Median and p99 over N runs, and approximate bytes
+ * allocated per call (heapUsed delta over a batch after gc(); run with NODE_OPTIONS=--expose-gc, else the column reads n/a).
+ * The probe only ever reads HEALTH_CAP (1000) entries; 10k exercises the pair budget (PAIR_CAP) that bounds the worst case.
+ * NODE_OPTIONS=--expose-gc npx -y tsx plugins/ruflo-console/scripts/bench-health.mjs [runs]
+ */
+import { analyseHealth, memoryHealthProbe } from '../hooks/data/memory-health.ts'
+import { newState } from '../hooks/state.ts'
+import { healthRows } from '../hooks/views/memory-health.ts'
+
+const RUNS = Math.max(5, Number(process.argv[2]) || 25)
+const NOW = 1_800_000_000_000
+const DAY = 86_400_000
+const gc = /** @type {(() => void) | undefined} */ (globalThis.gc)
+
+/** Deterministic entries: ~1/9 share a topic stem (near duplicates), a few exact key collisions across namespaces. */
+const entries = (/** @type {number} */ n) =>
+ Array.from({ length: n }, (_, i) => ({
+ namespace: `ns${i % 7}`,
+ key: i % 50 === 0 ? `Shared/Key_${i % 100}` : `topic-${i % 90}-item-${i}${i % 9 === 0 ? '-v2' : ''}`,
+ size: 50 + (i % 40),
+ accessCount: i % 3,
+ updatedAtMs: NOW - (i % 120) * DAY,
+ createdAtMs: NOW - 200 * DAY,
+ }))
+
+const stat = (/** @type {() => unknown} */ fn) => {
+ fn()
+ const times = []
+
+ for (let i = 0; i < RUNS; i++) {
+ const t = process.hrtime.bigint()
+
+ fn()
+ times.push(Number(process.hrtime.bigint() - t) / 1e6)
+ }
+
+ times.sort((a, b) => a - b)
+
+ let bytes = 'n/a'
+
+ if (gc !== undefined) {
+ gc()
+
+ const before = process.memoryUsage().heapUsed
+
+ for (let i = 0; i < 5; i++) fn()
+
+ bytes = `${Math.max(0, Math.round((process.memoryUsage().heapUsed - before) / 5 / 1024))} KB`
+ }
+
+ return { median: times[Math.floor(times.length / 2)] ?? 0, p99: times[Math.min(times.length - 1, Math.floor(times.length * 0.99))] ?? 0, bytes }
+}
+
+const make = (/** @type {string} */ kind) => (/** @type {Record<string, unknown>} */ props) => ({ kind, props })
+const kit = { Box: make('Box'), Text: make('Text'), Button: make('Button'), Input: make('Input') }
+const act = new Proxy({}, { get: () => new Proxy({}, { get: () => () => undefined }) })
+const rows = []
+
+for (const n of [1000, 10_000]) {
+ const list = entries(n)
+ const json = JSON.stringify(list.map(e => ({ key: e.key, namespace: e.namespace, size: e.size, accessCount: e.accessCount, createdAt: new Date(e.createdAtMs).toISOString(), updatedAt: new Date(e.updatedAtMs).toISOString(), hasEmbedding: true })))
+ const sample = { listed: n, entries: list }
+ const state = newState({ boot: false })
+
+ state.probes.set('memory-health', /** @type {never} */ ({ value: sample, okAtMs: NOW, error: null, errorAtMs: null }))
+
+ const ctx = /** @type {never} */ ({ kit, state, act, columns: 120, nowMs: NOW, pictures: new Map() })
+ const report = analyseHealth(sample, NOW)
+
+ rows.push({ what: 'probe parse', n, ...stat(() => memoryHealthProbe.parse(json)), note: 'capped at 1000 entries' })
+ rows.push({ what: 'analyseHealth', n, ...stat(() => analyseHealth(sample, NOW)), note: `${report.pairsCompared} pairs, ${report.clusterCount} clusters${report.isTruncated ? ', budget hit' : ''}` })
+ rows.push({ what: 'healthRows (per frame)', n, ...stat(() => healthRows(ctx)), note: 'what a render pays' })
+}
+
+console.log('what n median ms p99 ms alloc/call note')
+
+for (const r of rows) console.log(`${r.what.padEnd(25)} ${String(r.n).padEnd(7)} ${r.median.toFixed(2).padStart(9)} ${r.p99.toFixed(2).padStart(8)} ${String(r.bytes).padStart(11)} ${r.note}`)
diff --git a/plugins/ruflo-console/tests/memory-health.spec.ts b/plugins/ruflo-console/tests/memory-health.spec.ts
index 1c565ae8b9..d76f4e93a5 100644
--- a/plugins/ruflo-console/tests/memory-health.spec.ts
+++ b/plugins/ruflo-console/tests/memory-health.spec.ts
@@ -157,3 +157,14 @@ describe('the analysis cost at the cap', () => {
expect(ms).toBeLessThan(5000)
})
})
+
+describe('the per-frame cost', () => {
+ it('computes the report once per sample and minute, not once per render', async () => {
+ const { reportFor } = await import('../hooks/views/memory-health')
+ const sample = { listed: 2, entries: [e('a', 'x-y', 10, 0, 1), e('b', 'x-y', 10, 0, 2)] }
+
+ expect(reportFor(sample, NOW)).toBe(reportFor(sample, NOW + 1000))
+ expect(reportFor(sample, NOW + 120_000)).not.toBe(reportFor(sample, NOW))
+ expect(reportFor({ ...sample }, NOW)).not.toBe(reportFor(sample, NOW))
+ })
+})