Skip to content

fix(config): atomic write for .env to prevent API key loss on crash#954

Merged
teknium1 merged 1 commit intomainfrom
hermes/hermes-20ea56c0
Mar 11, 2026
Merged

fix(config): atomic write for .env to prevent API key loss on crash#954
teknium1 merged 1 commit intomainfrom
hermes/hermes-20ea56c0

Conversation

@teknium1
Copy link
Copy Markdown
Contributor

Summary

Cherry-picked from PR #842 by @alireza78a, rebased onto current main with conflict resolution.

save_env_value() used bare open('w') which truncates .env immediately. A crash or OOM kill between truncation and the completed write silently wipes every credential in the file.

Fix

Write now goes to a temp file in the same directory first (tempfile.mkstemp), then os.replace() swaps it atomically. Either the old .env exists or the new one does — never a truncated half-write. Same pattern already used in save_jobs() in cron/jobs.py.

Conflict resolution

The PR was 165 commits behind main. The only conflict was that main had refactored the inline os.chmod into _secure_file(env_path). Resolved by keeping the atomic write pattern AND the _secure_file() call.

Tests

201 hermes_cli tests pass.

Closes #842

Co-authored-by: alireza78a alireza78a@users.noreply.github.com

save_env_value() used bare open('w') which truncates .env immediately.
A crash or OOM kill between truncation and completed write silently
wipes every credential in the file.

Write now goes to a temp file first, then os.replace() swaps it
atomically. Either the old .env exists or the new one does — never
a truncated half-write. Same pattern used in cron/jobs.py.

Cherry-picked from PR #842 by alireza78a, rebased onto current main
with conflict resolution (_secure_file refactor).

Co-authored-by: alireza78a <alireza78a@users.noreply.github.com>
@teknium1 teknium1 merged commit 09b1de5 into main Mar 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants