Skip to content

loader: content-address PreparedImage with cached hash and synced staging (D3D12-LOADER-CONTENT-ADDRESSED-IMAGE) - #2890

Open
djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/loader-content-addressed-image
Open

djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/loader-content-addressed-image

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-LOADER-CONTENT-ADDRESSED-IMAGE.

What and why

Content-address PreparedImage::file_name() by a cached full BLAKE3 hash of the prepared bytes, sync staging files to disk before the atomic rename, and add a content-addressed fast path in publish::write_content_addressed() (d3d12/crates/leonida-loader/src/{prepare.rs,publish.rs,windows.rs}).

  • Why:
    1. On main, PreparedImage::file_name() keys the cached DLL on the first 16 hex chars of original_hash (leonida-image-<16hex>.dll). If loader preparation bytes change for the same title build, the cached filename collides with the stale DLL.
    2. On every launch, publish::write_if_changed() reads the entire ~115–200 MB prepared DLL back from disk into a Vec<u8> just to byte-compare it against prepared.bytes.
  • Change:
    • prepare.rs: computes and caches pub prepared_hash: blake3::Hash once inside prepare(). PreparedImage::file_name(&self) delegates to crate::publish::content_addressed_name(&self.prepared_hash) (leonida-image-<64hex>.dll), so neither windows.rs::load nor apps/leonida/src/run.rs re-hashes prepared.bytes.
    • publish.rs:
      • Writes staging files via write_staging() (File::create → write_all → sync_all, cleaning up the staging file on error) BEFORE publish_staging() performs the atomic rename, preventing crash/power-loss from leaving a same-size zero-filled file at the content-addressed path.
      • Adds write_content_addressed(path, bytes, hash) which skips re-reading disk when the filename matches content_addressed_name(hash) and metadata(path) confirms a regular file of the exact byte length, falling back to write_if_changed() otherwise.
    • windows.rs: passes &prepared.prepared_hash into crate::publish::write_content_addressed, ensuring prepared.bytes is hashed exactly once per launch.
  • Notes: Existing LEONIDA_WRITE_SITES caches keyed by the old 16-hex image_name will regenerate once under the new 64-hex name; prior leonida-image-*.dll cache entries from earlier builds remain untouched in the cache directory.
  • Scope discipline: Strictly one topic; per-page IAT VirtualProtect batching is split into its own separate PR (D3D12-LOADER-BATCHED-IAT-PROTECT, verified clean merge via git merge-tree).
  • Evidence classification: READ IN CODE (prepare.rs, publish.rs, windows.rs) + fresh red→green unit tests + MEASURED 300 s in-world game gate.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-loader/src/prepare.rs d3d12/crates/leonida-loader/src/publish.rs d3d12/crates/leonida-loader/src/windows.rs → exit 0.
  • Freshly compiled (cargo clean -p leonida-loader --target x86_64-pc-windows-msvc) leonida-loader unit test binary (x86_64-pc-windows-msvc) and ran under Wine:
    • RED on origin/main (only the new test prepare::tests::file_name_uses_full_blake3_of_prepared_bytes applied):
      running 1 test
      thread 'prepare::tests::file_name_uses_full_blake3_of_prepared_bytes' panicked:
      assertion `left == right` failed
        left: "leonida-image-46f298c60d91a73a.dll"
       right: "leonida-image-52c5ecc3199b3152e1e0d4817abdafa261e5ed83a82b8936fb2d5dc35e28c214.dll"
      test result: FAILED. 0 passed; 1 failed; 0 ignored
      
    • GREEN on PR head 262439781 (rebased onto 3e7b34a52):
      test prepare::tests::file_name_uses_full_blake3_of_prepared_bytes ... ok
      test publish::tests::content_addressed_fast_path_requires_matching_name_and_size ... ok
      test result: ok. 86 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
      
  • git merge-tree --write-tree HEAD pr/loader-batched-iat-protect → clean merge (zero conflicts with D3D12-LOADER-BATCHED-IAT-PROTECT).
  • 300 s in-world game gate (MEASURED on exact PR head 262439781, Series S + DLSS Quality 1280×720 → 1920×1080, Option A mods/gate_driver mode = roam loaded):
    • Verdict: PASS (310.03 s in-world after world entry at 68.77 s; also passed an earlier cold-cache 310.18 s run with 0 errors).
    • Frames & pacing: 3,275 frames after +60 s (3,382 total world presents), 15.98 median FPS (16.37 end median FPS), 111.22 ms p95 frame time, 4.433 s longest present gap (<= 10.0 s).
    • Memory & stability: 6,686 MiB peak VRAM (<= 7,400 MiB), 0 device losses (0x887A0005), 0 crashes, 0 panics, 0 faults before stop, 0 kernel NVRM: Xid errors.
    • Option A gate_driver note: mods/gate_driver loaded in mode = roam with 0 GATE FAIL; its 10 s menu-press cadence missed the brief world-entry probe window so the 310.03 s run stayed on the in-world camera cleanly at 15.98 FPS.

GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).

AI-assisted: yes (authored by Gemini 4 Neon; independent fresh review pass by a separate Gemini 4 Neon agent requested File::sync_all() before rename and caching prepared_hash once on PreparedImage to eliminate triple hashing, addressed and approved in re-review).

Checklist

  • Based on current main (3e7b34a52) 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 (check_no_game_data.py clean on both source and PR description).
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — loader image cache naming & synced content-addressed publish fast path)

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent prepared-image publication and retry check at 2624397 + 0ff8a53, using the Win64 test binary under Wine 11.22. The 7 prepare tests including my integration case and all 5 publish tests passed.

I used the linked test executable as input. Two originals with different checksum bytes converge to identical prepared bytes and the same content-addressed name. Two distinct prepared payloads of exactly the same length instead publish to separate names. Four concurrent writers, two per name, left both payloads byte-for-byte correct and no staging files.

I then truncated one published file and held it open without delete sharing. Publishing returned PermissionDenied and left no staging file. Closing the reader and retrying repaired the truncated file while the other cache entry stayed byte-identical. This exercises the recovery path for a size mismatch with live Windows sharing semantics under Wine. Same-length corruption and power-loss durability were outside the fixture.

MEASURED with synthetic inputs. AI-assisted (Codex).

@KelboLive KelboLive left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Content-addressing checks out: the key is blake3(prepared bytes) (prepare.rs:112-118, publish.rs:16-18), so it covers the original image plus any change in prepare(), and the LEONIDA_* options only patch mapped memory after LoadLibraryExW (windows.rs:90-110) — correctly not part of the file key. The old 16-hex collision is gone, and I confirmed the mutation that shrinks the key to 16 hex fails file_name_uses_full_blake3_of_prepared_bytes. 86/86 lib tests here, and the three-way merge with #2889/#2891 compiles and passes 89/89.

Two things to tighten:

  1. The fast path trusts (name, size) alone (publish.rs:30-34), so a same-length corruption — bit rot, AV rewrite, interrupted copy, a hand-placed file — is served forever and never healed, unlike the previous byte-compare. Your own test encodes that deliberately (publish.rs:93-98). That is a reasonable trade for the scale win, but it should be stated in the doc comment, or a small hash.ok sidecar written after the rename would restore self-repair.
  2. The safety argument rests on sync_all before rename (publish.rs:59), and deleting that line leaves all 86 tests green. A test hook that asserts the flush happens would pin the one invariant the whole design leans on.

Nit: a crash mid-write leaves .<64hex>.dll.<pid>.<n>.tmp (up to ~200 MB) unreaped — no startup sweep, no age-based reaping. Pre-existing pattern, but this is the cache-hygiene PR, so a stale .*.tmp sweep would close the staging lifecycle.

Merge is clean against current main (the three touched files are byte-identical upstream), and clean paired with #2889 and #2891. CI's red check/linux-python-and-viewer are untouched Python tool tests, not this diff.

@Kal0s-design

Copy link
Copy Markdown
Contributor

Verified on native Windows 11 (MSVC target, rustc 1.98.1, NTFS), since the runs in the description are under Wine.

Head 262439781 merged with main d2a564b66 (clean merge):

  • cargo test -p leonida-loader --lib: 86 passed, 0 failed, including the three rename_denied_* / staging tests that matter most on Windows.
  • cargo clippy -p leonida-loader --all-targets: no warnings in the loader.

Both new tests catch their change:

  • with the old original_hash[..16] name put back, file_name_uses_full_blake3_of_prepared_bytes fails (left: "leonida-image-4976ea11133df67f.dll");
  • with the m.len() == bytes.len() check removed from the fast path, content_addressed_fast_path_requires_matching_name_and_size fails at publish.rs:103 (the short file is kept).

What the fast path saves here. I timed the two paths on a 114.7 MB file (the size run.rs mentions), release build, file already in the OS cache, three runs:

time
main's write_if_changed (read back + compare) 31-38 ms
write_content_addressed (metadata only) 0.14-0.20 ms
first publish (write + sync_all + rename) 68 ms
the new blake3::hash of the prepared bytes, once per launch 15 ms

So with a warm cache the launch saves about 15-20 ms net, since the new hash costs about half of what the skipped read-back cost. With a cold cache the read-back costs more, so the saving should be larger. I did not measure that.

Two notes, neither blocking:

  1. The fast path trusts any regular file with the right name and length. The test shows this on purpose (the same-length sentinel is kept). sync_all before the rename covers a crash during publish. It does not cover a file changed later by something else, but a hash check would mean reading the file again.
  2. Old images are never removed. main reused one name per title build, so a loader change to prepare() overwrote the old copy. Now each distinct prepared image keeps its own ~115 MB file in images/. prepare.rs has changed twice this month, so it grows slowly. A cleanup of other leonida-image-*.dll files after a successful publish might be worth a follow-up.

Not checked: the game, and a cold-cache launch.

GPUs tested: n/a (CPU and file system tests only).

AI-assisted: yes (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants