gamedata_blobs: fix unshipped count, index type checks, and atomic JSON #2258

Open
github-bot wants to merge 2 commits from github-bot/gh-2258 into main AGit
Owner

@⁠kirigayakazima on GitHub · 2026-11-26 10:51 UTC · original
kirigayakazima:fix/gamedata-blobs-safety → main · +236 −14 · 2 files · 2 commits · open

Claimed in the coordination issue as: GAMEDATA-BLOBS-UNSHIPPED-OVERLAP-INDEX-TYPES-AND-ATOMIC-JSON (#1608)

What and why

  • Fix unshipped overlap double-subtraction in cross_reference_sgd5() (tools/gamedata_blobs.py) so preload-list entries present in both db0 and db1 are counted accurately via sum(1 for s in stems if s not in db0_set and s not in db1_set) instead of p["entries"] - len(in_db0) - len(in_db1).
  • Tighten check_carve_index() to convert UnicodeDecodeError and RecursionError from json.load() into single-line ValueError diagnostics and require type(row.get("off")) is int and type(row.get("stored")) is int (non-bool, >= 0).
  • Avoid double-parsing index.json across main() and read_payloads(..., _checked_index=is_dir), reject trailing / or \ --json directory paths in check_report_path() and non-file --shaders upfront before read_payloads(), and catch RecursionError cleanly in main().
  • Write --json output atomically via _write_json_atomic() (staging next to os.path.realpath(out_path), trailing LF \n, os.fsync(), preserving permissions with published_mode(), publishing via replace_retry.replace(), and unlinking .blobs-*.tmp files on failure).
  • Add GamedataBlobsSafetyTests to tests/test_gamedata_blobs.py (without overlapping #1269's lines) covering overlap unshipped, bool/negative/str index types, RecursionError, single index.json parse, early CLI validation, and atomic JSON write/failure rollback.

Tested

  • Patched: python -I tests/test_gamedata_blobs.py -v -> Ran 14 tests in 1.178s (OK).
  • Baseline check (upstream/main a73a57e1 with updated tests/test_gamedata_blobs.py copied into detached worktree): Ran 14 tests in 1.119s (FAILED (failures=10)).
  • Repo gates: python -I tests/test_ci_registration.py (Ran 16 tests in 5.560s, OK), python -I tests/test_text_write_line_endings.py (Ran 3 tests in 13.499s, OK), python -I scripts/check_no_game_data.py (exit 0), python -I -m compileall -q tools/gamedata_blobs.py tests/test_gamedata_blobs.py (exit 0), git diff --check (exit 0).

GPUs tested: n/a (synthetic carve/RPF/SGD5 fixtures and atomic JSON output tests)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed.
**@⁠kirigayakazima** on GitHub · 2026-11-26 10:51 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258) `kirigayakazima:fix/gamedata-blobs-safety` → `main` · +236 −14 · 2 files · 2 commits · open Claimed in the coordination issue as: GAMEDATA-BLOBS-UNSHIPPED-OVERLAP-INDEX-TYPES-AND-ATOMIC-JSON (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608) ### What and why - Fix `unshipped` overlap double-subtraction in `cross_reference_sgd5()` (`tools/gamedata_blobs.py`) so preload-list entries present in both `db0` and `db1` are counted accurately via `sum(1 for s in stems if s not in db0_set and s not in db1_set)` instead of `p["entries"] - len(in_db0) - len(in_db1)`. - Tighten `check_carve_index()` to convert `UnicodeDecodeError` and `RecursionError` from `json.load()` into single-line `ValueError` diagnostics and require `type(row.get("off")) is int` and `type(row.get("stored")) is int` (non-`bool`, `>= 0`). - Avoid double-parsing `index.json` across `main()` and `read_payloads(..., _checked_index=is_dir)`, reject trailing `/` or `\` `--json` directory paths in `check_report_path()` and non-file `--shaders` upfront before `read_payloads()`, and catch `RecursionError` cleanly in `main()`. - Write `--json` output atomically via `_write_json_atomic()` (staging next to `os.path.realpath(out_path)`, trailing LF `\n`, `os.fsync()`, preserving permissions with `published_mode()`, publishing via `replace_retry.replace()`, and unlinking `.blobs-*.tmp` files on failure). - Add `GamedataBlobsSafetyTests` to `tests/test_gamedata_blobs.py` (without overlapping `#1269`'s lines) covering overlap `unshipped`, `bool`/negative/`str` index types, `RecursionError`, single `index.json` parse, early CLI validation, and atomic JSON write/failure rollback. ### Tested - Patched: `python -I tests/test_gamedata_blobs.py -v` -> `Ran 14 tests in 1.178s` (`OK`). - Baseline check (`upstream/main` `a73a57e1` with updated `tests/test_gamedata_blobs.py` copied into detached worktree): `Ran 14 tests in 1.119s` (`FAILED (failures=10)`). - Repo gates: `python -I tests/test_ci_registration.py` (`Ran 16 tests in 5.560s`, `OK`), `python -I tests/test_text_write_line_endings.py` (`Ran 3 tests in 13.499s`, `OK`), `python -I scripts/check_no_game_data.py` (exit 0), `python -I -m compileall -q tools/gamedata_blobs.py tests/test_gamedata_blobs.py` (exit 0), `git diff --check` (exit 0). GPUs tested: n/a (synthetic carve/RPF/SGD5 fixtures and atomic JSON output tests) AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed.
Fix SGD5 unshipped overlap counting in cross_reference_sgd5(), validate
nonnegative pure-int off/stored and UTF-8/RecursionError in check_carve_index(),
avoid double-parsing index.json in main(), validate --shaders and
trailing-separator --json paths upfront, and write --json atomically
with published_mode and replace_retry.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 11:24:41 +00:00
Author
Owner

@⁠lixonik on GitHub · 2026-11-26 10:58 UTC · original · reviewed

Windows 11: 14/14 Python tests passed. Two additional checks on a synthetic carve reproduced a missed output collision and a second index.json parse. Details inline.

AI-assisted.

**@⁠lixonik** on GitHub · 2026-11-26 10:58 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#pullrequestreview-6072924808) · **reviewed** Windows 11: 14/14 Python tests passed. Two additional checks on a synthetic carve reproduced a missed output collision and a second `index.json` parse. Details inline. AI-assisted.
@ -371,3 +383,3 @@
rows: list[dict] | None = None) -> None:
"""Refuse a --json destination that is a directory or aliases any input file."""
if os.path.isdir(out_path):
if os.path.isdir(out_path) or out_path.endswith(("/", "\\")):
Author
Owner

@⁠lixonik on GitHub · 2026-11-26 10:58 UTC · original

[P2] Reject reports that would overwrite a .bk2 carve input.

DirectorySource.read() reads <off>.bk2 for type: "bink2", while the delegated gamedata_maps.check_report_path() checks only .bin. I used a single synthetic row at offset 4096 and set --json to the corresponding 000000001000.bk2 file. The CLI returned 0 and atomically replaced that input with the JSON report. Can the guard use the same filename rule as DirectorySource.read() for both payload types?

**@⁠lixonik** on GitHub · 2026-11-26 10:58 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#discussion_r4707375737) [P2] Reject reports that would overwrite a `.bk2` carve input. `DirectorySource.read()` reads `<off>.bk2` for `type: "bink2"`, while the delegated `gamedata_maps.check_report_path()` checks only `.bin`. I used a single synthetic row at offset 4096 and set `--json` to the corresponding `000000001000.bk2` file. The CLI returned 0 and atomically replaced that input with the JSON report. Can the guard use the same filename rule as `DirectorySource.read()` for both payload types?
@ -402,3 +444,3 @@
if a.json:
check_report_path(a.json, a.target, a.shaders, rows=rows)
payloads = read_payloads(a.target)
payloads = read_payloads(a.target, _checked_index=is_dir)
Author
Owner

@⁠lixonik on GitHub · 2026-11-26 10:58 UTC · original

[P3] Pass the parsed index through to DirectorySource if the CLI should parse it once.

Spying on json.load for the synthetic carve shows two real reads of index.json. _checked_index skips another call to check_carve_index(), while DirectorySource.__init__ opens and parses the file again. The new test counts calls to the validator only, so it misses this second read. Reusing the validated document would also keep path validation and payload reading on the same index snapshot.

**@⁠lixonik** on GitHub · 2026-11-26 10:58 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#discussion_r4707375744) [P3] Pass the parsed index through to `DirectorySource` if the CLI should parse it once. Spying on `json.load` for the synthetic carve shows two real reads of `index.json`. `_checked_index` skips another call to `check_carve_index()`, while `DirectorySource.__init__` opens and parses the file again. The new test counts calls to the validator only, so it misses this second read. Reusing the validated document would also keep path validation and payload reading on the same index snapshot.
Author
Owner

@⁠tiguan26 on GitHub · 2026-11-27 04:36 UTC · original · approved these changes

Approving d1545dfde.

The unshipped-count fix is real: entries - len(in_db0) - len(in_db1) subtracted a stem present in both databases twice (it could go negative); counting stems in neither set is right. Index rows now need nonnegative integer off/stored, bad UTF-8 is reported, the index is not checked twice, and the JSON is written atomically.

Merged onto main d1dff7949 in one batch with 22 other tool PRs of this series (no conflicts), on Linux with Python 3.13. tests/test_gamedata_blobs.py: 14 passed (main: 10). AI-assisted (Claude Code, Claude Opus 5.5).

**@⁠tiguan26** on GitHub · 2026-11-27 04:36 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#pullrequestreview-6083536098) · **approved these changes** Approving d1545dfde. The unshipped-count fix is real: `entries - len(in_db0) - len(in_db1)` subtracted a stem present in both databases twice (it could go negative); counting stems in neither set is right. Index rows now need nonnegative integer `off`/`stored`, bad UTF-8 is reported, the index is not checked twice, and the JSON is written atomically. Merged onto `main` `d1dff7949` in one batch with 22 other tool PRs of this series (no conflicts), on Linux with Python 3.13. `tests/test_gamedata_blobs.py`: 14 passed (main: 10). AI-assisted (Claude Code, Claude Opus 5.5).
@ -371,3 +392,3 @@
rows: list[dict] | None = None) -> None:
"""Refuse a --json destination that is a directory or aliases any input file."""
if os.path.isdir(out_path):
if os.path.isdir(out_path) or out_path.endswith(("/", "\\")):
Author
Owner

@⁠kirigayakazima on GitHub · 2026-11-27 12:07 UTC · original

Fixed: check_report_path() now checks each row's resolved .bk2/.bin payload path matching DirectorySource.read(), rejecting --json destinations that alias .bk2 carve inputs. Added regression coverage in tests/test_gamedata_blobs.py.

**@⁠kirigayakazima** on GitHub · 2026-11-27 12:07 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#discussion_r4719169834) Fixed: `check_report_path()` now checks each row's resolved `.bk2`/`.bin` payload path matching `DirectorySource.read()`, rejecting `--json` destinations that alias `.bk2` carve inputs. Added regression coverage in `tests/test_gamedata_blobs.py`.
Author
Owner

@⁠kirigayakazima on GitHub · 2026-11-27 12:07 UTC · original
On tools/gamedata_blobs.py line 446 (outdated):

@@ -395,15 +434,18 @@ def main(argv=None) -> int:
         print(f"ERROR: cannot read {a.target}: no such file or folder", file=sys.stderr)
         return 2
     try:
+        if a.shaders and not os.path.isfile(a.shaders):
+            raise ValueError(f"{a.shaders}: no such file")
         if a.json:
             check_report_path(a.json, a.target, a.shaders)
-        if os.path.isdir(a.target):
+        is_dir = os.path.isdir(a.target)
+        if is_dir:
             rows = check_carve_index(a.target)
             if a.json:
                 check_report_path(a.json, a.target, a.shaders, rows=rows)
-        payloads = read_payloads(a.target)
+        payloads = read_payloads(a.target, _checked_index=is_dir)

Fixed: main() passes the already-validated rows to read_payloads(..., _rows=rows) using _LoadedDirectorySource, so index.json is opened and parsed once cleanly. Verified via json.load spy in tests/test_gamedata_blobs.py (15 tests OK + 5 repo checks).

**@⁠kirigayakazima** on GitHub · 2026-11-27 12:07 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#discussion_r4719170288) On `tools/gamedata_blobs.py` line 446 (outdated): ```diff @@ -395,15 +434,18 @@ def main(argv=None) -> int: print(f"ERROR: cannot read {a.target}: no such file or folder", file=sys.stderr) return 2 try: + if a.shaders and not os.path.isfile(a.shaders): + raise ValueError(f"{a.shaders}: no such file") if a.json: check_report_path(a.json, a.target, a.shaders) - if os.path.isdir(a.target): + is_dir = os.path.isdir(a.target) + if is_dir: rows = check_carve_index(a.target) if a.json: check_report_path(a.json, a.target, a.shaders, rows=rows) - payloads = read_payloads(a.target) + payloads = read_payloads(a.target, _checked_index=is_dir) ``` Fixed: `main()` passes the already-validated `rows` to `read_payloads(..., _rows=rows)` using `_LoadedDirectorySource`, so `index.json` is opened and parsed once cleanly. Verified via `json.load` spy in `tests/test_gamedata_blobs.py` (15 tests OK + 5 repo checks).
Author
Owner

@⁠lixonik on GitHub · 2026-11-27 14:23 UTC · original · reviewed

Re-checked at 843a265f4 (merged onto main ec91d695c).

Both earlier points are cleanly addressed:

  • check_report_path() now rejects .bk2 and .bin carve-input aliases matching DirectorySource.read().
  • _LoadedDirectorySource reuses the validated sorted rows from check_carve_index() so index.json is parsed once, covered by the json.load spy test.

Verified locally on Windows 11 (Python 3):

  • tests/test_gamedata_blobs.py: 15/15 passed
  • scripts/check_no_game_data.py and git diff --check: clean

No remaining findings.

AI-assisted.

**@⁠lixonik** on GitHub · 2026-11-27 14:23 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2258#pullrequestreview-6089570550) · **reviewed** Re-checked at `843a265f4` (merged onto `main` `ec91d695c`). Both earlier points are cleanly addressed: - `check_report_path()` now rejects `.bk2` and `.bin` carve-input aliases matching `DirectorySource.read()`. - `_LoadedDirectorySource` reuses the validated sorted rows from `check_carve_index()` so `index.json` is parsed once, covered by the `json.load` spy test. Verified locally on Windows 11 (Python 3): - `tests/test_gamedata_blobs.py`: 15/15 passed - `scripts/check_no_game_data.py` and `git diff --check`: clean No remaining findings. AI-assisted.
This pull request can be merged automatically.
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 '+refs/pull/2258/head:github-bot/gh-2258'
git switch 'github-bot/gh-2258'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2258'
git switch 'github-bot/gh-2258'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2258'
git switch 'github-bot/gh-2258'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2258'
git switch 'main'
git merge --squash 'github-bot/gh-2258'
git switch 'main'
git merge --ff-only 'github-bot/gh-2258'
git switch 'main'
git merge 'github-bot/gh-2258'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.