Skip to content

fix: use context manager for file reads in code_projects_api.py - #93

Open
nwalio wants to merge 1 commit into
OpenNSWM-Lab:mainfrom
nwalio:fix/code-projects-unclosed-files
Open

fix: use context manager for file reads in code_projects_api.py#93
nwalio wants to merge 1 commit into
OpenNSWM-Lab:mainfrom
nwalio:fix/code-projects-unclosed-files

Conversation

@nwalio

@nwalio nwalio commented Aug 30, 2026

Copy link
Copy Markdown

Background

In backend/app/modules/code/code_projects_api.py, two file reads use the pattern json.loads(open(path, encoding="utf-8").read()), which opens a file handle without explicitly closing it. The handle is eventually collected by the garbage collector, but if json.loads raises before the handle is released, it leaks. Under PyPy or high-concurrency workloads, these accumulate.

Changes

Replaced both occurrences with the with open(...) as f: context manager pattern:

  • Line 1299 (get_pipeline_results): reading pipeline_results.json
  • Line 1374 (auto_fix_pipeline): reading previous pipeline results

Each change adds one line (the with statement) and re-indents the json.loads call inside the block. No behavioral change — the same data is read and parsed.

Before/After

# Before
data = json.loads(open(results_path, encoding="utf-8").read())

# After
with open(results_path, encoding="utf-8") as _f:
    data = json.loads(_f.read())

Notes

The existing encoding="utf-8" parameter is preserved — this was already correct. The only change is ensuring the file handle is deterministically closed via the context manager protocol rather than relying on GC timing.

Verification

  • py_compile confirms valid Python syntax
  • New test tests/test_pr_06_code_projects_files.py runs two assertions:
    1. No open(...).read() patterns remain in the module
    2. At least 3 context-managed results_path opens exist (2 reads + 1 write)
  • Both tests pass in the sandbox container

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