Skip to content

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

Closed
alireza78a wants to merge 1 commit intoNousResearch:mainfrom
alireza78a:fix/atomic-env-write-v2
Closed

fix(config): atomic write for .env to prevent API key loss on crash#842
alireza78a wants to merge 1 commit intoNousResearch:mainfrom
alireza78a:fix/atomic-env-write-v2

Conversation

@alireza78a
Copy link
Contributor

What

save_env_value() uses 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.

How It Works

Write goes to a temp file in the same directory first, 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.

Impact

Prevents silent loss of OPENROUTER_API_KEY, TELEGRAM_BOT_TOKEN,
DISCORD_BOT_TOKEN, NOUS_API_KEY, and every other key stored in .env.

Tests

173 hermes_cli tests pass.

teknium1 pushed a commit that referenced this pull request Mar 11, 2026
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
Copy link
Contributor

Merged via PR #954. Your commit was cherry-picked with authorship preserved — the branch was 165 commits behind main with a conflict in the _secure_file refactor area, so a direct merge wasn't possible. Thanks @alireza78a!

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.

2 participants