Skip to content

fix: __del__ not freeing up native resources#38

Open
acoroleu-tempus wants to merge 4 commits intoextism:mainfrom
acoroleu-tempus:fix-memory-leak
Open

fix: __del__ not freeing up native resources#38
acoroleu-tempus wants to merge 4 commits intoextism:mainfrom
acoroleu-tempus:fix-memory-leak

Conversation

@acoroleu-tempus
Copy link

@acoroleu-tempus acoroleu-tempus commented Feb 4, 2026

extism/extism#890

Summary

Fix memory leaks caused by del methods not properly freeing native resources.
Bug 1: Plugin.__del__ never called extism_plugin_free
The guard check used hasattr(self, "pointer") but Plugin stores the handle in self.plugin, not self.pointer. This caused the method to
always return early, never freeing the native plugin.
Bug 2: Double-free errors in all __del__ methods
When del is called multiple times (e.g., via context manager exit then garbage collection), the code would attempt to free
already-freed resources, causing TypeError or segfaults.

Changes

Plugin.__del__: Fix attribute check ("pointer" → "plugin") and add -1 guard
CompiledPlugin.__del__: Add -1 guard to prevent double-free
_ExtismFunctionMetadata.__del__: Add None guard and set pointer = None after freeing

Impact

This fix enables using extism in long-running services that create fresh plugin instances per request, which previously caused unbounded
memory growth.

Test plan

• Added test_plugin_del_frees_native_resources - verifies Plugin cleanup via context manager
• Added test_compiled_plugin_del_frees_native_resources - verifies CompiledPlugin cleanup
• Added test_extism_function_metadata_del_frees_native_resources - verifies function metadata cleanup
• All tests verify that del can be safely called multiple times

@acoroleu-tempus acoroleu-tempus marked this pull request as draft February 4, 2026 09:50
@acoroleu-tempus acoroleu-tempus marked this pull request as draft February 4, 2026 09:50
acoroleu-tempus and others added 2 commits February 4, 2026 11:13
When Plugin creates its own CompiledPlugin internally, it should also
free it in __del__. Added _owns_compiled_plugin flag to track ownership
and avoid freeing externally-passed CompiledPlugin instances.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@acoroleu-tempus acoroleu-tempus marked this pull request as ready for review February 5, 2026 18:09
@acoroleu-tempus
Copy link
Author

@nilslice in case you can take a look, thanks!

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.

1 participant