tooling: extend the patch manifest loader (nesting refusal, shader kind, load_data) #3119
No reviewers
Labels
No labels
accessibility
awaiting author
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
priority: P0
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/R0Y00--Xbox2Windows!3119
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-3119"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@JohnConnorNPC on GitHub · 2026-11-27 16:01 UTC · original
JohnConnorNPC:patches/loader-extend→main· +413 −9 · 3 files · 15 commits · merged 2026-11-28 08:02 UTCRefs #3037 (follows #3056; no applier yet).
What changes
tools/patch_manifest.pykeeps its format, its strictness (lowercase hex, integerrva, parse-time span and overlap checks) and its CLI (patch manifest: <reason>, exit status 1). It gains three behaviors:tomllibrecurses once per nested array or inline table, so a manifest nested past the recursion limit raisedRecursionError, and the CLI printed a traceback. It is now refused asmanifest is nested too deeply to parse.kind = "shader": the translation files of one shader cache key, for the shader-cache translation override named in #3037. It is checked for shape only.keyis 16 lowercase hex digits andpipelineisgraphics,computeormesh86.revisionmust have the form of that pipeline's key revision:x2w-startup-shader-<n>,x2w-startup-shader-<n>csorx2w-startup-mesh-86-<n>. The loader does not check that<n>is the runtime's current number, because the runtime bumps it often; a later consumer that serves the files must compare it with the runtime (none exists yet).filesis a non-empty array of{ ext, file, sha256 }tables using the pipeline's extensions, each listed once, with the required ones present.fileis a bare file name, for a later consumer to resolve in the manifest's directory.not supported.load_data(manifest, data):loadfor a caller that has already read the input. It hashesdata, so the bytes that pass the gate are the bytes the caller then patches or translates, even if the file changes in between.loadis unchanged and shares the target comparison.docs/experiments/patch-manifests.mdgains the shader format, its pipeline table, the new cases and the mutations.Fixture
tests/patch_manifest_check.pykeeps its three tests and adds five, all on the same synthetic PE32+ (build_pe32_plus). Registration is unchanged (tests/checks/python-linux/patch_manifest.txt, CTestpatch_manifest_controls).parseand through the CLI (status 1, empty stdout, no traceback). Shape control: a 50-deep array gets pasttomlliband is refused only for its unknown key.filevalues that are not bare names.cache_path(..., L"", key, ext)and mesh86'sload_stage). mesh86's.ps.csois the only optional one.load_data: the image's bytes give the same result asload, and the flipped image is refused. After the input file is replaced by the flipped image,load_dataon the original bytes still loads andloadon the file is refused.Mutations, each run once on the final tree with the file restored by hash:
RecursionErrorno longer caughttest_deep_nesting_is_refusederrorstest_shader_patches(5 failures)test_shader_patches(2 failures)test_shader_patches(1 failure)fileremovedtest_shader_patches(6 failures)d3d12_draw.inlreads.vx.csoinstead of.vs.csotest_shader_files_match_the_runtimefails-29b)test_shader_revision_forms_match_the_runtimefails-29to-30)load_datacompares the target with itselftest_load_data_gates_the_bytes_givenfailsTested
Commit
13269fb5onmainca659396, Linux (Debian 13), Python 3.13.5, pefile 2024.8.26:Not run on Windows; the CTest registration is unchanged and was not exercised.
This PR was AI-assisted.
@thepatrickworld on GitHub · 2026-11-27 17:39 UTC · original
Independent audit of the fixture's coverage on
13269fb5: 16 of 24 mutations killed, eight survive, and the memory kind's multi-patch geometry is not pinnedNot a code change; measurements only.
Environment
PYTHONPATH.13269fb5,git status --porcelain --untracked-files=noempty. Diff againstorigin/main(63a30dc1): 3 files, +290/−5.tools/patch_manifest.pyec0c1fb0dad12cdb5a845457c830208a01ee2cb84fb06dd0ba159743e907db35,tests/patch_manifest_check.py17ccc58ca44c9fb39027a5727f6c6ba3f8eacc4033422bea7754fbc0a90a9565,docs/experiments/patch-manifests.mdf269c786524f3e1427333c665904a1091b05a5b73f5f99767ec34c55db6d8ad3.Ran 8 tests in 0.321s…OK, rc=0. No Windows, no GPU needed: the fixture is pure Python.Commands
Each mutation below is applied alone, as a single
str.replacewhosecount(old)is asserted to be 1 first, then the fixture is run, thengit checkout -- tools/patch_manifest.py. The file's sha256 is printed before the matrix and after every restore, and isec0c1fb0…in all 24 cases, so no mutant leaks into the next run.Observed — 24 mutations, 16 killed
if not isinstance(entry["bytes"], str) or not HEX.fullmatch(entry["bytes"]):→if False:(positive control)bytes must beexcept RecursionError:→except ZeroDivisionError:test_deep_nesting_is_refused"[1-9][0-9]*"→"[0-9]+"(<n>accepts a leading zero)revision 'x2w-startup-shader-012cs'REVISIONS[pipeline].fullmatch(revision)→.match(revision)s002 revision 'x2w-startup-shader-12cs' is not a graphics key revisionKEY.fullmatch(key)→KEY.match(key)SHA256.fullmatch(value)→SHA256.match(value)for c in "/\\:"→for c in "/\\"(drive letter allowed)file 'C:s001.txt' must be a bare file nameor name in (".", "..")→or Falsefile '..' must be a bare file name(+1)if False:patches s001 and s002 override the same keyif ext in files:→if False:s001 lists .txt twiceif missing := [...]→if False:compute override is missing: .cs.cso(+1)or not entry["files"]removedfiles must be a non-empty arrayif start < end:→if start <= end:not 0 <= rva < 1 << 32→not 0 < rva < 1 << 32type(rva) is not int→not isinstance(rva, int)rva must beif not value.strip():→if not value:remove_when must be a non-empty.ps.csotest_shader_files_match_the_runtimehashlib.sha256(data).hexdigest()→ hash of the manifest's file nametest_load_data_gates_the_bytes_given"files": list(files.values())→[::-1]test_shader_patchespatches.append(patch)+continue→continueremovedKeyError: 'rva'except (ValueError, OSError)→except ValueErrorspans.sort()→passHEX = re.compile(r"(?:[0-9a-f]{2})+")→*"why": _text(...)removedThe mutation table in
docs/experiments/patch-manifests.mdis accurate for every row I re-ran in another form:RecursionErrorno longer caught, revision form check, bare-name check, required-file check and same-key check all killed the mutant here too. It covers "Overlap check removed" but not the neighbouring off-by-one, while it does cover "Span check off by one (>=)" for the RVA bound.The eight survivors, each with its witness
Run on the same manifest, head versus mutant in place.
KEYandinput_sha256accept trailing text (lines 90 and 74).KEY.fullmatch→match; key"00c0ffee0badf00dzz": headValueError: patch s001 key must be 16 lowercase hex digits, mutantparse ACCEPTED 1 patchcarrying that 18-character key. Same forinput_sha256= 64 hex digits +"garbage": headValueError: input_sha256 must be 64 lowercase hex digits, mutant accepts, and the hash gate then refuses withmanifest is for another input: manifest input_sha256 aaaa…garbage, input sha256 8573…— a message that sends the author to the input file when the malformed field is in the manifest. Note the revision check is not in this class:.matchthere is killed, because a graphics form matches the compute revisionx2w-startup-shader-12cs(the cross-pipeline case does double duty).Patch adjacency and ordering (lines 165–167).
if start < end:→<=: patches[0x1010, 0x1012)and[0x1012, 0x1014)— headparse ACCEPTED 2 patches, mutantValueError: patches p001 and p002 overlap. Withoutspans.sort(), the same two disjoint patches listed in descending RVA (p002at0x1020first,p001at0x1010) are accepted head and refusedpatches p002 and p001 overlapunder the mutant. Both are refusals of a valid manifest, and the fixture cannot see them: its only accepted manifest with more than one patch isp001plus four shader patches (tests/patch_manifest_check.py:153), and its only overlap case duplicates the same span (:110,ok + second). So no accepted manifest in the fixture carries two memory patches at all — neither adjacency, nor order, nor two disjoint patches are pinned.bytesis claimed non-empty, not pinned.HEX+→*:bytes = ""is refused head (bytes must be a non-empty, even number of lowercase hex digits) and accepted by the mutant as a patch whosebyteshas length 0. The fixture's onlybytesrefusal is the odd-length"90c"(:111).rvabottom edge (line 147).0 <= rva→0 < rva: a patch atrva = 0x0is accepted head and refused by the mutant. Decorative in practice — a patch at RVA 0 has no meaning in a PE32+ — but it is the lower end of the range the message documents, and only the upper end (0xffffffffplus one byte accepted, plus two refused,:124-126) is pinned.The memory patch's output field is unpinned. Removing
"why": _text(entry["why"], f"{where} why")from the memory dict (line 159) survives: head returns keys['bytes', 'expect_sha256', 'id', 'kind', 'remove_when', 'rva', 'why'], the mutant six of them. The fixture assertsid,rvaandbytesfor the memory kind, so a field can be dropped from the caller's view in silence.The CLI's
OSErrorbranch (line 202).except (ValueError, OSError)→except ValueError, with a manifest path that does not exist: head printspatch manifest: [Errno 2] No such file or directory: '<path>', rc=1; the mutant ends in a traceback (FileNotFoundError: [Errno 2] …), rc=1. The exit status is unchanged, so this is a diagnostic contract, not behaviour — and the class is partly pinned already, since the deep-nesting case asserts rc=1 with no traceback. What is not pinned isENOENT/EACCESon the manifest itself.What this does not say
tests/checks/python-linux/patch_manifest.txtand thepython-linuxjob (.github/workflows/windows.yml:182, noif:) runs it on every pull request, so this is the gate the change lands behind; the Windowsctest --preset prregex does not selectpatch_manifest_controls.rva = 0); two are shape checks that accept trailing text, and one of those then produces a misleading message from the gate; one accepts a zero-lengthbytes; one drops an output field; one is stderr only.tools/__pycache__was present at any point. Worth knowing for anyone repeating this:python3 -Bstops Python from writing bytecode, not from reading an existing.pyc, so a stale cache would make a survivor fake.d3d12_draw.inl,mesh86_cache.inl) were read, not re-run.AI-assisted.
@JohnConnorNPC on GitHub · 2026-11-27 17:51 UTC · original
Thank you for the audit, @thepatrickworld. I re-ran your 24 mutations at
13269fb5and got the same result: 16 killed, the same 8 survive, none of them an equivalent mutant. Seven of the eight sit in the memory code from #3056 (theKEYone is ours).I pushed two commits to this branch:
input_sha256andexpect_sha256with trailing text, emptybytes, a full-dict check ofp001, a missing input file through the CLI (status 1, no traceback), and a side-by-side test of two memory patches (descending order, adjacent, one at RVA 0, and a one-byte overlap refused in both orders).With them, all 24 mutations are killed.
patch_manifest_checkruns 9 tests OK,docs_linksandbidipass. Thanks also for the Python 3.11.16 datum: the deep-nesting case holds there too.This comment was AI-assisted.
@thepatrickworld on GitHub · 2026-11-27 18:18 UTC · original
Independent re-run on
4968e124: the 24 mutants are killed, and one more survivesNot a code change; measurements only
What was measured
The 24 mutations from the audit at
13269fb5, plus four aimed at the assertions you added, applied one at atime to
tools/patch_manifest.pywith the fixture re-run after each, then restored withgit checkout -- tools/patch_manifest.pyand its sha256 compared before the next mutant (a mismatch wouldhave aborted the run; final sha256
ec0c1fb0dad12cdb5a845457c830208a01ee2cb84fb06dd0ba159743e907db35).tools/patch_manifest.pyis byte-identical between13269fb5and4968e124, so every kill below comes fromthe new tests, not from a change in the loader. Fixture measured:
27af1a89897561fc9797da6f5c6f68fc5cf93f689f6fa27cf17c87e001cbb882.Environment
Commands
The Windows run used a directory holding a copy of
tools/,tests/patch_manifest_check.py,tests/call_evidence_check.pyandsrc/startup_stubs/, because the fixture resolvesROOTfrom its ownpath; the tool and fixture sha256 above are the ones it ran.
Observed: the eight that survived at
13269fb5Each is now killed, by the case that targets it:
KEY.fullmatch->match:test_shader_patches,patch s001 key must be 16 lowercase hex digits(17 digits).SHA256.fullmatch->match:test_malformed_manifests_are_refused, bothinput_sha256 must be 64 lowercase hex digitsandp001 expect_sha256 must be 64(trailing text).start < end->start <= end:test_memory_patches_side_by_side, which raises on the four adjacent patches.spans.sort()removed:test_memory_patches_side_by_side, which raises on the descending order.bytespattern+->*:test_malformed_manifests_are_refused,p001 bytes must be a non-empty.whydropped from a memory patch:test_bound_input_loads, on the full-dict comparison.0 <= rva->0 < rva:test_memory_patches_side_by_side, which raises on the patch at RVA 0.except (ValueError, OSError)->except ValueError:test_wrong_input_is_refused, on the missing input (traceback instead ofpatch manifest: [Errno).Three further probes of the new assertions are killed too:
spans.sort(reverse=True),remove_whendroppedfrom a memory patch, and the overlap guard removed.
The nine tests on Windows
Ran 9 tests in 0.648sthenOKat4968e124, which closes the "Not yet run on Windows" line indocs/experiments/patch-manifests.md. The same 28 mutants give the same verdict there, so the kills do notdepend on the 3.13 interpreter. It is not the CI path: the
python-linuxjob runs 3.12.One survivor
spans.sort()->spans.sort(key=lambda s: s[2])passes all nine tests on both machines. It is material,not equivalent: a manifest that lists four memory patches with ids that do not follow the addresses
(
p000atSECTION_RVA + 4,p001at+ 2,p002atSECTION_RVA,p003at0, same two-bytereplacement) is accepted at
4968e124and refused aspatches p000 and p001 overlapunder the mutant. Youraccept case pairs ids that ascend as the addresses descend (
p003at+ 4...p000at0), which is theorder an id sort happens to produce.
One-line remedy, verified: decorrelate the ids in that case,
(("p000", SECTION_RVA + 4), ("p001", SECTION_RVA + 2), ("p002", SECTION_RVA), ("p003", 0))with theexpected list below it. With that edit the head stays green and the mutant fails on
test_memory_patches_side_by_side.Limits
format beyond them.
AI-assisted.
@KelboLive on GitHub · 2026-11-27 18:51 UTC · original · approved these changes
Clean extension of the patch manifest loader. Deep nesting protection via RecursionError catch prevents tracebacks, shader patch support adds proper shape validation (key format, pipeline enum, revision regex, bare-name file check), and
load_data()correctly gates on caller-provided bytes rather than re-reading from disk. The 28 refusal cases covering every rule plus the mutation audit provide thorough verification. Approved.@pigalot on GitHub · 2026-11-27 20:47 UTC · original · requested changes
I reviewed
4968e124merged over currentmain9e7eab5b. The merge is clean (treecf564d9e) andgit diff --cached --checkis clean.What I ran on Windows. After
cmake --preset <dev|release>:3/3 pass in both presets.
out\pe-env\Scripts\python.exe -B tests/patch_manifest_check.py -vruns 9 tests, OK. So the CTest registration is now exercised; the body says it wasn't.What I traced against the runtime.
PIPELINESmatches the runtime at9e7eab5b.d3d12_draw.inlusesx2w-startup-shader-29and-29cs, andmesh86_cache.inlusesx2w-startup-mesh-86-1..txt,.vs.csoand.ps.csoand returns if either.csois missing. Compute reads.txtand.cs.cso. mesh86 reads.mesh86.txtand.ms.cso, and.ps.csoonly when the request has a pixel stage.request_slot57_mesh(x2w-startup-mesh-57-3) only publishesreq_files, and nothing reads a slot-57 translation back yet.Mutants on top of the 28 already in the thread, each run against
tests/patch_manifest_check.py::dropped from thefilecheck\dropped from thefilecheck.allowed as a name..allowed as a name[1-9][0-9]*→[0-9]+filesarray allowed.ps.csomade requiredextcheck removedload_datare-reads the input filespans.sort()→spans.sort(key=lambda s: s[2])Blocking:
fileaccepts names that aren't files in the manifest's directory on Windows._file_namesays the value is "for a later consumer to resolve in the manifest's directory". On this branch,parseaccepts these as a shader patch'sfile:NUL,CON.txtandCom1: device names. Opening<dir>\NULopens the null device, not a file in the directory.s001.txt.ands001.txt: Windows strips a trailing dot or space, so these names001.txt.a*b,a?b,a<b,a|b,a"banda<TAB>b: names Windows can't create.The runtime that would serve these files only runs on Windows. A check run once at load time is the place to refuse them, before any consumer exists. A version I tried:
With it, the fixture stays at 9 tests OK. All twelve names above are refused, and
s001.txt,s001.cs.cso,console.txt,nulls.csoanda b.txtare still accepted. Two or three of those names next to the six existing bare-name refusals would pin it.Non-blocking.
4968e124.load_data, which both serve #3037. I'm not asking for a split; a maintainer may prefer one.Verdict: changes requested on
4968e124, for thefilename rule only.Environment: Windows 11 25H2 build 26200.9974; Python 3.12.10; pefile from
requirements-dev.txt.This reply was AI-assisted.
@KelboLive on GitHub · 2026-11-28 00:05 UTC · original
I agree with pigalot's CHANGES_REQUESTED review — the
_file_namecheck needs to be tightened for Windows reserved names and invalid characters. The current check (any(c in name for c in "/\\:") or name in (".", "..")) misses:s001.txt.opens ass001.txt)< > " | ? *and control chars (< 32)pigalot's suggested fix looks correct. Please add a couple of the reserved names to the fixture refusals (e.g.,
file = "NUL",file = "CON.txt",file = "s001.txt ") to pin it.Non-blocking observations:
load_datacorrectly hashes the caller-provided bytes rather than re-reading from disk — this is the right design for race avoidance.spans.sort()→spans.sort(key=lambda s: s[2])) is from #3056 and out of scope here — just noting it for the maintainer.@JohnConnorNPC on GitHub · 2026-11-28 03:44 UTC · original
Thank you for the review, @pigalot. You're right:
fileaccepted names that don't name a file in the manifest's directory on Windows.I pushed two commits (the first is the earlier sort-key test fix). The loader now refuses, with three separate messages and the bare-name message unchanged: any of
<>"|?*or a control character (including a tab), a trailing dot or space (s001.txt.,s001.txt), and reserved device names (CON PRN AUX NUL COM0-9 LPT0-9, plusCONIN$/CONOUT$and the superscript COM/LPT forms), case-insensitive, with or without an extension.NUL,CON.txtandCom1are among the 17 refused names pinned next to the bare-name refusals. Six near-miss names still load (console.txt,nulls.cso,a b.txt,com10.txt,conin.txt,.s001.txt).Twelve new mutations each fail a test, and the 24 audit mutants are still killed. The sort-key mutant that survived is killed by the earlier commit; sorting by span end remains equivalent.
patch_manifest_checkruns 9 tests OK,docs_linksandbidipass. I ran these on Linux only, not Windows.This comment was AI-assisted.
@pigalot on GitHub · 2026-11-28 03:50 UTC · original · requested changes
I re-reviewed
0d733d9aon Windows. On its own it passes, but merged over currentmain(fdba6e15) one of its pins fails. The merge itself is clean, andgit diff --cached --checkreports no problems.My earlier request is fixed.
_file_namenow refuses the twelve names I listed, plusCONIN$,CONOUT$, andCOMorLPTfollowed by a superscript digit.console.txt,nulls.cso,com10.txt,conin.txt,a b.txtand.s001.txtare still accepted.On
0d733d9aalone,out\pe-env\Scripts\python.exe -B tests/patch_manifest_check.py -vruns 9 tests, all OK, so the first Windows run of these cases passes. I also ran nine of the mutations from your table on Windows, and each fails the check:<>"|?*check removedmatchinstead offullmatchrstrip(" ")droppedThe sort-key survivor from the earlier round is fixed too. The side-by-side ids no longer follow the addresses.
Blocking: merged with current
main,test_shader_files_match_the_runtime [compute]fails.patch_manifest_controlsfails the same way indevandrelease(ctest --test-dir out/build/<preset> --no-tests=error -R '^(patch_manifest.*|docs_links|call_evidence_check|bidi_controls)$': 3 of 4 pass). This branch's base isca659396. Since then, #3006 (7364e6a9) added this check tosrc/startup_stubs/d3d12_compute_dispatch.inl:So for a compute key, the runtime now looks for
<key>.cs.hlsltoo. It only checks that the file exists, and only when the.txtmanifest carries no native compiler revision. Without that file, a patch that ships only.txtand.cs.csowith an unmarked manifest is treated as stale. The pin is doing its job here; the loader's table is behind the runtime.A fix that matches how mesh86's
.ps.csois handled: after mergingmain, add.cs.hlslto compute's extensions as an optional file. Note in the doc that the runtime needs it only for an unmarked manifest, and pin that condition the way theload_stage(L".ps.cso", ...)line is pinned. Making it required would also satisfy the set pin, but then a patch with a natively marked manifest would have to carry a file the runtime never reads.Non-blocking: device names on current Windows. On Windows 11 build 26200, creating
nul.txt,nul .txtoraux.csoin a temporary directory makes an ordinary file of that name. Only bareNULopens the device. Older Windows versions still open these names as devices, and Microsoft's page still lists them, so refusing them is the safe rule. The doc's wording, "a name Windows would not open as a file of that name", is accurate for those versions. You might say "on some Windows versions" for the names with an extension.Verdict: changes requested on
0d733d9a, for the.cs.hlslpin failure after mergingmainonly. The file-name rule is done.Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; Python 3.12.10; pefile from
requirements-dev.txt.This reply was AI-assisted.
@JohnConnorNPC on GitHub · 2026-11-28 04:58 UTC · original
CI on
0d733d9afailed inpatch_manifest_checkbecause main's #3006 made the compute loader look for a.cs.hlslfile, which our drift test (test_shader_files_match_the_runtime [compute]) did not know about. It is not a Python-version or OS difference; the same failure reproduces locally on the PR merged into main.I pushed a fix: the compute manifest now accepts
.cs.hlslas an optional file (the required set stays.txt+.cs.cso), with a new accept case and a pin on the runtime condition under which it looks for the file (a.txtwith nonativeline). Three new mutations (.cs.hlsldropped, made required, runtime condition forced true) are each killed. On the merge with current mainpatch_manifest_checkruns 9 tests OK, anddocs_linksandbidipass.Because the fix needs #3006's lookup, I then merged current main into the branch (
d3013cf1), so the branch is green on its own; the results above are re-measured on that merge.This comment was AI-assisted.
@pigalot on GitHub · 2026-11-28 08:00 UTC · original · approved these changes
I re-reviewed
d3013cf1on Windows. The pin failure I asked about is fixed, so I'm approving.Fixed.
computenow lists.cs.hlslamong the files the runtime reads, and leaves it out of the required ones (.txt,.cs.cso). The doc table and the new paragraph say when the runtime looks for it: only for a.txtwithout anativeline.test_shader_files_match_the_runtimepins that condition (if (output == x2w::NativeComputeOutput::unmarked) {) the same way it pins mesh86's.ps.cso. The new accept case (s005, compute with.txt,.cs.csoand.cs.hlsl) loads, and the CLI lists its id.Testing. I trial-merged this head over current
main(c3204a9c); the merge is clean. On that tree,out\pe-env\Scripts\python.exe -B tests/patch_manifest_check.py -vruns 9 tests, all OK, includingtest_shader_files_match_the_runtime, which failed on0d733d9aafter mergingmain.bidi_controls_check.pypasses. CI is green ond3013cf1.Mutants (on Windows, each run through
tests/patch_manifest_check.py):.cs.hlsldropped from compute's files.cs.hlslmade requiredif (true) {.cs.dxilinstead of.cs.hlslThe first three are yours; the fourth checks that the set pin follows the extension the runtime actually reads.
The device-name note from my last review was non-blocking and still stands as a wording suggestion only.
Verdict: approve at
d3013cf1.Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; Python 3.12.10; pefile from
requirements-dev.txt.This reply was AI-assisted.