Skip to content

FIX avoid exponential traversal of shared __id__ subtrees - #569

Open
3urek4 wants to merge 2 commits into
skops-dev:mainfrom
3urek4:fix-shared-subtree-traversal
Open

3urek4 wants to merge 2 commits into
skops-dev:mainfrom
3urek4:fix-shared-subtree-traversal

Conversation

@3urek4

@3urek4 3urek4 commented Nov 28, 2026

Copy link
Copy Markdown

Reference Issues/PRs

Related to #549 and #566.

What does this implement/fix? Explain your changes.

get_tree() memoizes nodes by __id__, so multiple parent states sharing the same __id__ resolve to the same Node instance (forming a DAG). Currently:

  1. Node.get_unsafe_set() recomputes shared subtrees on every visit without caching, and
  2. walk_tree() only tracks _ancestors (true cycles from FEAT support circular pointers #549), re-expanding non-circular shared subtrees along every path ($O(2^k)$ on $k$ levels of shared container references).

This PR:

  • Caches Node.get_unsafe_set() per node whenever its traversal does not short-circuit on an active ancestor above the current node (preserving exact results inside cycles).
  • Tracks visited container/object nodes in walk_tree() so subsequent occurrences of a shared non-empty subtree are rendered once with a (shared reference) marker without re-walking their children.

Any other comments?

None.

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR and working on this @3urek4 . I ran my review skill on it, and here's a few things to note.

AI review. This review was written by an AI assistant, not by a human. Every point below was reproduced by running code against this PR's head (a3dca6f) and against main (91fa468), but please push back on anything that looks wrong.

Thanks for the PR. First what holds up: the cache never changes an audit answer. get_untrusted_types and loads(trusted=...) gave the same results as main on about 12,000 hand-crafted schemas (shared __id__s, cycles through every node type) and on 136 real dumps, and an audit that is aborted half-way leaves no stale state behind.

Three things should be addressed before merging, with details in the inline comments:

  1. Sharing combined with a cycle is still exponential. One reference back to the root keeps every level uncached.
  2. Each node now keeps its own copy of its unsafe set, so peak memory during the audit can grow quadratically with the file. This is new compared to main.
  3. The new complexity test asserts results but no cost. It still passes with the cache removed, only a few minutes slower.

One change would cover 1 and 2: a single walk per top-level call that carries a visited set, instead of a cached set per node. It would also remove the depth / min_loop bookkeeping. That was only tried as an in-process prototype, not as a patch, so take it as a direction rather than a tested design; the first inline comment lists what it has to take care of.

The smaller points are inline as well: one more test for the cycle logic, the (shared reference) marker in visualize, and the changelog entry.

Comment thread skops/io/_audit.py Outdated
)

my_min_loop = _unsafe_walk_state.min_loop
if my_min_loop >= depth:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A node whose walk reaches an ancestor that is still being computed is never cached. When the shared levels sit on a cycle, that is every level, and the traversal is as exponential as on main.

Reproducer: the diamond from the new test, with the leaf pointing back at the root.

script
import io
import json
import time
from zipfile import ZipFile

from skops.io import get_untrusted_types
from skops.io._protocol import PROTOCOL


def lst(content, id_):
    return {
        "__class__": "list",
        "__module__": "builtins",
        "__loader__": "ListNode",
        "__id__": id_,
        "content": content,
    }


def ref(id_):
    return {
        "__class__": "list",
        "__module__": "builtins",
        "__loader__": "CachedNode",
        "__id__": id_,
    }


def cyclic_diamond(depth):
    # the diamond from the test, but the leaf points back at the root
    state = lst([ref(depth)], 100)
    for idx in range(depth):
        state = lst([state, ref(state["__id__"])], idx + 1)
    state["protocol"] = PROTOCOL
    buf = io.BytesIO()
    with ZipFile(buf, "w") as zf:
        zf.writestr("schema.json", json.dumps(state))
    return buf.getvalue()


for depth in (14, 16, 18, 20):
    data = cyclic_diamond(depth)
    start = time.perf_counter()
    get_untrusted_types(data=data)
    print(depth, len(data), "bytes", f"{time.perf_counter() - start:.2f}s")
