set_key and unset_key don't fsync before replacing the .env file
Mantenedores costumam responder em até 1 dia
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 72/100
Direção de pesquisa
Start in src/dotenv/main.py at rewrite(), then trace its callers from set_key, unset_key, and the dotenv set/unset commands. Find the existing tests covering rewrite or key updates and add coverage that records fsync and os.replace ordering. Done means the temporary file is durable before replacement, with any directory-durability behavior covered consistently across supported platforms.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
set_key and unset_key rewrite the .env file through rewrite() (src/dotenv/main.py): they write a temporary file next to the target, then os.replace it over the target. That makes the swap atomic for other processes, but nothing forces the new contents to disk before the rename. The temporary file is closed (which flushes Python's buffer to the OS) and then renamed, with no fsync.
What can go wrong
If the machine loses power or the kernel crashes shortly after set_key returns, the rename can reach the disk before the file's data does. After a reboot, .env can then be empty (zero length) or contain garbage, instead of holding either the old or the new contents. This applies to set_key, unset_key, and the dotenv set / dotenv unset commands.
How likely this is depends on the filesystem. ext4 with its default auto_da_alloc option flushes data before a rename that replaces an existing file, which covers this exact pattern. Other filesystems (XFS, and ext4 mounted with noauto_da_alloc) make no such promise, and a .env that has never existed before isn't covered by that heuristic at all. I haven't reproduced data loss; this is based on the documented semantics of rename(2) and fsync(2), and is the reason other write-then-rename implementations call fsync.
Since .env files often hold credentials, losing one silently is a bad outcome.
Proposed change
In rewrite(), before os.replace:
dest.flush()
os.fsync(dest.fileno())
This has to happen while the temporary file is still open, i.e. inside the with temp_file as dest: block, after the caller's writes have finished.
Optionally, after os.replace on POSIX, fsync the containing directory so the rename itself is durable:
if os.name == "posix":
dir_fd = os.open(os.path.dirname(os.path.abspath(path)), os.O_RDONLY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
Directory fsync isn't available on Windows, and some filesystems reject it with EINVAL. Since the file contents are already safe at that point, an OSError from it could reasonably be ignored.
Cost
.env files are small and set_key is not called in hot loops, so one or two fsync calls per write should not be noticeable. A test can check that os.fsync is called on the temporary file before os.replace, for example by patching both in dotenv.main and recording the call order.
Out of scope
Concurrent writers (two set_key calls at once can lose one update) and file-replacement side effects such as single-file Docker bind mounts are separate problems and not addressed here.
- Linguagem predominante
- Python
- Estrelas
- 8.9k
- Forks
- 600
- Merge médio
- 8d 8h
- PRs com merge (30d)
- 5
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Sem modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de theskumar/python-dotenv
-
An empty value ignores ${name:-default}Talvez já em andamento @SashaMIT assumiu há 6 dias. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
theskumar/python-dotenv#715 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 5/5 Mais de uma semana Facilidade para iniciantes 28/100
theskumar/python-dotenv#693 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
python-dotenv installation without cli masks python-dotenv cliTalvez já em andamento @gyanu2507 assumiu há 45 dias. Aberta
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 55/100
theskumar/python-dotenv#683 · 4 comentários ·
Mantenedores costumam responder em até 1 dia
-
Feature Request: Automatically copy `default.env` to `.env`Talvez já em andamento @dradetsky assumiu há 155 dias. Aberta
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 55/100
theskumar/python-dotenv#644 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
Add `strict` parameter to `load_dotenv()` and `dotenv_values()` for fail-fast behaviorTalvez já em andamento @AhsanSheraz assumiu há 206 dias. Aberta
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 68/100
theskumar/python-dotenv#631 · 3 comentários · 1 reação ·
Mantenedores costumam responder em até 1 dia
Todas as issues de theskumar/python-dotenv
Issues semelhantes
-
Link Checker ReportAbertaautomated issue report
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 85/100
RapidAI/RapidOCRDocs#119 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 85/100
btclib-org/btclib-node#1833 ·
Mantenedores costumam responder em até 1 dia
-
IRIS reader: no-data velocity bins (DB_VEL, DB_VELC) returned as 0.0 m/s instead of NaNTalvez já em andamento @syedhamidali assumiu hoje. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
Mantenedores costumam responder em até 2 dias
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 80/100
elodin-sys/elodin#890 ·
Mantenedores costumam responder em até 1 dia