tests: a released page is read back without racing the tests beside it #3017

Closed
fiestorra wants to merge 0 commits from upstream-pr/3017 into main
fiestorra commented 2026-12-01 23:45:35 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-01T23:45:35Z.


tests: a released page is read back without racing the tests beside it

memory_at_names_what_an_access_hit releases a four-page reservation and then reads one of
the pages back to see nothing mapped there. Another test in the same binary mapping in the
microseconds between the VirtualFree and the read takes that address, and the read says
read-write instead - which is exactly what CI did on two unrelated pull requests:

---- crash::tests::memory_at_names_what_an_access_hit
assertion `left == right` failed
  left: "read-write"
 right: "nothing mapped there"

The read is now over a fresh reservation released immediately before it, retried: the first
attempt whose address nobody took is the answer, and 64 taken in a row is a real failure
rather than a busy neighbour. Each attempt is a VirtualAlloc and a VirtualFree of 4 KiB.

Why not a lock: the window is between the release and the read, and the neighbour is any of
six files in this crate that map pages in their tests (console_insn, descriptor_sites,
game_actions, thunks, tls, write_sites), so a lock held by this module alone would not
remove it; a crate-wide one would touch all seven. The retry costs nothing and holds whatever
the neighbour does.

What I could not do: reproduce the failure on demand. cargo test -p leonida-loader --lib crash::tests passed 19/19 six times in a row here, so the negative control is the CI log
above and not a local red. With the change: 19/19 four more times, clippy 0.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5596768503 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3017). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-01T23:45:35Z. --- tests: a released page is read back without racing the tests beside it `memory_at_names_what_an_access_hit` releases a four-page reservation and then reads one of the pages back to see `nothing mapped there`. Another test in the same binary mapping in the microseconds between the `VirtualFree` and the read takes that address, and the read says `read-write` instead - which is exactly what CI did on two unrelated pull requests: ---- crash::tests::memory_at_names_what_an_access_hit assertion `left == right` failed left: "read-write" right: "nothing mapped there" The read is now over a fresh reservation released immediately before it, retried: the first attempt whose address nobody took is the answer, and 64 taken in a row is a real failure rather than a busy neighbour. Each attempt is a `VirtualAlloc` and a `VirtualFree` of 4 KiB. Why not a lock: the window is between the release and the read, and the neighbour is any of six files in this crate that map pages in their tests (`console_insn`, `descriptor_sites`, `game_actions`, `thunks`, `tls`, `write_sites`), so a lock held by this module alone would not remove it; a crate-wide one would touch all seven. The retry costs nothing and holds whatever the neighbour does. What I could not do: reproduce the failure on demand. `cargo test -p leonida-loader --lib crash::tests` passed 19/19 six times in a row here, so the negative control is the CI log above and not a local red. With the change: 19/19 four more times, clippy 0. Written with an AI assistant.
andrew-ai commented 2026-12-01 23:48:11 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by andrew-ai on 2026-12-01T23:48:11Z.


Ran the Windows leonida-loader library suite 25 times at parent 913b88b90 and 25 times at PR head a607df12e. I rebuilt at each revision with cargo test --locked -p leonida-loader --lib --no-run, then launched the resulting test executable in a fresh process each time with --test-threads 16.

All 85 tests passed in each of the 50 runs (2,125 test executions per revision). I could not reproduce the original intermittent failure on this machine, so this confirms repeated parallel passes on the PR but does not establish a reduction in flake rate.

Codex-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7329790404 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3017#issuecomment-7329790404). Originally posted by [andrew-ai](https://github.com/andrew-ai) on 2026-12-01T23:48:11Z. --- Ran the Windows leonida-loader library suite 25 times at parent 913b88b90 and 25 times at PR head a607df12e. I rebuilt at each revision with cargo test --locked -p leonida-loader --lib --no-run, then launched the resulting test executable in a fresh process each time with --test-threads 16. All 85 tests passed in each of the 50 runs (2,125 test executions per revision). I could not reproduce the original intermittent failure on this machine, so this confirms repeated parallel passes on the PR but does not establish a reduction in flake rate. Codex-assisted.
imShangLi commented 2026-12-02 07:09:38 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-02T07:09:38Z.


