Skip to content

fix: guard sanitize_for_json against circular references - #515

Open
SarthakB11 wants to merge 1 commit into
sktime:mainfrom
SarthakB11:fix/189-sanitize-circular-ref
Open

fix: guard sanitize_for_json against circular references#515
SarthakB11 wants to merge 1 commit into
sktime:mainfrom
SarthakB11:fix/189-sanitize-circular-ref

Conversation

@SarthakB11

Copy link
Copy Markdown
Contributor

Closes #189.

Problem

sanitize_for_json recurses into dicts/lists/tuples/Series/DataFrames
with no cycle detection. An object graph containing a back-reference
(e.g. a dict that (indirectly) contains itself) blows the recursion
limit and crashes with RecursionError instead of returning any
usable response to the calling tool.

Fix

Track the id() of containers visited along the current recursion
path in a _seen set (passed as an internal-only kwarg, not part of
the public signature). On revisiting an already-seen container id,
return the placeholder string "<circular reference>" instead of
recursing again. Each recursive branch gets its own copy of _seen
(immutable set union), so sibling branches that legitimately share the
same nested object are not falsely flagged as circular.

Tests

Added 4 regression tests to tests/test_sanitize.py:

  • direct self-reference in a dict
  • direct self-reference in a list
  • indirect two-hop cycle (a -> b -> a)
  • sibling containers sharing the same nested object are NOT flagged as circular (guards against an overly aggressive fix)

Full suite passes locally: 201 passed.

Recursive containers (e.g. an object graph with a back-reference) hit
Python's recursion limit and crash with RecursionError instead of
returning a usable (if lossy) JSON payload. Track visited container
ids per recursion path and substitute a placeholder on repeat instead
of recursing forever.

Closes sktime#189
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.

[BUG] sanitize_for_json crashes on circular references (RecursionError)

1 participant