Skip to content

Collect cycles through sets, frozensets and set iterators - #9343

Merged
youknowone merged 1 commit into
RustPython:mainfrom
1ndahous3:set_gc_clear
Oct 25, 2026
Merged

youknowone merged 1 commit into
RustPython:mainfrom
1ndahous3:set_gc_clear

Conversation

@1ndahous3

@1ndahous3 1ndahous3 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Found while testing collection adapters for an embedding application: a native object holding a plain PyRef<PySet> remained allocated when the set contained that object.

Summary

  • Break cycles through sets and frozensets by detaching keys before releasing their references; traverse frozenset members and the container owned by a set iterator.
  • Preserve shared internal tables until they have an exclusive owner, avoiding duplicate accounting and clearing another owner's references.
  • Release set tables directly during ordinary destruction, keeping deferred reference release for cyclic GC.
  • Keep exact frozensets with acyclic contents outside GC, including native allocation paths. Subclasses and potentially cyclic contents remain tracked.

Performance

Three full collections release all 3,000 native/set cycles in the reproduction on both systems; previously none of the native payloads were released.

Windows 11 x64

Operation main This patch
Temporary set union (24 elements) 821 ns 816 ns
Temporary frozenset union (24 elements) 827 ns 863 ns
Frozenset union (256 integers) 3.05 µs 3.47 µs
Full GC with 30,000 live singleton frozensets 2.50 ms 2.35 ms

Debian 13 amd64

Operation main This patch
Temporary set union (24 elements) 707 ns 731 ns
Temporary frozenset union (24 elements) 720 ns 804 ns
Frozenset union (256 integers) 2.84 µs 3.19 µs
Full GC with 30,000 live singleton frozensets 2.35 ms 1.89 ms

Checking frozenset eligibility adds a linear scan of the result's keys. The union measurements include destruction of the temporary result.

AI assistance

Written with Codex (GPT-6), reviewed by a human before submission.

Summary by CodeRabbit

  • Bug Fixes
    • Improved memory management for sets and frozen sets, including when their underlying data is shared.
    • Updated object cleanup and cycle tracking to better account for values that can participate in reference cycles, helping ensure references are released safely. These changes may also reduce unnecessary garbage-collection tracking in cases where it is not needed.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T12:20:36.979262Z cbf92d3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 5bccf31 and cbf92d3.

Files ignored due to path filters: 1
  • Lib/test/test_set.py is excluded by !Lib/**
Files selected for processing: 4
  • crates/vm/src/builtins/set.rs
  • crates/vm/src/dict_inner.rs
  • crates/vm/src/object/core.rs
  • crates/vm/src/object/payload.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

Set and frozenset now use manual GC traversal and clearing that accounts for shared tables. Payloads can specify whether they need cyclic GC and whether deallocation calls their clear function.

Changes: GC lifecycle and set traversal

Layer / File(s) Summary
Payload GC and deallocation policy
crates/vm/src/object/payload.rs, crates/vm/src/object/core.rs
PyPayload adds needs_gc and CLEAR_ON_DEALLOC. Object creation uses the payload’s GC eligibility alongside dict-backed and heap-type tracking rules. Default deallocation clears payloads only when the payload opts in or uses a freelist.
Set traversal, tracking, and validation
crates/vm/src/builtins/set.rs, crates/vm/src/dict_inner.rs
Set payloads manually traverse and clear table entries only when the table has one owner. Frozenset tracking checks subclasses, table sharing, and key GC edges. Tests cover deferred key release, shared tables, and frozenset tracking cases.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: youknowone, shaharnaveh

Merge Risk: Minimal · up to cbf92

No actionable merge-blocking risk remains; the change is mergeable after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 20.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Collect cycles through sets, frozensets and set iterators" matches the main change. The raw summary and PR objectives show GC traversal and clearing for PySet, PyFrozenSet, and set iterator…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Collect cycles through sets, frozensets and set iterators" matches the main change. The raw summary and PR objectives show GC traversal and clearing for PySet, PyFrozenSet, and set iterators, plus the needs_gc and CLEAR_ON_DEALLOC additions that support cycle collection through these types. The title is specific and concise, and it names the primary change for a reviewer scanning history.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[ ] test: cpython/Lib/test/test_set.py (TODO: 1)

dependencies:

dependent tests: (no tests depend on set)

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cbf92d3163

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread crates/vm/src/builtins/set.rs

@youknowone youknowone 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.

👍

@youknowone
youknowone merged commit db48780 into RustPython:main Oct 25, 2026
22 checks passed
youknowdot added a commit to youknowdot/RustPython that referenced this pull request Oct 25, 2026
Integrate main at 9bd84b2 while preserving the published mega history.
Keep the authentic profiler locator and capabilities from RustPython#9340, set-cycle
GC from RustPython#9343, backward-compatible bytecode tooling from RustPython#9344, package
paths from RustPython#9345, canonical Levenshtein coverage from RustPython#9346, and the safe
full-width None-return scanner from RustPython#9347.

Regenerate support helpers through the official updater from unchanged
CPython d220409a13b7, preserving four exact existing-main neighborhoods.
Retain the newer main specialization/C-stack helpers, Cargo environment
adaptation, prior isolation checks and remaining Python 3.15 updates.
The obsolete manual capability guard is superseded by the genuine API.

Preserve unlanded explicit sharing modes and opcode override support.
Ruff and XML vendor sources remain unchanged.

Validation: normal hooks, locked host_env/VM/stdlib library check and
strict Clippy, and the default CLI build. No target-runtime or full-suite
pass is claimed for this composition.

Assisted-by: OpenAI Codex:model version unavailable
@1ndahous3
1ndahous3 deleted the set_gc_clear branch October 25, 2026 09:34
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