VERIFY-3017 — Linux, Fedora 45, Rust 1.98.1, cross-compiled for x86_64-pc-windows-gnu, Wine 11.21, no GPU device, no game files

Verdict: PASS. The old line reads an address back after handing it to the free pool, and anything else can already be in it; the pull request keeps the property the line was checking (a released page reads back free) and stops failing on a neighbour taking it. I reproduced the race it is defending against.

Head a607df12, base the current main (0ae5a266), merge base 913b88b9, 1 file, +17/−1: d3d12/crates/leonida-loader/src/crash.rs.

1. What it changes

One test, crash::tests::memory_at_names_what_an_access_hit, which reserves four pages, commits three with different protections, asks [memory_at] to name each, releases them all, and then asks what the released range is. The base asserts that directly, which is the flaky part:

unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) };
-        assert_eq!(memory_at(base + 8), "nothing mapped there");

The release hands those pages back to the process, and a test running beside this one can take them between the VirtualFree and the read. The replacement makes a fresh reservation instead and treats a taken range as "try again":

+        let gone = (0..64).any(|_| {
+            // SAFETY: reserves, commits and releases four pages of ours; nothing reads them.
+            let fresh = unsafe {
+                let fresh = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS);
+                assert!(!fresh.is_null());
+                assert!(!VirtualAlloc(fresh, 0x1000, MEM_COMMIT, PAGE_READWRITE).is_null());
+                VirtualFree(fresh, 0, MEM_RELEASE);
+                fresh as usize
+            };
+            memory_at(fresh + 8) == "nothing mapped there"
+        });
+        assert!(gone, "a released page was still read back as mapped 64 times in a row");

and it keeps the base's remaining lines, memory_at(0), memory_at(usize::MAX) and the check that the test's own code is a read-execute image page named by its module. Everything is inside mod tests, so no production code moves.

2. The new test checks the property that matters

This is test-only, so the red side (merge base plus the test hunks) compiles and passes the same way the green side does, and the harness cannot show red-then-green. Two things were worth checking instead.

First, that the race is real. I wrote a small standalone program (cross-compiled with the same toolchain and run under Wine) where one thread reserves the same range as PAGE_READWRITE, commits it, spins, and releases it, while the main thread reserves, commits, MEM_RELEASEs and reads the range back 200 000 times:

rounds released range read back as what memory_at would say
200 000 MEM_FREE nothing mapped there — 52 156, 54 991, 58 621 over three runs
200 000 mapped in the meantime MEM_COMMIT/PAGE_READWRITE — 6 399, 5 882, 6 590
200 000 taken outright (my own VirtualAlloc failed) 141 445, 139 127, 134 789

So the base line is not deterministic: in about one round out of thirty the range already holds somebody else's PAGE_READWRITE, and the assertion fails for a reason nothing to do with the code. That is the bug, and it explains a read-write from CI.

Second, that the replacement is not vacuous. I mutated the loop body so no attempt can ever match (memory_at(fresh + 8) == "a string that is never returned"), rebuilt, and the test failed with the new message:

panicked at crates/leonida-loader/src/crash.rs:931:9:
a released page was still read back as mapped 64 times in a row

Restoring the line, it passes again. So the assertion still has teeth, and it still says something the base said — a released page really does read back free — rather than giving that up.

Compared with the sibling pull request #2939, which fixes the same test by querying addresses Windows never maps, this one is the more conservative fix: it retains the property under test. The cost is the any over 64 attempts, and the assert!(!fresh.is_null()) inside it, which would panic rather than retry if a neighbour held the address space in that round. Sixty-four 16 KiB allocations is nothing to exhaust, and the retry loop was intended to absorb exactly that, but it is a panic path rather than a skipped one.