depth file size this PR main
14 3.0 KB 0.05 s 0.04 s
16 3.4 KB 0.21 s 0.16 s
18 3.8 KB 0.84 s 0.63 s
20 4.2 KB 3.38 s 2.50 s

Depth 22 takes 13 s on this PR. So this is not a regression, but one back-reference undoes the fix, and visualize and loads run the same audit. Like the diamond in the test, only a hand-crafted file has this shape.

Suggestion: one walk per top-level get_unsafe_set() call that carries a visited set, so that each distinct node is visited once whether it is shared, on a cycle, or both. A prototype of this audited the schema above at depth 200 in about a millisecond. What it needs to take care of:

  • the visited set has to travel without changing the no-argument get_unsafe_set() signature that the node subclasses override;
  • inner calls then return partial sets, so only the result of the top-level call may be cached on a node;
  • walk_tree calls is_safe() once per row, so that needs its own cheap path, for example a boolean walk that stops at the first unsafe node and caches per node. Otherwise visualize becomes quadratic.

Comment thread skops/io/_audit.py Outdated

my_min_loop = _unsafe_walk_state.min_loop
if my_min_loop >= depth:
self._unsafe_set = set(res)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every node stores its own copy of its unsafe set here, and line 266 copies it again on each hit, so peak memory during the audit can grow quadratically with the size of the file. main only holds the sets that are being built.

Reproducer: a list x of n objects of n different classes, plus n small lists that each hold a reference to x.

script
import io
import json
import tracemalloc
from zipfile import ZipFile

from skops.io import get_untrusted_types
from skops.io._protocol import PROTOCOL


def lst(content, **extra):
    return {
        "__class__": "list",
        "__module__": "builtins",
        "__loader__": "ListNode",
        "content": content,
        **extra,
    }


def shared_names(n):
    objs = [
        {"__class__": f"C{i}", "__module__": "mod", "__loader__": "ObjectNode"}
        for i in range(n)
    ]
    x = lst(objs, __id__=1)
    ref = {
        "__class__": "list",
        "__module__": "builtins",
        "__loader__": "CachedNode",
        "__id__": 1,
    }
    state = lst([x] + [lst([ref]) for _ in range(n)])
    state["protocol"] = PROTOCOL
    buf = io.BytesIO()
    with ZipFile(buf, "w") as zf:
        zf.writestr("schema.json", json.dumps(state))
    return buf.getvalue()


for n in (500, 1000, 2000):
    data = shared_names(n)
    tracemalloc.start()
    get_untrusted_types(data=data)
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    print(n, f"{len(data) / 1e6:.2f} MB file", f"peak {peak / 1e6:.1f} MB")
n file size this PR main
500 0.13 MB 10.5 MB 2.1 MB
1000 0.25 MB 37.3 MB 4.1 MB
2000 0.50 MB 140.2 MB 8.3 MB

The memory is released when the call returns, and this PR is far faster than main on the same file (0.2 s against 25 s at n=2000, with tracemalloc on), so on this input it is a trade of time for memory. The memory side is new, though.

The per-call walk suggested in the comment above needs no per-node sets at all: a prototype peaked at about 8 MB on this file. Sharing one frozenset between nodes would fix this shape, but not a chain in which each list references the previous one and adds one new name, because there every node's set is different.

Comment thread skops/io/_audit.py Outdated
my_min_loop = _unsafe_walk_state.min_loop
if my_min_loop >= depth:
self._unsafe_set = set(res)
_unsafe_walk_state.min_loop = min(saved_min_loop, my_min_loop)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is what tells the caller that its own result is incomplete too, and no test covers it. With min(saved_min_loop, my_min_loop) replaced by saved_min_loop, every test in test_audit.py and test_visualize.py still passes, yet the middle node of a three-node cycle is then cached as safe. The code as written is correct; only the test is missing. The existing cycle test has two nodes, where the node that meets the active ancestor is the one being asked.

def test_unsafe_set_cache_in_cycle_through_intermediate_node():
    # In a cycle A -> B -> C -> A where A also has an unsafe child, only C meets
    # the active ancestor A. B must learn through C that its own result is
    # incomplete: it must not be cached as safe.
    c: list[object] = []
    b: list[object] = [c]
    a: list[object] = [b, CustomType(1)]
    c.append(a)
    with ZipFile(io.BytesIO(dumps(a))) as zf:
        schema, load_context = read_schema(zf)
        tree_a = get_tree(schema, load_context, trusted=None)

    assert isinstance(tree_a, ListNode)
    tree_b = tree_a.content[0]
    assert isinstance(tree_b, ListNode)
    tree_c = tree_b.content[0]
    assert isinstance(tree_c, ListNode) and tree_c.content[0] is tree_a
    expected = {f"{CustomType.__module__}.CustomType"}
    assert tree_a.get_unsafe_set() == expected
    assert tree_b.get_unsafe_set() == expected
    assert tree_c.get_unsafe_set() == expected

It passes on this PR and on main, and fails on tree_b with the line changed as above.

Comment thread skops/io/tests/test_audit.py Outdated
loads(data)


def test_shared_subtrees_visited_once_during_audit_and_visualize():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test checks the results but not the cost, so it cannot catch the regression it is named after. With self._unsafe_set = set(res) replaced by pass it still passes; it takes about 3.5 minutes instead of milliseconds, and nothing in the project turns a slow test into a failing one. If the dedup in walk_tree regressed instead, list(walk_tree(tree)) would try to build 67 million rows before the == 51 assertion is reached.

Counting calls at a smaller depth makes both halves fail fast:

suggested test
def test_shared_subtrees_visited_once_during_audit_and_visualize(monkeypatch):
    # Each level holds two references to the next level's __id__, forming a
    # diamond DAG with 2^depth paths and depth + 1 distinct nodes. Both
    # get_untrusted_types and walk_tree must visit each distinct node a
    # constant number of times.
    depth = 16
    state: dict[str, object] = {
        "__class__": "int",
        "__module__": "builtins",
        "__loader__": "JsonNode",
        "content": "1",
        "__id__": 100,
    }
    for idx in range(depth):
        ref = {
            "__class__": state["__class__"],
            "__module__": state["__module__"],
            "__loader__": "CachedNode",
            "__id__": state["__id__"],
        }
        state = {
            "__class__": "list",
            "__module__": "builtins",
            "__loader__": "ListNode",
            "__id__": idx + 1,
            "content": [state, ref],
        }
    state["protocol"] = PROTOCOL

    buf = io.BytesIO()
    with ZipFile(buf, "w") as zf:
        zf.writestr("schema.json", json.dumps(state))
    data = buf.getvalue()

    calls = 0
    is_self_safe = ListNode.is_self_safe

    def counting_is_self_safe(self):
        nonlocal calls
        calls += 1
        return is_self_safe(self)

    monkeypatch.setattr(ListNode, "is_self_safe", counting_is_self_safe)

    assert get_untrusted_types(data=data) == []
    assert calls <= 2 * depth

    with ZipFile(io.BytesIO(data)) as zf:
        schema, load_context = read_schema(zf)
        tree = get_tree(schema, load_context, trusted=None)

    calls = 0
    # asking for one row more than expected bounds the work if dedup regresses
    rows = list(islice(walk_tree(tree), 2 * depth + 2))
    assert len(rows) == 2 * depth + 1
    assert calls <= 4 * depth

This passes on this PR and fails on main in about a second with assert 65535 <= (2 * 16). It needs from itertools import islice.

Comment thread skops/io/_visualize.py
# it is already a recursive call, i.e. child nodes will be checked many
# times. A solution to this would be to add caching to its call.
is_circular = id(node) in _ancestors
is_shared = not is_circular and id(node) in _visited

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This collapses every repeated node that has children, which changes the output for ordinary models too, not only for crafted files. For example:

pipe = Pipeline([("a", MinMaxScaler()), ("b", MinMaxScaler())]).fit(X)
sio.visualize(sio.dumps(pipe))

