Skip to content

Make temporary_cd() thread-safe by not calling os.chdir() in the no-argument form#147

Draft
Copilot wants to merge 2 commits intomainfrom
copilot/fix-thread-safety-temporary-cd
Draft

Make temporary_cd() thread-safe by not calling os.chdir() in the no-argument form#147
Copilot wants to merge 2 commits intomainfrom
copilot/fix-thread-safety-temporary-cd

Conversation

Copy link
Copy Markdown

Copilot AI commented Apr 17, 2026

os.chdir() is process-wide: concurrent threads calling temporary_cd() simultaneously all mutate the same CWD, causing races where threads write/read files in each other's temp directories.

Changes

  • temporary_cd() (no-arg): no longer calls os.chdir(). Creates a temp dir, yields its absolute path, and cleans up — the process CWD is never touched. Thread-safe.
  • temporary_cd(path) (explicit path): retains os.chdir() for backward compatibility. Still not thread-safe (unchanged behaviour, now documented).
  • Return type: Generator[None, None, None]Generator[str, None, None] — the yielded absolute path is the intended interface for file I/O.
  • Absolute path is resolved before os.chdir() to avoid resolving a relative path against the new directory.

Migration

# Before — not thread-safe
with temporary_cd():
    open("f.txt", "w").write(data)

# After — thread-safe
with temporary_cd() as tmpdir:
    open(os.path.join(tmpdir, "f.txt"), "w").write(data)

New tests cover: correct yielded paths in all three call forms, and concurrent correctness with 8 threads.

Copilot AI changed the title [WIP] Fix thread safety in temporary_cd for file I/O Make temporary_cd() thread-safe by not calling os.chdir() in the no-argument form Apr 17, 2026
Copilot AI requested a review from mattwthompson April 17, 2026 16:23
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 17, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.93%. Comparing base (7bc4a2f) to head (7287329).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #147   +/-   ##
=======================================
  Coverage   94.93%   94.93%           
=======================================
  Files           6        6           
  Lines         158      158           
=======================================
  Hits          150      150           
  Misses          8        8           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

File I/O is not thread-safe within temporary_cd

2 participants