Fix memory_zone cleanup on exception#13932
Merged
honnibal merged 1 commit intoexplosion:masterfrom Mar 15, 2026
Merged
Conversation
Wrap yield in try/finally in StringStore.memory_zone and Vocab.memory_zone so transient state is always cleaned up, even when an exception propagates through the context manager.
Contributor
Author
|
Hi @honnibal — this is a small fix for the memory_zone context managers in The fix wraps the existing cleanup in |
Member
|
Thanks! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When an exception propagates out of
nlp.memory_zone(), the cleanup code inStringStore.memory_zone()andVocab.memory_zone()never runs. This leaves the vocab in a broken state (transient strings/lexemes not cleared,self.memstill pointing to a temporary pool), causing anAssertionErrorinVocab.get()on the next call tonlp().Fixes #13924
Root cause
Both
StringStore.memory_zone()andVocab.memory_zone()use@contextmanagerwith cleanup code placed afteryieldbut without atry/finallywrapper. In a@contextmanager, code afteryieldonly runs on normal exit. If an exception is thrown at theyieldpoint, it propagates without executing the cleanup.Changes
spacy/strings.pyx: Wrapyieldand cleanup (clearing transient keys, restoringself.mem) intry/finallyspacy/vocab.pyx: Same pattern for_clear_transient_orths()andself.memrestorespacy/tests/vocab_vectors/test_memory_zone.py: Add regression test that raises inside a memory zone and verifies the vocab is usable afterwardTesting
test_memory_zonetests pass (no change to happy-path behavior)test_memory_zone_exception_cleanupverifies:vocab.in_memory_zoneisFalseafter exception