Skip to content

Freeze GC objects at exit to skip the Generation 2 sweep - #2062

Merged
rocky merged 1 commit into
masterfrom
faster-exits-freeze
Oct 20, 2026
Merged

rocky merged 1 commit into
masterfrom
faster-exits-freeze

Conversation

@tombouctou

Copy link
Copy Markdown
Collaborator

An alternative to #2061 for the slow exit after loading a large package such as Rubi.

At exit, Py_Finalize() runs a full cyclic garbage collection that walks the huge Generation 2 graph Rubi leaves behind. This registers gc.freeze as the first atexit handler, so it runs last. Every tracked object moves into the permanent generation, and the final collection has almost nothing to walk.

Unlike os._exit(), the normal shutdown stays intact. The other atexit handlers still run (readline history, --show-statistics, trace dumps), SystemExit still propagates (Dialog[], embedding hosts), and exit codes are unchanged. Because the hook is on main() rather than on the Quit[] branch of the REPL loop, it also applies on Ctrl-D.

Measurements

Python 3.12.13 on Linux, Get["Rubi.wl"] (2819 Int rules), then exit. Time is from the last output to process exit, two runs each:

variant Quit[3] EOF / Ctrl-D
master 10.85 s, 10.88 s 10.84 s, 10.74 s
#2061 (os._exit) 0.14 s, 0.13 s 10.85 s, 10.54 s
this PR 0.15 s, 0.15 s 0.14 s, 0.15 s

Exit code after Quit[3] is 3 in all variants. Details are in #2061 (comment).

test/test_main.py and test/test_returncode.py pass locally.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rocky

rocky commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

LGTM - I will modify the PR #2061 to remove where this overlaps
#2061 also tries to address pytest exit slowness, although it should use an atexit hook instead of os._exit(). Correction: it uses gc.disable() before finalization which I guess is okay.

But in the back of my mind, another thing that might be done is to add a parameter when a Mathics3 session is called, which also has a way of addressing the GC slowness.

@rocky
rocky merged commit 82af046 into master Oct 20, 2026
15 checks passed
@rocky
rocky deleted the faster-exits-freeze branch October 20, 2026 17:11
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