perf(memory-graph): fix O(n^2) BFS queue drain in computeClusterAssignments (#1714)

This commit is contained in:
Thanniru Sai Teja 2026-10-12 21:43:20 -07:00 • committed by Mahesh Sanikommu
parent 35794564e4
commit 48bd3cc668
2 changed files with 22 additions and 2 deletions

View file

@ -140,6 +140,24 @@ describe("cluster assignments", () => {
expect(assignments.get("a1")?.key).toBe(assignments.get("b1")?.key)
})
it("merges a wide fan-out of memories relating to one hub into a single cluster", () => {
const hub = makeDocument("doc-hub", [makeMemory({ id: "hub" })])
const spokes = Array.from({ length: 200 }, (_, i) =>
makeDocument(`doc-${i}`, [
makeMemory({ id: `spoke-${i}`, memoryRelations: { hub: "derives" } }),
]),
)
const assignments = computeClusterAssignments([hub, ...spokes])
const hubKey = assignments.get("hub")?.key
expect(hubKey).toBeDefined()
for (let i = 0; i < spokes.length; i++) {
expect(assignments.get(`spoke-${i}`)?.key).toBe(hubKey)
}
expect(assignments.get("hub")?.size).toBe(spokes.length + 1)
})
})
describe("memory orbit placement", () => {

View file

@ -157,10 +157,12 @@ export function computeClusterAssignments(
const component: string[] = []
const queue = [startId]
// index dequeue: shift() is O(n) per call, O(n^2) on wide components
let head = 0
visited.add(startId)
while (queue.length > 0) {
const id = queue.shift() as string
while (head < queue.length) {
const id = queue[head++] as string
component.push(id)
for (const nextId of adjacency.get(id) ?? []) {
if (visited.has(nextId)) continue