3. What the tests do here

count
red side (merge base + this pull request's test hunks) 88
green side (the pull request's head) 88
pass on both 87
red → green 0 (expected: the change touches no production code)
regressions (pass on red, fail on green) 0
fail on both 1 — loads_binds_and_calls_probe
ignored 0
only on red / only on green 0 / 0

Run by hand on the head, the crate's unit suite is 84 passed / 0 failed three times in a row, and memory_at_names_what_an_access_hit on its own is 30/30. The red side has one test fewer than the green side because the merge base here is newer than the one #2939 branched from, not because this pull request removed anything.

4. Any failure I saw, and why it is not this pull request

loads_binds_and_calls_probe fails on the red side and on the green side alike, so it is not caused here. It is an integration test (d3d12/crates/leonida-loader/tests/load_probe.rs) and it dies building its own fixture:

panicked at crates/leonida-loader/tests/load_probe.rs:35:10: running cargo: Os { code: 6, kind: Uncategorized, ... }
error: manifest path `/home/shangli/.../d3d12/tests/fixtures/hle-probe/Cargo.toml` does not exist

The test shells out to cargo to compile a probe, and there is no cargo on the Wine side of this machine, and the manifest path is written with backslashes that only Windows accepts. It needs a native Windows box. Nothing else failed on either side.

5. What I did not check

  • A GPU, a D3D12 adapter, or the running title. Everything is unit tests under Wine. The crash module needs no device, which is why these pass here at all.
  • Real Windows, not Wine 11.21. The CI failure the comment refers to happened on a different machine, and I have not reproduced it there, nor can I see their log. I reproduced the race on this one.
  • The real contention rate. My racer polls one address as hard as it can, which overstates it: the actual neighbour is whatever test calls VirtualAlloc next, so ~3 % is a ceiling and not a measurement. I did not measure how often the 64 attempts would all be beaten, and the panic path on a null VirtualAlloc was exercised by reasoning only, not by forcing an exhaustion.
  • The PAGE_NOACCESS reservation versus the base's mixed protections. The fresh block reserves four pages as PAGE_NOACCESS and commits one as PAGE_READWRITE; the base committed read-only, guard and no-access pages. Both end MEM_FREE after the release, and that is the point, but the fresh loop does not re-exercise the three protections — the lines above it do, so nothing is lost.

The program was scratch work under /tmp/opencode, cross-compiled with the same toolchain, and is not part of this pull request: nothing was committed and nothing was pushed.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7337847391 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3017#issuecomment-7337847391). Originally posted by [imShangLi](https://github.com/imShangLi) on 2026-12-02T07:09:38Z. --- ## VERIFY-3017 — Linux, Fedora 45, Rust 1.98.1, cross-compiled for x86_64-pc-windows-gnu, Wine 11.21, no GPU device, no game files **Verdict: PASS.** The old line reads an address back after handing it to the free pool, and anything else can already be in it; the pull request keeps the property the line was checking (a released page reads back free) and stops failing on a neighbour taking it. I reproduced the race it is defending against. Head `a607df12`, base the current `main` (`0ae5a266`), merge base `913b88b9`, 1 file, +17/−1: `d3d12/crates/leonida-loader/src/crash.rs`. ### 1. What it changes One test, `crash::tests::memory_at_names_what_an_access_hit`, which reserves four pages, commits three with different protections, asks [`memory_at`] to name each, releases them all, and then asks what the released range is. The base asserts that directly, which is the flaky part: ```rust unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; - assert_eq!(memory_at(base + 8), "nothing mapped there"); ``` The release hands those pages back to the process, and a test running beside this one can take them between the `VirtualFree` and the read. The replacement makes a fresh reservation instead and treats a taken range as "try again": ```rust + let gone = (0..64).any(|_| { + // SAFETY: reserves, commits and releases four pages of ours; nothing reads them. + let fresh = unsafe { + let fresh = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!fresh.is_null()); + assert!(!VirtualAlloc(fresh, 0x1000, MEM_COMMIT, PAGE_READWRITE).is_null()); + VirtualFree(fresh, 0, MEM_RELEASE); + fresh as usize + }; + memory_at(fresh + 8) == "nothing mapped there" + }); + assert!(gone, "a released page was still read back as mapped 64 times in a row"); ``` and it keeps the base's remaining lines, `memory_at(0)`, `memory_at(usize::MAX)` and the check that the test's own code is a read-execute image page named by its module. Everything is inside `mod tests`, so no production code moves. ### 2. The new test checks the property that matters This is test-only, so the red side (merge base plus the test hunks) compiles and passes the same way the green side does, and the harness cannot show red-then-green. Two things were worth checking instead. First, that the race is real. I wrote a small standalone program (cross-compiled with the same toolchain and run under Wine) where one thread reserves the same range as `PAGE_READWRITE`, commits it, spins, and releases it, while the main thread reserves, commits, `MEM_RELEASE`s and reads the range back 200 000 times: | rounds | released range read back as | what `memory_at` would say | |---|---|---| | 200 000 | `MEM_FREE` | `nothing mapped there` — 52 156, 54 991, 58 621 over three runs | | 200 000 | mapped in the meantime | `MEM_COMMIT/PAGE_READWRITE` — **6 399, 5 882, 6 590** | | 200 000 | taken outright (my own `VirtualAlloc` failed) | 141 445, 139 127, 134 789 | So the base line is not deterministic: in about one round out of thirty the range already holds somebody else's `PAGE_READWRITE`, and the assertion fails for a reason nothing to do with the code. That is the bug, and it explains a `read-write` from CI. Second, that the replacement is not vacuous. I mutated the loop body so no attempt can ever match (`memory_at(fresh + 8) == "a string that is never returned"`), rebuilt, and the test failed with the new message: ``` panicked at crates/leonida-loader/src/crash.rs:931:9: a released page was still read back as mapped 64 times in a row ``` Restoring the line, it passes again. So the assertion still has teeth, and it still says something the base said — a released page really does read back free — rather than giving that up. Compared with the sibling pull request #2939, which fixes the same test by querying addresses Windows never maps, this one is the more conservative fix: it retains the property under test. The cost is the `any` over 64 attempts, and the `assert!(!fresh.is_null())` inside it, which would panic rather than retry if a neighbour held the address space in that round. Sixty-four 16 KiB allocations is nothing to exhaust, and the retry loop was intended to absorb exactly that, but it is a panic path rather than a skipped one. ### 3. What the tests do here | | count | |---|---| | red side (merge base + this pull request's test hunks) | 88 | | green side (the pull request's head) | 88 | | pass on both | 87 | | red → green | 0 (expected: the change touches no production code) | | regressions (pass on red, fail on green) | 0 | | fail on both | 1 — `loads_binds_and_calls_probe` | | ignored | 0 | | only on red / only on green | 0 / 0 | Run by hand on the head, the crate's unit suite is 84 passed / 0 failed three times in a row, and `memory_at_names_what_an_access_hit` on its own is 30/30. The red side has one test fewer than the green side because the merge base here is newer than the one #2939 branched from, not because this pull request removed anything. ### 4. Any failure I saw, and why it is not this pull request `loads_binds_and_calls_probe` fails on the red side and on the green side alike, so it is not caused here. It is an integration test (`d3d12/crates/leonida-loader/tests/load_probe.rs`) and it dies building its own fixture: ``` panicked at crates/leonida-loader/tests/load_probe.rs:35:10: running cargo: Os { code: 6, kind: Uncategorized, ... } error: manifest path `/home/shangli/.../d3d12/tests/fixtures/hle-probe/Cargo.toml` does not exist ``` The test shells out to `cargo` to compile a probe, and there is no `cargo` on the Wine side of this machine, and the manifest path is written with backslashes that only Windows accepts. It needs a native Windows box. Nothing else failed on either side. ### 5. What I did not check - **A GPU, a D3D12 adapter, or the running title.** Everything is unit tests under Wine. The crash module needs no device, which is why these pass here at all. - **Real Windows, not Wine 11.21.** The CI failure the comment refers to happened on a different machine, and I have not reproduced it there, nor can I see their log. I reproduced the race on this one. - **The real contention rate.** My racer polls one address as hard as it can, which overstates it: the actual neighbour is whatever test calls `VirtualAlloc` next, so ~3 % is a ceiling and not a measurement. I did not measure how often the 64 attempts would all be beaten, and the panic path on a null `VirtualAlloc` was exercised by reasoning only, not by forcing an exhaustion. - **The `PAGE_NOACCESS` reservation versus the base's mixed protections.** The fresh block reserves four pages as `PAGE_NOACCESS` and commits one as `PAGE_READWRITE`; the base committed read-only, guard and no-access pages. Both end `MEM_FREE` after the release, and that is the point, but the fresh loop does not re-exercise the three protections — the lines above it do, so nothing is lost. The program was scratch work under `/tmp/opencode`, cross-compiled with the same toolchain, and is not part of this pull request: nothing was committed and nothing was pushed.
fiestorra commented 2026-12-02 14:24:36 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-02T14:24:36Z.


Closing: main fixed this in 561bbc19c ("leonida-loader: remove post-MEM_RELEASE VA-reuse race in memory_at test"), and its fix is the better one.

Theirs: after the release, the test no longer reads the address it just gave back. It reads 0x1008, inside the low 64 KiB that Windows keeps permanently unmapped:

// Do not query `base` after `MEM_RELEASE`: concurrent test threads can
// immediately reuse the released VA as PAGE_READWRITE. Windows keeps
// the low 64 KiB (0..0x10000) permanently unmapped (MEM_FREE).
...
assert_eq!(memory_at(0x1008), "nothing mapped there");

Mine retried a fresh reservation 64 times. Deterministic beats retried, and it needs no VirtualAlloc in the test at all.

And the branch is not what it was: while trying to rebase this onto main I created it from main by mistake and force-pushed that over the commit (a607df12e), which is why the diff looked empty before this. The commit is recoverable and I did recover it (git cat-file -t a607df12e -> commit), but there is nothing to restore it to: the flake is gone from main and this PR would be a second fix for it. My mistake, said plainly - the check that would have caught it is git rev-parse HEAD before the push, which I ran one command too late.

AI-assisted: yes - DeepSeek v4.1 (flash).

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7348495870 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3017#issuecomment-7348495870). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-02T14:24:36Z. --- **Closing: `main` fixed this in `561bbc19c` ("leonida-loader: remove post-MEM_RELEASE VA-reuse race in memory_at test"), and its fix is the better one.** **Theirs**: after the release, the test no longer reads the address it just gave back. It reads `0x1008`, inside the low 64 KiB that Windows keeps permanently unmapped: ```rust // Do not query `base` after `MEM_RELEASE`: concurrent test threads can // immediately reuse the released VA as PAGE_READWRITE. Windows keeps // the low 64 KiB (0..0x10000) permanently unmapped (MEM_FREE). ... assert_eq!(memory_at(0x1008), "nothing mapped there"); ``` **Mine** retried a fresh reservation 64 times. **Deterministic beats retried**, and it needs no `VirtualAlloc` in the test at all. **And the branch is not what it was**: while trying to rebase this onto `main` I created it from `main` by mistake and force-pushed that over the commit (`a607df12e`), which is why the diff looked empty before this. **The commit is recoverable and I did recover it** (`git cat-file -t a607df12e` -> commit), but there is nothing to restore it to: **the flake is gone from `main` and this PR would be a second fix for it.** **My mistake, said plainly** - the check that would have caught it is `git rev-parse HEAD` before the push, which I ran one command too late. **AI-assisted:** yes - DeepSeek v4.1 (flash). Written with an AI assistant.

Pull request closed

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
ProjectLeonida/mandy!3017
No description provided.