Skip to content

fix: use context manager for settings file to prevent file descriptor leak#24

Open
amathxbt wants to merge 2 commits into
nesaorg:mainfrom
amathxbt:fix/file-resource-leak-settings-load
Open

fix: use context manager for settings file to prevent file descriptor leak#24
amathxbt wants to merge 2 commits into
nesaorg:mainfrom
amathxbt:fix/file-resource-leak-settings-load

Conversation

@amathxbt
Copy link
Copy Markdown

@amathxbt amathxbt commented May 9, 2026

Bug

In demo/server.py, the settings file is opened without a context manager:

# Before (broken)
file_contents = open(settings_file, 'r', encoding='utf-8').read()

Impact: If any exception is raised during the read (e.g. encoding error, I/O error, interrupted system call), the file descriptor is never explicitly closed. While CPython's reference-counting GC will usually close it eventually, this is not guaranteed across all Python runtimes (PyPy, Jython) and is flagged as a resource leak by static analysis tools. Under heavy load or rapid restarts this can exhaust the process's file descriptor limit.

Fix

Wrapped in a with statement to guarantee closure in all code paths:

# After (fixed)
with open(settings_file, 'r', encoding='utf-8') as f:
    file_contents = f.read()

amathxbt added 2 commits May 9, 2026 19:43
The settings file was opened without a context manager:
  open(settings_file, ...).read()

If an exception is raised while reading (e.g. encoding error, disk issue),
the file descriptor is never closed, causing a resource leak. Replacing
with a 'with' statement guarantees the file is closed in all code paths.
The settings file was opened without a with-statement:
  open(settings_file, ...).read()

If any exception is raised during reading (encoding error, disk issue,
etc.), the file descriptor is never explicitly closed. CPython may
close it on GC, but this is not guaranteed in all Python runtimes.

Using a with-statement ensures the fd is always closed on exit.
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