Skip to content

fix: coerce the child id in setParent cycle check - #271

Open
bardrop wants to merge 1 commit into
dagrejs:masterfrom
bardrop-oss:fix-setparent-numeric-cycle
Open

bardrop wants to merge 1 commit into
dagrejs:masterfrom
bardrop-oss:fix-setparent-numeric-cycle

Conversation

@bardrop

@bardrop bardrop commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What is wrong

setParent turns the parent id into a string, but not the child id. So the cycle check compares a string with a number and never matches when ids are numbers. graphlib supports number ids elsewhere (setNode(1), setEdge(1, 2), and the old JS test for setParent(2, 1)).

const g = new Graph({ compound: true });
g.setParent(1, 1);   // no error, node "1" is now its own parent
g.children();        // [] - the node is gone from the root

const h = new Graph({ compound: true });
h.setParent(1, 2);
h.setParent(2, 1);   // no error, "1" and "2" are each other's parent
h.setParent(3, 1);   // never returns: the ancestor loop goes 1 -> 2 -> 1 -> ...

Expected: both bad calls throw Setting ... would create a cycle, the same as with "1" and "2".

Cause

lib/graph.ts, setParent: parent += "" makes ancestor a string, but v stays a number, so ancestor === v is always false.

Fix

Turn v into a string too, at the top of setParent, before the check.

Test

  • Added "preserves the tree invariant for non-string ids" in test/graph-test.ts. It fails on master and passes with the fix.
  • npm test (283 passed), npm run typecheck and eslint on the changed files pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant