pe: harden pe_inventory changes and CLI validation with unit suite #1963

Merged
Ammmae0x merged 3 commits from upstream-pr/1970 into main 2026-11-24 22:45:28 +00:00
Ammmae0x commented 2026-11-24 22:19:49 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-24T22:19:49Z.


Change

Harden changes() schema/structure validation and CLI error handling in tools/pe_inventory.py, and add a synthetic AMD64 PE32+ unit and CLI validation suite (pe_inventory_cli_check) in tests/pe_inventory_cli_check.py, registered in CMakeLists.txt.

  • Validate old/new dict types, "schema" presence/equality, and "images" (dict) / "imports" (list) structure in changes() so malformed inventory payloads raise ValueError instead of KeyError or TypeError.
  • Refactor main(argv=None) -> int in tools/pe_inventory.py to accept an optional argv, verify root.is_dir(), unlink temporary JSON files if atomic replacement fails, and exit cleanly with code 1 (no traceback) on (OSError, ValueError, json.JSONDecodeError, pefile.PEFormatError), while keeping exit code 2 via parser.error(...) when --output is inside the input tree or aliases --baseline.
  • Add tests/pe_inventory_cli_check.py covering changes() diff categories, atomic JSON output + --baseline diffing, and negative controls for schema mismatches, missing/empty/malformed input directories, missing/invalid/mismatched --baseline files, and invalid --output paths.

Verification

  • Direct Python suite: .\out\pe-env\Scripts\python.exe -B tests/pe_inventory_cli_check.py -v -> Ran 6 tests in 1.009s (OK); tests/pe_package_preflight_check.py (14/14 OK); tests/intake/import_forms_check.py, tests/intake/paths_check.py, and tests/intake/routing_check.py all passed.
  • Mutation sanity check (temporarily reverting tools/pe_inventory.py to upstream/main): Ran 6 tests -> FAILED (failures=1, errors=3) (KeyError: 'schema', missing argv parameter in main, and traceback on missing input directory).
  • dev preset (rebased onto upstream/main 3682b34f; Total Tests: 1254): ctest --preset dev --no-tests=error -R "^(pe_inventory_cli_check|pe_package_import_closure|pe_package_ordinal_plan|static_exe_intake|conditional_import_paths|bundled_export_forwarders)$" -V -> 6/6 passed (pe_package_ordinal_plan 3/3, conditional_import_paths, static_exe_intake, bundled_export_forwarders, pe_package_import_closure 14/14, pe_inventory_cli_check 6/6).
  • release preset (rebased onto upstream/main 3682b34f; Total Tests: 1254): ctest --preset release --no-tests=error -R "^(pe_inventory_cli_check|pe_package_import_closure|pe_package_ordinal_plan|static_exe_intake|conditional_import_paths|bundled_export_forwarders)$" -V -> 6/6 passed.
  • Repo checks: tests/form_coverage_check.py, tests/docs_links_check.py, and tests/bidi_controls_check.py all exited 0.

Evidence and follow-up

  • tests/pe_inventory_cli_check.py constructs minimal synthetic AMD64 PE32+ binaries in memory with normal and delay import tables using synthetic module/symbol names and zero external binaries or game files.
  • This change is AI-assisted.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6592552334 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1970). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-24T22:19:49Z. --- ## Change Harden `changes()` schema/structure validation and CLI error handling in `tools/pe_inventory.py`, and add a synthetic AMD64 PE32+ unit and CLI validation suite (`pe_inventory_cli_check`) in `tests/pe_inventory_cli_check.py`, registered in `CMakeLists.txt`. - Validate `old`/`new` dict types, `"schema"` presence/equality, and `"images"` (dict) / `"imports"` (list) structure in `changes()` so malformed inventory payloads raise `ValueError` instead of `KeyError` or `TypeError`. - Refactor `main(argv=None) -> int` in `tools/pe_inventory.py` to accept an optional `argv`, verify `root.is_dir()`, unlink temporary JSON files if atomic replacement fails, and exit cleanly with code `1` (no traceback) on `(OSError, ValueError, json.JSONDecodeError, pefile.PEFormatError)`, while keeping exit code `2` via `parser.error(...)` when `--output` is inside the input tree or aliases `--baseline`. - Add `tests/pe_inventory_cli_check.py` covering `changes()` diff categories, atomic JSON output + `--baseline` diffing, and negative controls for schema mismatches, missing/empty/malformed input directories, missing/invalid/mismatched `--baseline` files, and invalid `--output` paths. ## Verification - Direct Python suite: `.\out\pe-env\Scripts\python.exe -B tests/pe_inventory_cli_check.py -v` -> `Ran 6 tests in 1.009s` (`OK`); `tests/pe_package_preflight_check.py` (`14/14 OK`); `tests/intake/import_forms_check.py`, `tests/intake/paths_check.py`, and `tests/intake/routing_check.py` all passed. - Mutation sanity check (temporarily reverting `tools/pe_inventory.py` to `upstream/main`): `Ran 6 tests` -> `FAILED (failures=1, errors=3)` (`KeyError: 'schema'`, missing `argv` parameter in `main`, and traceback on missing input directory). - `dev` preset (rebased onto `upstream/main` `3682b34f`; `Total Tests: 1254`): `ctest --preset dev --no-tests=error -R "^(pe_inventory_cli_check|pe_package_import_closure|pe_package_ordinal_plan|static_exe_intake|conditional_import_paths|bundled_export_forwarders)$" -V` -> `6/6` passed (`pe_package_ordinal_plan` 3/3, `conditional_import_paths`, `static_exe_intake`, `bundled_export_forwarders`, `pe_package_import_closure` 14/14, `pe_inventory_cli_check` 6/6). - `release` preset (rebased onto `upstream/main` `3682b34f`; `Total Tests: 1254`): `ctest --preset release --no-tests=error -R "^(pe_inventory_cli_check|pe_package_import_closure|pe_package_ordinal_plan|static_exe_intake|conditional_import_paths|bundled_export_forwarders)$" -V` -> `6/6` passed. - Repo checks: `tests/form_coverage_check.py`, `tests/docs_links_check.py`, and `tests/bidi_controls_check.py` all exited `0`. ## Evidence and follow-up - `tests/pe_inventory_cli_check.py` constructs minimal synthetic AMD64 PE32+ binaries in memory with normal and delay import tables using synthetic module/symbol names and zero external binaries or game files. - This change is AI-assisted. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [ ] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets.
upstream-sync closed this pull request 2026-11-24 23:03:20 +00:00
ChazY11 commented 2026-11-24 23:03:38 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by ChazY11 on 2026-11-24T22:26:35Z.


Ran it, broke five things: two caught, and two of the three survivors are real

Windows 11 build 26300.9974:

out/pe-env/Scripts/python.exe -B tests/pe_inventory_cli_check.py
Ran 6 tests in 1.763s
OK      exit 0
mutation in tools/pe_inventory.py result
except (OSError, ValueError, json.JSONDecodeError, pefile.PEFormatError) → except (KeyboardInterrupt,) caught
parser.exit(1, …) → parser.exit(0, …) caught
raise ValueError("Invalid inventory structure") → pass not caught
if not root.is_dir(): → if False: not caught (equivalent, see below)
isinstance half of the schema guard disabled not caught (equivalent, see below)

The structure check is unpinned, and its failure modes are the ones this PR exists to remove

I drove the CLI end-to-end with a real synthetic PE in the root and a baseline whose structure is wrong:

unmutated:   images: []   exit=1  Invalid inventory structure
             imports: {}  exit=1  Invalid inventory structure

check silenced:
             images: []   exit=1  AttributeError: 'list' object has no attribute 'keys'
                                  TRACEBACK present
             imports: {}  exit=0  (no stderr)

Two separate problems, both invisible to the suite:

  1. AttributeError is not in the caught tuple, so a baseline with "images": [] prints a Python traceback and exits 1 — the exact class of output this PR was written to stop. changes() raises ValueError for that shape only because of the guard being mutated here.
  2. "imports": {} is silently accepted and the run exits 0, producing a diff as if the baseline had no imports. A wrong diff that looks like a clean run is worse than a refusal.

The fixture asserts the CLI boundary and the diff categories, but nothing feeds changes() a structurally wrong payload, so both survive.

Suggested cases — the first is the one I would insist on:

def test_malformed_baseline_structure_is_refused_without_a_traceback(self):
    base = json.loads(json.dumps(scan(root)))
    for bad in (dict(base, images=[]), dict(base, imports={})):
        baseline = pathlib.Path(tmp) / "bad.json"
        baseline.write_text(json.dumps(bad), encoding="utf-8")
        proc = self._run_cli(root, out, baseline)
        self.assertEqual(proc.returncode, 1)
        self.assertNotIn("Traceback", proc.stderr)
        self.assertIn("Invalid inventory structure", proc.stderr)

The two survivors I checked and am not reporting

  • if not root.is_dir(): removed: a file as --directory still exits 1 in both runs, because resolve(strict=True)/scan() raise an OSError that the handler catches. Different message, same outcome.
  • The isinstance half of the schema guard removed: "schema" not in old already refuses a list or a string, so changes() raises ValueError: Inventory schema mismatch either way. Redundant, not load-bearing.

I am stating both because a reader of the mutation table would otherwise think three behaviours are untested when only one is.

What the rest does well

Exit code 2 for --output inside the input tree or aliasing the baseline (via parser.error) versus 1 for runtime failures is the right split — a caller scripting this can tell "I passed a bad path" from "the run failed". Unlinking the temporary JSON when the atomic replace fails is the kind of cleanup that is usually missing.

Verdict

Reviewed. The CLI boundary is pinned; the new structure check is not, and its two failure modes are a leaked traceback and a silently wrong diff.

Notes

  • AI-assisted review.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7146234666 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1970#issuecomment-7146234666). Originally posted by [ChazY11](https://github.com/ChazY11) on 2026-11-24T22:26:35Z. --- ## Ran it, broke five things: two caught, and two of the three survivors are real Windows 11 build 26300.9974: ```powershell out/pe-env/Scripts/python.exe -B tests/pe_inventory_cli_check.py Ran 6 tests in 1.763s OK exit 0 ``` | mutation in `tools/pe_inventory.py` | result | |---|---| | `except (OSError, ValueError, json.JSONDecodeError, pefile.PEFormatError)` → `except (KeyboardInterrupt,)` | **caught** | | `parser.exit(1, …)` → `parser.exit(0, …)` | **caught** | | `raise ValueError("Invalid inventory structure")` → `pass` | **not caught** | | `if not root.is_dir():` → `if False:` | not caught (equivalent, see below) | | isinstance half of the schema guard disabled | not caught (equivalent, see below) | ## The structure check is unpinned, and its failure modes are the ones this PR exists to remove I drove the CLI end-to-end with a real synthetic PE in the root and a baseline whose structure is wrong: ```text unmutated: images: [] exit=1 Invalid inventory structure imports: {} exit=1 Invalid inventory structure check silenced: images: [] exit=1 AttributeError: 'list' object has no attribute 'keys' TRACEBACK present imports: {} exit=0 (no stderr) ``` Two separate problems, both invisible to the suite: 1. **`AttributeError` is not in the caught tuple**, so a baseline with `"images": []` prints a Python traceback and exits 1 — the exact class of output this PR was written to stop. `changes()` raises `ValueError` for that shape only because of the guard being mutated here. 2. **`"imports": {}` is silently accepted** and the run exits **0**, producing a diff as if the baseline had no imports. A wrong diff that looks like a clean run is worse than a refusal. The fixture asserts the CLI boundary and the diff categories, but nothing feeds `changes()` a structurally wrong payload, so both survive. Suggested cases — the first is the one I would insist on: ```python def test_malformed_baseline_structure_is_refused_without_a_traceback(self): base = json.loads(json.dumps(scan(root))) for bad in (dict(base, images=[]), dict(base, imports={})): baseline = pathlib.Path(tmp) / "bad.json" baseline.write_text(json.dumps(bad), encoding="utf-8") proc = self._run_cli(root, out, baseline) self.assertEqual(proc.returncode, 1) self.assertNotIn("Traceback", proc.stderr) self.assertIn("Invalid inventory structure", proc.stderr) ``` ## The two survivors I checked and am *not* reporting - `if not root.is_dir():` removed: a file as `--directory` still exits 1 in both runs, because `resolve(strict=True)`/`scan()` raise an `OSError` that the handler catches. Different message, same outcome. - The `isinstance` half of the schema guard removed: `"schema" not in old` already refuses a list or a string, so `changes()` raises `ValueError: Inventory schema mismatch` either way. Redundant, not load-bearing. I am stating both because a reader of the mutation table would otherwise think three behaviours are untested when only one is. ## What the rest does well Exit code `2` for `--output` inside the input tree or aliasing the baseline (via `parser.error`) versus `1` for runtime failures is the right split — a caller scripting this can tell "I passed a bad path" from "the run failed". Unlinking the temporary JSON when the atomic replace fails is the kind of cleanup that is usually missing. ## Verdict Reviewed. The CLI boundary is pinned; the new structure check is not, and its two failure modes are a leaked traceback and a silently wrong diff. ## Notes - AI-assisted review.
Ammmae0x commented 2026-11-24 23:03:39 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-24T22:32:44Z.


Updated PR #1970 (commit cc171feb) to address the unpinned structure-validation finding:

  • Added test_malformed_baseline_structure_is_refused_without_a_traceback in tests/pe_inventory_cli_check.py driving the CLI end-to-end with synthetic PE baselines containing "images": [] and "imports": {} (asserting exit code 1, no traceback, Invalid inventory structure in stderr, and no output file created).
  • Expanded test_changes_schema_and_structure_validation_raises_value_error and test_missing_empty_and_malformed_input_dirs_exit_1_without_traceback to pin direct changes() structure checks (old and new) and file-as-directory refusal (Not a directory:).

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7146358243 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1970#issuecomment-7146358243). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-24T22:32:44Z. --- Updated PR #1970 (commit `cc171feb`) to address the unpinned structure-validation finding: - Added `test_malformed_baseline_structure_is_refused_without_a_traceback` in `tests/pe_inventory_cli_check.py` driving the CLI end-to-end with synthetic PE baselines containing `"images": []` and `"imports": {}` (asserting exit code `1`, no traceback, `Invalid inventory structure` in stderr, and no output file created). - Expanded `test_changes_schema_and_structure_validation_raises_value_error` and `test_missing_empty_and_malformed_input_dirs_exit_1_without_traceback` to pin direct `changes()` structure checks (`old` and `new`) and file-as-directory refusal (`Not a directory:`). AI-assisted.
R0Y00 commented 2026-11-24 23:03:40 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T22:40:24Z.


Three source-built CLI inputs still raised tracebacks on the preceding head: missing image digest, missing import fields and a list-valued symbol. Added nested validation and pinned all three refusals. The inventory CLI suite passed 7/7 and the adjacent PE preflight suite passed 14/14 on Windows.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7146509407 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1970#issuecomment-7146509407). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T22:40:24Z. --- Three source-built CLI inputs still raised tracebacks on the preceding head: missing image digest, missing import fields and a list-valued symbol. Added nested validation and pinned all three refusals. The inventory CLI suite passed 7/7 and the adjacent PE preflight suite passed 14/14 on Windows.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!1963
No description provided.