The second scaler now prints feature_range: builtins.tuple (shared reference) without its 0 / 1 rows, because both scalers hold the same default-argument tuple. A fitted VotingClassifier goes from 163 rows to 111 and a GridSearchCV from 103 to 86.

Nothing is lost: each collapsed subtree is printed in full once, above its marker, in all three show modes, and the marker is accurate, since loads restores these as one object. But the row does not say which earlier node it refers to, and for a small value like a 2-tuple the marker is longer than what it replaces. Two options:

  • keep the rule and document it (see the comment on the changelog), or
  • collapse only subtrees with more than a handful of rows. In a quick experiment, "more than 8 rows below" kept the 25-level diamond at 59 rows and restored the previous output for small tuples.

Not a blocker either way.

Comment thread skops/io/_visualize.py
suffix = (
" (circular reference)"
if is_circular
else " (shared reference)"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The marker is appended to NodeInfo.val, so a custom sink that reads val sees two different values for one type:

class Unsafe:
    def __init__(self):
        self.v = 1


u = Unsafe()
seen = []
sio.visualize(sio.dumps([u, u]), sink=lambda nodes, show, **kw: seen.extend(nodes))
sorted({n.val for n in seen if not n.is_self_safe})
# main:    ['__main__.Unsafe']
# this PR: ['__main__.Unsafe', '__main__.Unsafe (shared reference)']

This follows what (circular reference) already does, so it is consistent. The difference is that the circular marker only shows up for cyclic objects, while this one appears for ordinary files. A boolean field with a default on NodeInfo, with the sink printing the text, would keep val clean for both markers. That could be a follow-up.

Comment thread skops/io/_visualize.py Outdated
print(f" {node.key}: {label}")


def _has_visitable_children(node: Node) -> bool:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This helper restates the skip rules of walk_tree, and the two can disagree:

d = {"key_types": [1, 2]}
sio.visualize(sio.dumps([d, d]))
# root: builtins.list
# ├── content: builtins.dict
# └── content: builtins.dict (shared reference)

Nothing was shown under the first dict (children named key_types are hidden, which predates this PR), so the marker points at nothing. Marking a node as visited after its children were walked, and only if they produced at least one row, would remove the helper and fix this case. In a quick check the output was otherwise unchanged, including for both new tests.

Comment thread docs/changes.rst Outdated

v0.17
-----
- Avoid exponential traversal of shared subtrees referenced through the same

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things for this entry:

  • The other entries end with a reference and an author, for example :pr:`569` by :user:`Your Name <3urek4>`.
  • It reads as an internal fix, but visualize output changes for users (the (shared reference) rows). It would help to say that here in a sentence and to mention the marker in the visualize docstring. __id__ is an internal detail of the file format, so something like "shared objects" reads better in a changelog.

Best reworded once the points above are settled.

@3urek4

3urek4 commented Nov 29, 2026

Copy link
Copy Markdown
Author

Thanks for the detailed review and reproducers @adrinjalali. I have updated the PR to address the points raised:

  1. get_unsafe_set() and is_safe():
    • Replaced per-node set[str] caching and the depth / min_loop tracking with an iterative per-call visited walk in Node.get_unsafe_set(), keeping the zero-argument signature intact for subclass overrides.
    • Added a reachability pass in Node.is_safe() that populates the existing Node._is_safe boolean attribute across reachable nodes so repeated checks in walk_tree() stay O(V + E) without storing per-node type sets.
    • Tested against both reproducers locally: cyclic_diamond(200) finishes in under 1 ms, and shared_names(2000) peaks at ~8.2 MB.
  2. walk_tree() and docs:
    • Removed _has_visitable_children and only add id(node) to _visited after walking its children produces at least one row (covering the dict with only hidden key_types, added to test_visualize_shared_reference).
    • Kept the (shared reference) rule and documented it in visualize() and docs/changes.rst.
  3. Tests and coverage:
    • Switched the diamond test to count is_self_safe calls and bound walk_tree with islice (parametrized over both acyclic and cyclic diamonds), added the 3-node cycle intermediate-node test, and covered the remaining child branches in Node.get_unsafe_set for codecov/patch.

This branch has not been deployed

No deployments
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.

2 participants