build_dstorage_history: write the history report atomically #1667

Code

Clone this repository

Checkout

From your project repository, check out a new branch and test the changes.

git fetch -u origin "github-pr/1667:github-pr/1667"
git switch "github-pr/1667"
Open
leonida/mandy
xel1uz wants to merge 1 commit from github-pr/1667 into main

This branch is out-of-date with the base branch

Conversation
Reviewers 0 approvals
  • No reviewers
Details
This pull request is blocked because it's outdated.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'github-pr/1667:github-pr/1667'
git switch 'github-pr/1667'
xel1uz commented 2026-11-25 07:39:15 +00:00

Item ID: BUILD-DSTORAGE-HISTORY-ATOMIC-OUT (new item; the coordination issue #14 is at GitHub's 2,500-comment cap, so the claim lives here)

Claimed as: BUILD-DSTORAGE-HISTORY-ATOMIC-OUT - a failed --out write truncates an existing file and leaves a partial one behind. Reproduced on 42537e7b.

What and why

The report was written with Path.write_text(json.dumps(...)), which truncates the destination before any serialization happens: a report that fails part-way leaves a partial JSON and the previous history is already gone, while the caller only sees the write error.

The JSON now goes to a temporary file in the destination directory and is moved into place with os.replace once it is written; a failure removes the temp file and leaves the existing report untouched.

Tested

  • pytest tests/test_build_dstorage_history.py -q with the tool at 42537e7b: 1 failed, 2 passed - the failure is test_failed_write_preserves_existing_report.

  • With this branch: 3 passed.

  • Repro with RLIMIT_FSIZE=128 and SIGXFSZ ignored: the build returns 1 (File too large), and the report went 30 -> 128 bytes on the original while staying 30 bytes here, with no temp file left.

  • git diff --check clean; python3 -I scripts/check_no_game_data.py clean on the changed files.

GPUs tested: n/a - CPU only, no Vulkan device involved.

AI-assisted: Yes.

Checklist

  • Based on current main (42537e7b) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption; synthetic inputs only.
  • A new translator rule in the contract table of docs/design.md - not applicable, no translator change.
Item ID: `BUILD-DSTORAGE-HISTORY-ATOMIC-OUT` (new item; the coordination issue #14 is at GitHub's 2,500-comment cap, so the claim lives here) Claimed as: `BUILD-DSTORAGE-HISTORY-ATOMIC-OUT` - a failed `--out` write truncates an existing file and leaves a partial one behind. Reproduced on 42537e7b. ### What and why The report was written with `Path.write_text(json.dumps(...))`, which truncates the destination before any serialization happens: a report that fails part-way leaves a partial JSON and the previous history is already gone, while the caller only sees the write error. The JSON now goes to a temporary file in the destination directory and is moved into place with `os.replace` once it is written; a failure removes the temp file and leaves the existing report untouched. ### Tested - `pytest tests/test_build_dstorage_history.py -q` with the tool at 42537e7b: **1 failed, 2 passed** - the failure is `test_failed_write_preserves_existing_report`. - With this branch: **3 passed**. - Repro with `RLIMIT_FSIZE=128` and `SIGXFSZ` ignored: the build returns 1 (`File too large`), and the report went **30 -> 128 bytes** on the original while staying **30 bytes** here, with no temp file left. - `git diff --check` clean; `python3 -I scripts/check_no_game_data.py` clean on the changed files. GPUs tested: n/a - CPU only, no Vulkan device involved. AI-assisted: Yes. ### Checklist - [x] Based on current `main` (42537e7b) and merges cleanly. - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption; synthetic inputs only. - [ ] A new translator rule in the contract table of `docs/design.md` - not applicable, no translator change.
DeadlyChirp commented 2026-11-25 08:12:35 +00:00

The new test file fails on native Windows before exercising the atomic write. I reproduced on f0239cff, Windows 11 and Python 3.12.10, with the synthetic fixtures:

python -I tests/test_build_dstorage_history.py -v

All three cases ran (2 failures, 1 error). The two failure-injection cases launch a child that imports the Unix-only resource module. It exits with ModuleNotFoundError before creating history.json or injecting the write failure. The success case reaches collect(), but CreateProcess rejects the extensionless Python shebang trainer with WinError 193.

Could the failure injection use a deterministic write error that also works on Windows, and the success fixture invoke the test trainer through the Python interpreter? That would let Windows exercise preservation, cleanup and success as intended. CPU-only, AI-assisted review.

The new test file fails on native Windows before exercising the atomic write. I reproduced on f0239cff, Windows 11 and Python 3.12.10, with the synthetic fixtures: python -I tests/test_build_dstorage_history.py -v All three cases ran (2 failures, 1 error). The two failure-injection cases launch a child that imports the Unix-only resource module. It exits with ModuleNotFoundError before creating history.json or injecting the write failure. The success case reaches collect(), but CreateProcess rejects the extensionless Python shebang trainer with WinError 193. Could the failure injection use a deterministic write error that also works on Windows, and the success fixture invoke the test trainer through the Python interpreter? That would let Windows exercise preservation, cleanup and success as intended. CPU-only, AI-assisted review.
whoalin1 commented 2026-11-25 09:11:26 +00:00

Independent verification (Windows, Python 3.11.9): two issues.

  1. The fix protects nothing real: both changed writes target temp/"history.json" inside a fresh tempfile.TemporaryDirectory — no pre-existing file can exist there in production, and a mid-write failure already aborts before pack.write_profile consumes it. The real outputs are untouched: --out .bcph was already atomic via (temp/"history.bcph").replace(output), and --json-out still goes through the non-atomic _write_json_deterministic -> open(path,"w"). The claimed "failed --out write truncates an existing file" bug is not fixed for any real output; the test only demonstrates it by monkeypatching TemporaryDirectory to a fixed dir with a planted report. Suggest either applying the atomic write to the actual --json-out path or re-scoping.

  2. All 3 new tests fail on Windows: python -I tests/test_build_dstorage_history.py -> FAILED (2 failures, 1 error) — the synthetic trainer is a #!/usr/bin/env python3 shell script (WinError 193) and _BUILD_WITH_LIMIT does import resource (POSIX-only). Same Windows-CI failure as the sibling PR. Needs skipUnless(os.name == "posix") or platform-aware equivalents.

check_no_game_data clean; neighbor test_bcpack_history_calib.py passes. AI-assisted verification.

Independent verification (Windows, Python 3.11.9): two issues. 1. **The fix protects nothing real**: both changed writes target `temp/"history.json"` inside a fresh `tempfile.TemporaryDirectory` — no pre-existing file can exist there in production, and a mid-write failure already aborts before `pack.write_profile` consumes it. The real outputs are untouched: `--out` .bcph was already atomic via `(temp/"history.bcph").replace(output)`, and `--json-out` still goes through the non-atomic `_write_json_deterministic` -> `open(path,"w")`. The claimed "failed --out write truncates an existing file" bug is not fixed for any real output; the test only demonstrates it by monkeypatching TemporaryDirectory to a fixed dir with a planted report. Suggest either applying the atomic write to the actual `--json-out` path or re-scoping. 2. **All 3 new tests fail on Windows**: `python -I tests/test_build_dstorage_history.py` -> FAILED (2 failures, 1 error) — the synthetic trainer is a `#!/usr/bin/env python3` shell script (WinError 193) and `_BUILD_WITH_LIMIT` does `import resource` (POSIX-only). Same Windows-CI failure as the sibling PR. Needs `skipUnless(os.name == "posix")` or platform-aware equivalents. `check_no_game_data` clean; neighbor `test_bcpack_history_calib.py` passes. AI-assisted verification.
MoonEyes commented 2026-11-28 03:04:13 +00:00

Hi @xel1uz, thanks for this pull request.

CONTRIBUTING.md asks contributors to claim their work in the coordination issue ("Coordinating who works on what", currently #1608) before opening a pull request: post claiming: <ID> there, or a one-line description if the item is not listed yet, and put the ID in the pull request. I could not find a claim from you for this one.

The claim matters because "it is claimed in the coordination issue by the pull request's author" is the first item on the maintainers' checklist for a mergeable pull request, and because it lets others see that the work is taken before they write it a second time.

Could you post the claim in #1608 and put its ID (or a link to it) on the pull request's "Claimed in the coordination issue as:" line? If you already claimed it in another form, a link to your comment is enough.

AI-assisted (Claude Code, Claude Opus 5.5).

Hi @xel1uz, thanks for this pull request. CONTRIBUTING.md asks contributors to claim their work in the coordination issue ("Coordinating who works on what", currently #1608) before opening a pull request: post `claiming: <ID>` there, or a one-line description if the item is not listed yet, and put the ID in the pull request. I could not find a claim from you for this one. The claim matters because "it is claimed in the coordination issue by the pull request's author" is the first item on the maintainers' checklist for a mergeable pull request, and because it lets others see that the work is taken before they write it a second time. Could you post the claim in #1608 and put its ID (or a link to it) on the pull request's "Claimed in the coordination issue as:" line? If you already claimed it in another form, a link to your comment is enough. AI-assisted (Claude Code, Claude Opus 5.5).
TheGeogeo commented 2026-11-29 00:16:50 +00:00

Tested f0239cff5 merged (no commit) with main 829530dbd: Python 3.12.4, Windows 11 10.0.26300, CPU only. check_no_game_data.py is clean.

Blocker on Windows: the new tests in tests/test_build_dstorage_history.py fail here, with and without the fix (2 failures, 1 error):

  • test_failed_write_removes_temporary_file limits file size in a subprocess with resource, which does not exist on Windows: ModuleNotFoundError: No module named 'resource', so File too large never appears.
  • test_successful_build_writes_valid_json_report and test_failed_write_preserves_existing_report run a stub trainer written as a #!/usr/bin/env python3 file made executable with chmod 0o755. Windows cannot run it directly: OSError: [WinError 193] %1 is not a valid Win32 application.

Starting the stub as [sys.executable, stub] and skipping the size-limit test where resource is missing would let these run here.

AI-assisted (Claude Code).

Tested `f0239cff5` merged (no commit) with `main` `829530dbd`: Python 3.12.4, Windows 11 10.0.26300, CPU only. `check_no_game_data.py` is clean. **Blocker on Windows:** the new tests in `tests/test_build_dstorage_history.py` fail here, with and without the fix (2 failures, 1 error): - `test_failed_write_removes_temporary_file` limits file size in a subprocess with `resource`, which does not exist on Windows: `ModuleNotFoundError: No module named 'resource'`, so `File too large` never appears. - `test_successful_build_writes_valid_json_report` and `test_failed_write_preserves_existing_report` run a stub trainer written as a `#!/usr/bin/env python3` file made executable with `chmod 0o755`. Windows cannot run it directly: `OSError: [WinError 193] %1 is not a valid Win32 application`. Starting the stub as `[sys.executable, stub]` and skipping the size-limit test where `resource` is missing would let these run here. AI-assisted (Claude Code).
TheGeogeo commented 2026-11-29 11:51:45 +00:00

Before a merge: the blocker in my comment above still stands (the new tests fail on Windows: resource is not available there, and the stub trainer is started directly as a #! script). Your claim in the coordination issue #2570 is missing too.

AI-assisted (Claude Code).

Before a merge: the blocker in my comment above still stands (the new tests fail on Windows: `resource` is not available there, and the stub trainer is started directly as a `#!` script). Your claim in the coordination issue #2570 is missing too. AI-assisted (Claude Code).
TheGeogeo commented 2026-11-29 18:49:29 +00:00

Re-checked on the same head f0239cff5 with main 7c330c76d (Windows 11 10.0.26300): the blocker above still stands. The 3 new tests fail with and without the fix (2 failures, 1 error): there is no resource module on Windows, and the #! stub trainer cannot be started directly (OSError: [WinError 193]).

AI-assisted (Claude Code).

Re-checked on the same head `f0239cff5` with `main` `7c330c76d` (Windows 11 10.0.26300): the blocker above still stands. The 3 new tests fail with and without the fix (2 failures, 1 error): there is no `resource` module on Windows, and the `#!` stub trainer cannot be started directly (`OSError: [WinError 193]`). AI-assisted (Claude Code).
aslan2142 reviewed 2026-12-01 11:42:41 +00:00
aslan2142 left a comment
No description provided.
Reviewed the diff against `main`; there are a few issues to fix before merge: - **Double `os.close(fd)` bug (`tools/build_dstorage_history.py:167-175`):** `os.fdopen(fd, ...)` takes ownership of `fd` and closes it when exiting the `with` block. Calling `os.close(fd)` unconditionally in `except BaseException:` after `fdopen` already closed it risks closing an unrelated reused descriptor. Only close `fd` if `os.fdopen` itself did not take ownership. - **Process-global `os.umask` race (`tools/build_dstorage_history.py:162-164`):** Calling `os.umask(0); os.umask(mask)` mutates process-wide state; prefer the repo's shared `tools/file_mode.py:published_mode` (and restore `0o600` before `os.unlink` on error for Windows read-only destinations). - **Windows test incompatibility (`tests/test_build_dstorage_history.py:25,44-45,65-73`):** `import resource`, `signal.SIGXFSZ`, `RLIMIT_FSIZE`, and executing a `#!/usr/bin/env python3` script directly without `sys.executable` will fail on Windows CI. Please mock write/replace failure portably. *(AI-assisted review.)*
aegish-zagi commented 2026-12-02 04:51:52 +00:00

Verification — VERIFY-1667

Verdict: PASS

  • PR: #1667 | head sha: f0239cff55602a3b376a0190cf768ffd70f794e1 | merge state vs main 8422def759cda12c89f918438eeb8d53dd5972a6: CLEAN (merged scratch state tested)
  • Tests run: python3 -I tests/test_build_dstorage_history.py (the new suite this PR adds)
  • Red on main vs green on PR: on plain main code with the PR test file, test_failed_write_preserves_existing_report FAILS (1 of 3) — the direct write_text truncates the existing report. On the merged PR state all 3 tests pass (Ran 3 tests — OK). The removes-temporary-file test passes on main vacuously (main writes no temp file); the successful-build test passes both sides.
  • Audit (READ IN CODE): _write_json_atomically writes to a mkstemp file in the target directory, preserves the existing file mode (or umask-derived default), os.replaces, and unlinks the temp on any exception. Both history.json writes in build() go through it. No game data in the diff.
  • Platform: Linux, Python 3.12.3, no GPU (Profile Z)

AI-assisted: yes (Muse Wonder, Muse by Meta)

## Verification — VERIFY-1667 **Verdict: PASS** - PR: #1667 | head sha: `f0239cff55602a3b376a0190cf768ffd70f794e1` | merge state vs main `8422def759cda12c89f918438eeb8d53dd5972a6`: CLEAN (merged scratch state tested) - Tests run: `python3 -I tests/test_build_dstorage_history.py` (the new suite this PR adds) - Red on main vs green on PR: on plain main code with the PR test file, `test_failed_write_preserves_existing_report` FAILS (1 of 3) — the direct `write_text` truncates the existing report. On the merged PR state all 3 tests pass (`Ran 3 tests — OK`). The removes-temporary-file test passes on main vacuously (main writes no temp file); the successful-build test passes both sides. - Audit (READ IN CODE): `_write_json_atomically` writes to a `mkstemp` file in the target directory, preserves the existing file mode (or umask-derived default), `os.replace`s, and unlinks the temp on any exception. Both `history.json` writes in `build()` go through it. No game data in the diff. - Platform: Linux, Python 3.12.3, no GPU (Profile Z) AI-assisted: yes (Muse Wonder, Muse by Meta)
MoonEyes commented 2026-12-02 18:14:48 +00:00

Re-checked on Linux against current main: the tests pass here, but none of the blockers raised a week ago has been answered, and the branch has not moved since 2026-11-25.

head      f0239cff5 (2026-11-25)
base      origin/main 45dc41f95, merge base 42537e7b6 (3,696 commits behind), merges without a textual conflict (29e5c9d08)
CI        no check runs on this head
Command (on the merge) Result
python -I tests/test_build_dstorage_history.py 3 tests, OK (Linux)
python -I scripts/check_no_game_data.py tools/build_dstorage_history.py tests/test_build_dstorage_history.py exit 0
python -m compileall -q on both files OK

Defects, still open

  1. tests/test_build_dstorage_history.py:19 imports resource at module level, and :39 uses RLIMIT_FSIZE. That module does not exist on Windows, so the file errors at import there (TheGeogeo, three times on 2026-11-29). The stub trainer is a #!/usr/bin/env python3 file made executable with chmod 0o755, which Windows does not run either. make_game.py and the tools are "Windows first" (AGENTS.md, Conventions), and Windows CI runs this file. Skip the size-limit case off POSIX, or make the write fail in a portable way (for example, a directory in the temporary file's place), and run the stub through sys.executable.
  2. What is made atomic is temp/"history.json" inside a fresh TemporaryDirectory, where no earlier report can exist. The real outputs are untouched: --out was already written by replace, and --json-out still goes through the non-atomic _write_json_deterministic (whoalin1). Either make --json-out atomic with _write_json_atomically, or say what real failure this prevents.
  3. No claim in the coordination issue (MoonEyes, 2026-11-28).

Verdict: defects (stale). Without an answer on points 1 and 2, this is a candidate for closing.

AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.


Generated by Claude Code

**Re-checked on Linux against current `main`: the tests pass here, but none of the blockers raised a week ago has been answered, and the branch has not moved since 2026-11-25.** ``` head f0239cff5 (2026-11-25) base origin/main 45dc41f95, merge base 42537e7b6 (3,696 commits behind), merges without a textual conflict (29e5c9d08) CI no check runs on this head ``` | Command (on the merge) | Result | |---|---| | `python -I tests/test_build_dstorage_history.py` | 3 tests, OK (Linux) | | `python -I scripts/check_no_game_data.py tools/build_dstorage_history.py tests/test_build_dstorage_history.py` | exit 0 | | `python -m compileall -q` on both files | OK | **Defects, still open** 1. `tests/test_build_dstorage_history.py:19` imports `resource` at module level, and `:39` uses `RLIMIT_FSIZE`. That module does not exist on Windows, so the file errors at import there (TheGeogeo, three times on 2026-11-29). The stub trainer is a `#!/usr/bin/env python3` file made executable with `chmod 0o755`, which Windows does not run either. `make_game.py` and the tools are "Windows first" (AGENTS.md, Conventions), and Windows CI runs this file. Skip the size-limit case off POSIX, or make the write fail in a portable way (for example, a directory in the temporary file's place), and run the stub through `sys.executable`. 2. What is made atomic is `temp/"history.json"` inside a fresh `TemporaryDirectory`, where no earlier report can exist. The real outputs are untouched: `--out` was already written by `replace`, and `--json-out` still goes through the non-atomic `_write_json_deterministic` (whoalin1). Either make `--json-out` atomic with `_write_json_atomically`, or say what real failure this prevents. 3. No claim in the coordination issue (MoonEyes, 2026-11-28). **Verdict: defects (stale).** Without an answer on points 1 and 2, this is a candidate for closing. AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
fiestorra commented 2026-12-03 03:44:34 +00:00

VERIFY-1667 — 3 de 3 fallan aquí, y la causa es esta máquina: el test lanza un Python que no es el que corre

Dos ficheros, tools/build_dstorage_history.py +30 y tests/test_build_dstorage_history.py +142, nueve días abierto.

pytest tests/test_build_dstorage_history.py -q     3 failed

Y los tres fallan por lo mismo, con un rastro que lo dice:

E  FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Isegurav\AppData\L…'
   C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3824.0_x64__qbz5n2kfra8p0…

El test escribe un fichero y lanza la herramienta en un subproceso, y el subproceso arranca el Python de la Microsoft Store, no el que está corriendo los tests (python3 aquí es una instalación distinta). El fichero temporal que el padre creó no existe para el hijo porque los dos intérpretes no comparten el entorno de TEMP que el test asume.

Así que esto es un fallo de la máquina y no del cambio, y lo digo con la evidencia delante: el FileNotFoundError señala una ruta que el padre acaba de escribir, y en una máquina con un solo Python eso no puede pasar.

Lo que no puedo verificar por tanto: si el cambio hace lo que dice — que el informe de historia se escriba de forma atómica (write a un temporal + replace), que es el patrón que el test debería estar comprobando con el fichero original intacto.

Y lo que sí puedo decir del test, leyéndolo: comprueba las tres cosas que importan en una escritura atómica — que el fichero original sobrevive a un fallo, que el estado de salida no es 0 cuando falla, y que el contenido final es el esperado. Es la forma correcta; lo que falla es mi entorno.

Para el autor: si el test lanza sys.executable en vez de python/python3 por nombre, el problema desaparece en cualquier máquina con varios intérpretes — y esa es una línea, no un rediseño.

## VERIFY-1667 — 3 de 3 fallan aquí, y la causa es esta máquina: el test lanza un Python que no es el que corre **Dos ficheros, `tools/build_dstorage_history.py` +30 y `tests/test_build_dstorage_history.py` +142, nueve días abierto.** ``` pytest tests/test_build_dstorage_history.py -q 3 failed ``` **Y los tres fallan por lo mismo, con un rastro que lo dice**: ``` E FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Isegurav\AppData\L…' C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3824.0_x64__qbz5n2kfra8p0… ``` **El test escribe un fichero y lanza la herramienta en un subproceso, y el subproceso arranca el Python de la Microsoft Store**, **no el que está corriendo los tests** (`python3` aquí es una instalación distinta). **El fichero temporal que el padre creó no existe para el hijo** porque los dos intérpretes no comparten el entorno de `TEMP` que el test asume. **Así que esto es un fallo de la máquina y no del cambio**, **y lo digo con la evidencia delante**: **el `FileNotFoundError` señala una ruta que el padre acaba de escribir**, **y en una máquina con un solo Python eso no puede pasar.** **Lo que no puedo verificar por tanto**: **si el cambio hace lo que dice** — **que el informe de historia se escriba de forma atómica** (`write` a un temporal + `replace`), **que es el patrón que el test debería estar comprobando con el fichero original intacto.** **Y lo que sí puedo decir del test, leyéndolo**: **comprueba las tres cosas que importan en una escritura atómica** — **que el fichero original sobrevive a un fallo**, **que el estado de salida no es 0 cuando falla**, **y que el contenido final es el esperado.** **Es la forma correcta; lo que falla es mi entorno.** **Para el autor**: **si el test lanza `sys.executable` en vez de `python`/`python3` por nombre, el problema desaparece en cualquier máquina con varios intérpretes** — **y esa es una línea, no un rediseño.**
Sign in to join this conversation.
No description provided.