Repository navigation
Conversation
adrinjalali
left a comment
There was a problem hiding this comment.
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:
- Sharing combined with a cycle is still exponential. One reference back to the root keeps every level uncached.
- 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. - 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.
| ) | ||
|
|
||
| my_min_loop = _unsafe_walk_state.min_loop | ||
| if my_min_loop >= depth: |
There was a problem hiding this comment.
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_treecallsis_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. Otherwisevisualizebecomes quadratic.
|
|
||
| my_min_loop = _unsafe_walk_state.min_loop | ||
| if my_min_loop >= depth: | ||
| self._unsafe_set = set(res) |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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() == expectedIt passes on this PR and on main, and fails on tree_b with the line changed as above.
| loads(data) | ||
|
|
||
|
|
||
| def test_shared_subtrees_visited_once_during_audit_and_visualize(): |
There was a problem hiding this comment.
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 * depthThis passes on this PR and fails on main in about a second with assert 65535 <= (2 * 16). It needs from itertools import islice.
| # 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 |
There was a problem hiding this comment.
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.
| suffix = ( | ||
| " (circular reference)" | ||
| if is_circular | ||
| else " (shared reference)" |
There was a problem hiding this comment.
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.
| print(f" {node.key}: {label}") | ||
|
|
||
|
|
||
| def _has_visitable_children(node: Node) -> bool: |
There was a problem hiding this comment.
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.
|
|
||
| v0.17 | ||
| ----- | ||
| - Avoid exponential traversal of shared subtrees referenced through the same |
There was a problem hiding this comment.
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
visualizeoutput changes for users (the(shared reference)rows). It would help to say that here in a sentence and to mention the marker in thevisualizedocstring.__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.
|
Thanks for the detailed review and reproducers @adrinjalali. I have updated the PR to address the points raised:
|
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 sameNodeinstance (forming a DAG). Currently:Node.get_unsafe_set()recomputes shared subtrees on every visit without caching, andwalk_tree()only tracks_ancestors(true cycles from FEAT support circular pointers #549), re-expanding non-circular shared subtrees along every path (This PR:
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).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.