D3D12-GPU-BOOK-NEIGHBOURS-U64-MAX: prevent u64::MAX overflow and wrap in Book::neighbours #3005
No reviewers
No assignees
Labels
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
No project
No milestone
Dependencies
No dependencies set
Notifications
3 participants
Due date
No due date set.
Reference
leonida/mandy!3005
Loading…
Reference in a new issue
No description provided.
Delete branch "github-pr/3005"
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?
Pull request successfully merged and closed
Fixes
D3D12-GPU-BOOK-NEIGHBOURS-U64-MAX(claim comment 7328994859).Summary
Book::neighbours(d3d12/crates/leonida-gpu/src/book.rs): Replacedself.by_start.range((at + 1, 0)..).next()withat.checked_add(1).and_then(|next| self.by_start.range((next, 0)..).next()). Callingneighbours(u64::MAX)(for instance fromat_loss(u64::MAX)) previously panicked with integer overflow in debug builds or wrapped to(0, 0)..in release builds and returned the lowest live allocation as the upper neighbour.bases(base.saturating_add(bytes.saturating_sub(1))),walksuspect expiry (s.2.saturating_add(400)), andat_losswindow length calculations (e.start.saturating_add(e.size).saturating_sub(base)and.saturating_add(64 << 10)) with saturating arithmetic so extreme addresses/timestamps cannot panic or wrap.neighbours_handles_u64_max_without_overflow_or_wrap.Verification
Book::neighbours(u64::MAX)panicked in debug (RED_BOOK_EXIT=101, attempt to add with overflow).cargo test --package leonida-gpu --features diagnostics --lib book::tests->4 passed; 0 failed(including GPU testa_pooled_texture_and_its_block_are_in_the_bookon RX 7900 XTX).leonida-gpucompile &tools/d3d12_switches.py --checkexit0.APPROVE).AI-assisted
Verified the neighbour lookup at a708b08fd against an independently sorted list of live entries. I compiled the unchanged Book add/remove/neighbours methods from parent and head. The matrix included duplicate starts at 0 and u64::MAX, interior gaps, and removals of the most recent and older entries sharing an address.
With one live entry at zero, the parent panicked on a u64::MAX query with overflow checks enabled. With checks disabled it returned that same entry as both neighbours. The PR matched the reference on all 130 lookups in each build, including after removing entries at the maximum address. This checks the indexed lookup only. Codex-assisted.
VERIFY-3005 — 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, with one thing the maintainer should know about the test's reach. The change fixes a real overflow in
Book::neighbours(a panic in a debug build, a wrapped address in a release build) and makes three other arithmetic spots saturating. The new test fails on the merge base with exactly "attempt to add with overflow" and passes with the pull request; nothing regressed. The thing to know:book.rsis behind#[cfg(all(windows, feature = "diagnostics"))], and the repository's CI runscargo test --workspace --lockedwithout that feature, so the new test is never executed by CI as the workflow stands — it only runs when someone builds the crate with--features diagnostics(I had to use a scratch copy of the harness to do that).head
a708b08fdc5283d56da3ea04217ec280953d9dcf("d3d12/gpu: prevent u64::MAX overflow/wrap in Book::neighbours and loss spans"), baseorigin/main=0ae5a2664b9cd2fd30abfb1f6096f1c07b030f39, merge base1abef08d09f6c085efbd47de4cc9e2010bb70793(124 commits behindmain;book.rsitself has not been touched onmainsince that merge base, so the diff still applies tomain'sbook.rsunchanged). One file, +21/−6:d3d12/crates/leonida-gpu/src/book.rs.1. What it changes
book.rsis the diagnostics-only book of what the title has mapped (lib.rs:52:#[cfg(all(windows, feature = "diagnostics"))] mod book;). Four arithmetic expressions are made overflow-safe:Book::neighbours(at)(book.rs:149) — the important one. Old:let above = self.by_start.range((at + 1, 0)..).next();. Withat == u64::MAX,at + 1overflows: a panic ("attempt to add with overflow") in a debug build, and a wrapped0in a release build, which would then ask for "the entry starting at or above 0" — a completely unrelated entry. New:let above = at.checked_add(1).and_then(|next| self.by_start.range((next, 0)..).next());— atu64::MAXthere is no address above, so the answer is "no entry above".neighboursis whatat_loss(va)uses to answer "what was at this address" for a faulting address.bases()(book.rs:474) —base + bytes - 1becomesbase.saturating_add(bytes.saturating_sub(1)), for the "buffer's end" entry. Thebytes - 1underflow is unreachable in practice (decodereturnsNames::Nothingfor a zero-length buffer, book.rs:432), and thebase + bytesoverflow is conceivable only for a descriptor whose base sits at the top of memory; the change makes both harmless.walk()(book.rs:527) —now >= s.2 + 400becomesnow >= s.2.saturating_add(400).s.2is a timestamp in milliseconds, so the overflow is unreachable; the change is defensive.at_loss()(book.rs:626-634) —e.start + e.size - basebecomese.start.saturating_add(e.size).saturating_sub(base)(twice), andlen.unwrap_or(64 << 20) + (64 << 10)becomeslen.unwrap_or(64 << 20).saturating_add(64 << 10). Same values in every reachable case; no overflow.So one change fixes a reachable bug and three make unreachable arithmetic safe. All four are in the file's own style (the file already uses
saturating_*andchecked_*elsewhere).2. The new test checks the property that matters
book::tests::neighbours_handles_u64_max_without_overflow_or_wrapis exactly the property that was broken:u64::MAXthere is no address above, so "no entry above" is the correct answer — and it is the answer the release build of the old code got wrong (it wrapped to 0 and would have reported the entry at the lowest address). The first assertion also checks that the fix did not break the ordinary case: the entry at0x1000_0000is still the one belowu64::MAX.The test body really runs here; it is not a no-op. I built the red side alone (merge base + the PR's test hunks) with
--features diagnosticsand ran the new test by name under Wine (lane/red_3005.log): the binary reported1 failed; 784 filtered outwithLine 149 column 42 is the
at + 1ofself.by_start.range((at + 1, 0)..)— the overflow the pull request removes. The test needs no GPU, no device and no game files: it is aBook(a map of what the title mapped) built in memory.What the test does not cover. The other three changes (
bases,walk,at_loss) have no test; onlyneighboursis tested. That is defensible — they are unreachable arithmetic — but it means a future edit could reintroduce a non-saturating expression there without any test noticing.The test's reach is limited by the feature gate.
book.rsis compiled only with--features diagnostics, so this test exists only in that build. The repository's CI (d3d12/.github/workflows/ci.yml) runscargo test --workspace --locked(line 33) with no features, so thebookmodule — and this test — is not part of the test run CI does. The only CI job that compiles it is the clippy job with--all-features(line 30), which compiles but does not run the test. The new test therefore never fails onmainin CI, and never passes in CI either: the maintainer's checklist item "a new test that fails onmainand passes with the pull request" is satisfied in the source but is not exercised by the workflow. Moving the test out of the gated module, or adding--features diagnosticsto the test job, would close that gap.3. What the tests do here
The crate has to be built twice for this pull request to mean anything, because the whole change lives behind a feature gate. I cross-compiled for
x86_64-pc-windows-gnuand ran the test binaries under Wine in both builds.With
--features diagnostics(the build in which the change exists) —python3 tools/wine_red_green.py 3005 --crate leonida-gpuwith a scratch copy of the harness that accepts--features(/tmp/opencode/wine_rg_feat.py; the same red-side rule as the repository'sscripts/red_green.py):1abef08d+ the PR's test hunksbook.rs:149:42a708b08f(PR head)The tool's verdict: "red then green" — 1 red→green (the new test), 0 regressions, 4 failing on both sides, 722 passing on both sides, no test on one side only.
With the default feature set (what CI runs) the
bookmodule is not compiled at all, so there is no book test on either side: the plain run is 703 tests per side with nobook::test among them. I checked the two sides of that build by hand as well, running the base's and the head's test binary under Wine single-threaded:1abef08d(plain)watchtests)a708b08f(plain)watchtests)Identical. That is what one expects: the pull request's whole diff is inside
#[cfg(all(windows, feature = "diagnostics"))] mod book;, so in the default build the change is not compiled at all and cannot alter anything.4. Any failure I saw and why it is not this PR
diagnosticsbuild:timeline::report::tests::real_waits_are_recorded_with_who_ended_them,watch::many_askers_tests::holes_are_known_until_the_runtime_tells,watch::many_askers_tests::no_mapping_is_lost_between_askers,watch::tests::what_is_left_alone_is_no_known_hole. None of them is inbook.rs, which is the only file this pull request touches; the threewatchones fail identically on the base of the other three pull requests I verified (same merge base family) and are environment failures of the guard-page machinery under Wine without a real GPU.timeline::report::tests::real_waits_are_recorded_with_who_ended_themis a timing-sensitive test that also fails on the base (it is one of the four "fail on both sides" of the run).tools/wine_red_green.py 3005 --crate leonida-gpusat in a spinningleonida_gpu-*.exefor 30 minutes and had to be killed (the tool's own timeout is one hour). I identified what it was: the binary was the red side — the base's code — and I copied it out and ran it under Wine on its own, where it finished in 14.8 s (parallel) and 38.8 s (single-threaded) with the same 3 failures as every other run. So the hang is a pre-existing flake of the base's test suite under Wine, in code this pull request does not touch and, in that build, does not even compile into. An earlier run of the same command reported the verdict "NOT red-then-green" with threewatchregressions, which the repeat runs show to be the usualwatchflakiness (those same tests fail at the same rates on the base).main. The reviewer checklist asks formainto be merged into the branch before merging, and that is the maintainer's step, not the author's. I checked thatmainhas not changedbook.rssince that merge base (0 commits touch it), so the diff still applies tomain'sbook.rsas it stands; I did not mergemaininto the branch and did not test the merged result.5. What I did not check
cargo test --workspace --locked) is read fromd3d12/.github/workflows/ci.yml; I did not run the workflow itself, and I did not check whether some other job in the repository runs the crate's tests with the feature enabled.bases,walk,at_loss) are unexercised by any test, here or in the pull request; I checked them by reading and by reasoning about where their operands come from (decode, a millisecond timestamp, mapping sizes), not by measurement.book.rsexists to explain a faulting address in a running title ("what was at this address"). I could not check that the diagnostics answer is right for a real fault at the top of the address space, only that the arithmetic no longer overflows.cargo test --target x86_64-pc-windows-gnuunder Wine 11.21 on Fedora 45, in both the default and thediagnosticsfeature set. The release-build half of the "no wrap" claim (the old code wrapping to 0 instead of panicking) is reasoning from the code — I only ran the debug build.at_losstext output: the change alters only the arithmetic inside the string the diagnostics print; I did not compare the printed text before and after for any address.leonida-gpuwas, because the change is confined to it.Depends on:line) was not read: I was asked not to touch GitHub.Code review only, not built (Windows-only
leonida-gpu). Ready.a708b08fd, merge base1abef08d0, 326 behind currentmain45dc41f95. A trial merge is clean. CI on the head: all 6 checks pass.neighbours.Review of
d3d12/crates/leonida-gpu/src/book.rs:neighbours:at.checked_add(1).and_then(..)is the root-cause fix. Atu64::MAXthere is no "above". The oldat + 1panicked in debug and wrapped to 0 in release, which returned the lowest entry as "above".bases(Names::Buffer):base.saturating_add(bytes.saturating_sub(1))also coversbytes == 0, which underflowed before.walk(s.2.saturating_add(400)) andat_loss(saturating_addandsaturating_subon extents) are defensive. They only run on the device-loss and diagnostics path, so the cost does not matter.neighbours_handles_u64_max_without_overflow_or_wrappins the real bug. The other saturating spots have no test, which is acceptable for diagnostics arithmetic.Verdict: ready.
AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.
Generated by Claude Code
This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists).
Could you, or anyone with a working setup, post a run report on the current head merged onto current
main:mainSHA it was merged onto;mainalone for comparison, if you can.Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough.
AI-assisted (Claude Code).
VERIFY-3005 — Windows nativo:
red then green, y el módulo solo existe con la featurediagnostics(this PR)1abef08d0(well behindmainb41763227)main—merge-treeclean,git merge --no-ffcleanRan
The trap that costs ten minutes and is worth writing down:
mod bookis#[cfg(all(windows, feature = "diagnostics"))](lib.rs:52). Without--features diagnosticsthe module — and this pull request's test — is not compiled at all, andcargo test -p leonida-gpu --lib u64_maxreports0 passed; 762 filtered outwith exit 0. A verifier who runs the obvious command would record "no test" for a test that exists.Negative control (synthetic — the test ships with the change, in the same file): I put the old
self.by_start.range((at + 1, 0)..).next()back and rebuilt:The test bites on exactly the arithmetic this PR replaces with
checked_add/saturating_add.What the change is, from the diff: five expressions that could wrap at
u64::MAX— a buffer's end (base + bytes - 1), a suspect's due frame, twoend - basedistances, and a size cap — now go throughchecked_add/saturating_add. The new test drivesneighbours(..)atu64::MAX. The other three tests in the module still pass.What I could not test
u64::MAX: the fixture asks the book about it synthetically; no game run, and no such address exists in a real process.diagnostics: only the module was run (840 filtered out), not the whole suite under that feature.Written with an AI assistant.
RUN (in game, RTX 3090 24 GB) — stock compatibility PASS, with two earlier present-gap failures retained.
a708b08fdc5283d56da3ea04217ec280953d9dcfmerged locally onto main6e979905054be3ba9737883fe8e205501a2183b7as9f07ff0f6e1585a0007a80c544db11b4e629092e. Executable SHA-25694caed878bc47034257cf09a76a4d7585aab73dc9163fcc162ec787403f4f0e9, diagnostics,dlss,mimalloc. Clean-room scan passed.LEONIDA_BOOK=1in all runs. Stock gate.The initial two runs accidentally copied the large pipeline seed into the cache root rather than its expected pipelines subdirectory, so they were effectively cold. The third run corrected the seed layout. It measured 3,119 present intervals from world+60 s, p5 FPS 5.98, p95/p99 167.36/350.15 ms, VRAM peak 5,058 MiB against 23,558 MiB budget. All three completed a target stop and actual clean exit; no loss marker.
Book activity was confirmed in the first two runs by 143/131 slot-check rounds, with alive/gone counts advancing 21/1→11135/2496 and 19/1→11902/2941. The third run had Book enabled but no slot-check telemetry. Initial native placement succeeded in the first two legs and was later lost; control and placement were not established in the third. This is renderer compatibility evidence with those limitations; workload, cache and instrumentation differ, and no matched main live control was run.
Synthetic red/green: all four diagnostics book tests passed before and after restoration. Replacing only the checked neighbour increment with the old increment made the exact maximum-address test panic with integer overflow (exit 101); fixed source restored byte-for-byte then four passed. The conditional pooled-texture ownership assertion had no reported address on this NVIDIA adapter, so that assertion was not exercised. No real hardware fault was induced.
AI-assisted: Codex GPT-6.2 Sol (tester and independent numerical verification). No game content attached.
Bundle gate run on an RTX 3090 (NVIDIA 621.40, Windows 11 Pro build 26300): #3303
2892951f4, #3136fd16493ac, #30103ca5765acand #3005b3a1a8f57(the current heads) merged together intomain04a838fc4without conflict, diag profile withdiagnostics,dlss,mimalloc, msvc target. These four were judged to have no effect on the picture, so they share one run. Reference:main04a838fc4built the same way, run the same day with the same frame-timing capture on. Series X output 2560x1440, DLSS quality, no frame generation, 300 s standing at the save, fresh data.main(-0.6, inside the run-to-run spread of this recipe); median frame 29.27 ms, p99 48.8 against 48.9 ms. From 210 to 300 s the 30 s slices are the same as the reference (34.4-35.0 against 34.5-34.7). The 150-210 s slices are lower: a slower climb, plus a short CPU burst from a monitoring query on this PC at 173 s.mainrun; none after 150 s.Verdict: PASS, no cost, for the four PRs together.
GPUs tested: NVIDIA GeForce RTX 3090, driver 621.40.
AI-assisted: run and report by Claude Code (Claude Opus 5.5).
27118932einto #3005 (tree tested by local CI) 0a7eda0d3bMerged by OreoFR (agent) at MoonEyes' request. His judge accepted it, and it is part of enlighted's G1 pack, which passed a 300 s run on an RTX 3090: no cost, 0 lost, 0 crash, 0 ERROR.
Local CI (normal mode) on head
b3a1a8f57merged into main27118932e: PASS.make_game.py --help.leonida,leonida-gpuandleonida-hle, 162 s.-D warnings, 49 s.The forge refused the merge while the head was behind main.
main(27118932e) was then merged into the head as0a7eda0d3, which has the same tree the CI tested. Merged asa9361504a.This completes G1 (#3303, #3136, #3010, #3005).