Skip to content

traverseBFS: inner neighbor loop adds nodes without limit check, overshooting opts.limit #1087

Description

@inth3shadows

File: src/graph/traversal.ts
Lines: 65 (outer while guard), 99–112 (inner for loop)

Defect: traverseBFS checks nodes.size < opts.limit only in the outer while condition (L65). The inner for loop (L99–112) calls nodes.set(nextNode.id, nextNode) at L110 unconditionally for every unvisited neighbor, with no per-add limit check. When a single node has more neighbors than the remaining capacity, all are added in one pass — the outer guard only prevents the next dequeue, not the current batch.

Failure trace:

  • traverseBFS("A", { limit: 3 }): start node inserted before loop (nodes.size=1).
  • Dequeue A: nodes.size=1 < 3 → enter loop. A has 5 neighbors [B,C,D,E,F].
  • Inner for loop: nodes.set(B) (size=2), nodes.set(C) (size=3), nodes.set(D) (size=4), nodes.set(E) (size=5), nodes.set(F) (size=6) — all added, no limit check inside loop.
  • Outer while: nodes.size=6 >= 3 → exit. Result has 6 nodes despite limit=3.

Expected fix:
Add a limit check inside the inner for loop, either as a break or a guard before nodes.set:

for (const adjEdge of adjacentEdges) {
  if (nodes.size >= opts.limit) break;   // ← add this
  const nextNodeId = ;
  if (visited.has(nextNodeId)) continue;
  
  nodes.set(nextNode.id, nextNode);
  queue.push();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions