feat(shaders): add shareable shader/pipeline recording (.hints) and offline precompilation #530

Open
github-bot wants to merge 5 commits from github-bot/gh-530 into main AGit
Owner

@⁠Mvii7 on GitHub · 2026-12-06 01:55 UTC · original
Mvii7:feat/shader-recording-precompile → main · +2028 −9 · 15 files · 5 commits · open

Summary

Adds chenxiao07/KytyPS5-style shareable shader/pipeline recordings (.hints), automatic bundled .hints import on launch, and standalone offline precompilation (larp shaders precompile — translating shaders and compiling host D3D12 pipelines directly from <cache_dir>\pipelines\ without loading or launching game_scarlett_master.exe, avoiding the game window and title RAM/VRAM footprint).

Both paths write into the exact same shaders\ and pipelines\blobs*\ cache:

  • Automatic on launch (larp run --execute): Drop a .hints file in Larp\hints\ (or Larp\ / Larp\bin\), and larp automatically imports it before startup warmup so the normal startup precompile bar compiles everything with zero extra user steps.
  • Standalone / offline (larp shaders precompile): Precompile shaders and host D3D12 pipelines ahead of time from the CLI without booting the game (e.g. after a GPU driver update or from a script).

What's included

  • crates/larp-pipeline/src/recording.rs: LRPSHD01 zlib-compressed, BLAKE3-checksummed recording format packing created-pipelines.bin + quad-pipelines.txt (zero copyrighted game shader bytecode — hashes and D3D12 state subobjects only), with --from merging, validation, fast 48-byte header checksum reads (read_header_checksum), safe quad-pipelines.txt newline-boundary handling, and apply_to_cache_dir.
  • crates/larp-gpu/src/pipeline/precompile.rs (plus blobs.rs, host.rs, make.rs, larp-hle/src/modules/d3d12x.rs): standalone shader translation + host D3D12 pipeline precompilation (no title executable loaded), skipping already-cached blobs (including compute via WarmMode::All), suppressing the E_ABORT skip warning for compute pipelines, and flushing the async blob writer before exit.
  • apps/larp/src/shaders_cmd.rs + apps/larp/src/run.rs + apps/larp/src/main.rs:
    • Automatic bundled .hints discovery & import on larp run --execute (before startup pipeline warmup) and larp shaders precompile (when no file arg is passed), scanning Larp\hints\, Larp\, Larp\bin\hints\, Larp\bin\, or LARP_SHADERS_HINTS (0/off disables). Deduplicates only after full decode and stamps <cache_dir>\pipelines\imported-hints.txt per-bundle only when all referenced shaders are resolved, so repeat launches skip in <1 ms while partial imports retry cleanly.
    • CLI commands:
      • larp shaders export <out.hints> [--from <file.hints>...] [--no-local] [--build <label>]
      • larp shaders info <file.hints>
      • larp shaders import <file.hints> [<game_path>...] [--jobs <N>]
      • larp shaders precompile [<file.hints>] [--game <path>...] [--jobs <N>] [--shaders-only]
  • docs/environment-variables.md: CLI and LARP_SHADERS_HINTS documentation.

Release & Community Workflow (Building One Master .hints File)

  1. Export per playthrough: Any player who finishes an area, mission, or playthrough exports their local cache into a small code-free .hints file (~1 MB for ~88k pipelines, zero game code; --build is optional and just stores an informational label for shaders info):
    larp.exe shaders export my-playthrough.hints
    
  2. Merge into one master .hints file (--from): Maintainers can deduplicate and combine any number of community-submitted .hints files (plus the previous release's master .hints) into a single master file:
    larp.exe shaders export master-1.0.2.1.hints --no-local --from prev-master.hints --from player1.hints --from player2.hints --build "1.0.2.1"
    
  3. Bundle in release: Drop the master .hints file into Larp\hints\ (or Larp\ / Larp\bin\) in the release ZIP.
  4. Automatic on launch: On first launch (larp run --execute), larp resolves the shader hashes against the user's own game files and feeds all recorded pipelines straight into the normal startup precompile bar. Repeat launches skip already-imported .hints in <1 ms, and interrupted precompiles resume from already-cached shaders\ and blobs*\.

Testing (Windows native, x86_64-pc-windows-msvc, rebased on main / PR #376)

  • cargo test -p larp-pipeline: 6/6 passed (including quad-mask newline-boundary and unreadable-catalog tests).
  • cargo test -p larp shaders_cmd::tests: 4/4 passed (complete, partial, empty, duplicate retry/dedup cases).
  • cargo build --release -p larp: clean build.
  • Live gameplay recording + export (54.7 MB created-pipelines.bin + 10.1 KB quad-pipelines.txt):
    • Verified live session appended +7 pipelines (88,604 → 88,611) and +28 quad-mask variants (278 → 306).
    • larp shaders export → 1029.8 KiB .hints file (~53× compression, zero game shader code), 19,059 unique shaders (1,167 VS, 8,525 PS, 2,682 CS, 6,685 MS).
    • larp shaders info → BLAKE3 checksum verified (checksum ok).
  • Full import into a clean cache against game files: matched 19,059 / 19,059 shaders in 36.5 s, resolved 88,604 / 88,604 pipelines + 278 quad variants (0 missing).
  • Automatic bundled .hints import + mixed 60-pipeline precompile (20 graphics VS+PS + 20 mesh MS+PS + 20 compute CS + shader-replace .dxils):
    • Cold run (auto-discovered via LARP_SHADERS_HINTS): matched 40 / 40 shaders, compiled 60 / 60 (0 failed, 3.6 s), stamped imported-hints.txt.
    • Warm run: instantly skipped game-file scan via imported-hints.txt, 0 new, 60 / 60 already cached (40 from shader cache, 0 warnings, 0.6 s).
**@⁠Mvii7** on GitHub · 2026-12-06 01:55 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530) `Mvii7:feat/shader-recording-precompile` → `main` · +2028 −9 · 15 files · 5 commits · open ## Summary Adds chenxiao07/KytyPS5-style shareable shader/pipeline recordings (`.hints`), automatic bundled `.hints` import on launch, and standalone **offline precompilation** (`larp shaders precompile` — translating shaders and compiling host D3D12 pipelines directly from `<cache_dir>\pipelines\` **without loading or launching `game_scarlett_master.exe`**, avoiding the game window and title RAM/VRAM footprint). Both paths write into the exact same `shaders\` and `pipelines\blobs*\` cache: - **Automatic on launch (`larp run --execute`)**: Drop a `.hints` file in `Larp\hints\` (or `Larp\` / `Larp\bin\`), and `larp` automatically imports it before startup warmup so the normal startup precompile bar compiles everything with zero extra user steps. - **Standalone / offline (`larp shaders precompile`)**: Precompile shaders and host D3D12 pipelines ahead of time from the CLI without booting the game (e.g. after a GPU driver update or from a script). ### What's included - **`crates/larp-pipeline/src/recording.rs`**: `LRPSHD01` zlib-compressed, BLAKE3-checksummed recording format packing `created-pipelines.bin` + `quad-pipelines.txt` (**zero copyrighted game shader bytecode** — hashes and D3D12 state subobjects only), with `--from` merging, validation, fast 48-byte header checksum reads (`read_header_checksum`), safe `quad-pipelines.txt` newline-boundary handling, and `apply_to_cache_dir`. - **`crates/larp-gpu/src/pipeline/precompile.rs`** (plus `blobs.rs`, `host.rs`, `make.rs`, `larp-hle/src/modules/d3d12x.rs`): standalone shader translation + host D3D12 pipeline precompilation (no title executable loaded), skipping already-cached blobs (including compute via `WarmMode::All`), suppressing the `E_ABORT` skip warning for compute pipelines, and flushing the async blob writer before exit. - **`apps/larp/src/shaders_cmd.rs` + `apps/larp/src/run.rs` + `apps/larp/src/main.rs`**: - Automatic bundled `.hints` discovery & import on `larp run --execute` (before startup pipeline warmup) and `larp shaders precompile` (when no file arg is passed), scanning `Larp\hints\`, `Larp\`, `Larp\bin\hints\`, `Larp\bin\`, or `LARP_SHADERS_HINTS` (`0`/`off` disables). Deduplicates only after full decode and stamps `<cache_dir>\pipelines\imported-hints.txt` per-bundle only when all referenced shaders are resolved, so repeat launches skip in <1 ms while partial imports retry cleanly. - CLI commands: - `larp shaders export <out.hints> [--from <file.hints>...] [--no-local] [--build <label>]` - `larp shaders info <file.hints>` - `larp shaders import <file.hints> [<game_path>...] [--jobs <N>]` - `larp shaders precompile [<file.hints>] [--game <path>...] [--jobs <N>] [--shaders-only]` - **`docs/environment-variables.md`**: CLI and `LARP_SHADERS_HINTS` documentation. ## Release & Community Workflow (Building One Master `.hints` File) 1. **Export per playthrough**: Any player who finishes an area, mission, or playthrough exports their local cache into a small code-free `.hints` file (~1 MB for ~88k pipelines, zero game code; `--build` is optional and just stores an informational label for `shaders info`): ```powershell larp.exe shaders export my-playthrough.hints ``` 2. **Merge into one master `.hints` file (`--from`)**: Maintainers can deduplicate and combine any number of community-submitted `.hints` files (plus the previous release's master `.hints`) into a single master file: ```powershell larp.exe shaders export master-1.0.2.1.hints --no-local --from prev-master.hints --from player1.hints --from player2.hints --build "1.0.2.1" ``` 3. **Bundle in release**: Drop the master `.hints` file into `Larp\hints\` (or `Larp\` / `Larp\bin\`) in the release ZIP. 4. **Automatic on launch**: On first launch (`larp run --execute`), `larp` resolves the shader hashes against the user's own game files and feeds all recorded pipelines straight into the normal startup precompile bar. Repeat launches skip already-imported `.hints` in <1 ms, and interrupted precompiles resume from already-cached `shaders\` and `blobs*\`. ## Testing (Windows native, `x86_64-pc-windows-msvc`, rebased on `main` / PR #376) - `cargo test -p larp-pipeline`: 6/6 passed (including quad-mask newline-boundary and unreadable-catalog tests). - `cargo test -p larp shaders_cmd::tests`: 4/4 passed (`complete`, `partial`, `empty`, `duplicate` retry/dedup cases). - `cargo build --release -p larp`: clean build. - Live gameplay recording + export (`54.7 MB` `created-pipelines.bin` + `10.1 KB` `quad-pipelines.txt`): - Verified live session appended **+7 pipelines** (`88,604` → `88,611`) and **+28 quad-mask variants** (`278` → `306`). - `larp shaders export` → `1029.8 KiB` `.hints` file (~53× compression, zero game shader code), `19,059` unique shaders (`1,167` VS, `8,525` PS, `2,682` CS, `6,685` MS). - `larp shaders info` → BLAKE3 checksum verified (`checksum ok`). - Full `import` into a clean cache against game files: matched **19,059 / 19,059** shaders in `36.5 s`, resolved **88,604 / 88,604** pipelines + `278` quad variants (`0` missing). - Automatic bundled `.hints` import + mixed 60-pipeline `precompile` (20 graphics VS+PS + 20 mesh MS+PS + 20 compute CS + `shader-replace` `.dxil`s): - Cold run (auto-discovered via `LARP_SHADERS_HINTS`): matched `40 / 40` shaders, compiled `60 / 60` (`0` failed, `3.6 s`), stamped `imported-hints.txt`. - Warm run: instantly skipped game-file scan via `imported-hints.txt`, `0` new, `60 / 60` already cached (`40` from shader cache, `0` warnings, `0.6 s`).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-06 02:00:45 +00:00
Author
Owner

@⁠Heliumrich on GitHub · 2026-12-06 02:02 UTC · original

Do these hints get outdated with code changes ?
Like will we get graphical bugs if we use old hints on a way more recent build of this project ?

Or at worst just useless garbage shader files polluting our disk of a few GBs

**@⁠Heliumrich** on GitHub · 2026-12-06 02:02 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7449641459) Do these hints get outdated with code changes ? Like will we get graphical bugs if we use old hints on a way more recent build of this project ? Or at worst just useless garbage shader files polluting our disk of a few GBs
Author
Owner

@⁠Mvii7 on GitHub · 2026-12-06 02:51 UTC · original

Do these hints get outdated with code changes ? Like will we get graphical bugs if we use old hints on a way more recent build of this project ?

Or at worst just useless garbage shader files polluting our disk of a few GBs

No graphical bugs on newer larp builds: .hints files don't store any translated DXIL, replacement shaders, or GPU driver blobs — they only store the console shader hashes and D3D12 pipeline state recipes the game itself asks for. When larp's translator, shader-replace, or root signature changes, larp translates and compiles those pipelines using the new build's translator and replacement shaders (and shaders/ + blobs*/ are already keyed by translator output + host state + driver).

What actually invalidates a .hints file: Mainly a game update that changes shader binaries (unmatched hashes are cleanly skipped on import without error), or a future breaking change to created-pipelines.bin's wire format (VICPSOS1), which Recording::decode validates and rejects safely.

Disk usage: The .hints file itself is only ~1 MB for ~88k pipelines, and importing deduplicates against your existing created-pipelines.bin / created-shaders.bin — it only populates the same files larp would create as you play through those areas. If a major translator change ever leaves old cached shaders/ or blobs*/ files behind, you can wipe cache\ just like today and larp will automatically re-import the .hints file and rebuild cleanly on the next launch.

**@⁠Mvii7** on GitHub · 2026-12-06 02:51 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450261862) > Do these hints get outdated with code changes ? Like will we get graphical bugs if we use old hints on a way more recent build of this project ? > > Or at worst just useless garbage shader files polluting our disk of a few GBs No graphical bugs on newer larp builds: .hints files don't store any translated DXIL, replacement shaders, or GPU driver blobs — they only store the console shader hashes and D3D12 pipeline state recipes the game itself asks for. When larp's translator, shader-replace, or root signature changes, larp translates and compiles those pipelines using the new build's translator and replacement shaders (and shaders/ + blobs*/ are already keyed by translator output + host state + driver). What actually invalidates a .hints file: Mainly a game update that changes shader binaries (unmatched hashes are cleanly skipped on import without error), or a future breaking change to created-pipelines.bin's wire format (VICPSOS1), which Recording::decode validates and rejects safely. Disk usage: The .hints file itself is only ~1 MB for ~88k pipelines, and importing deduplicates against your existing created-pipelines.bin / created-shaders.bin — it only populates the same files larp would create as you play through those areas. If a major translator change ever leaves old cached shaders/ or blobs*/ files behind, you can wipe cache\ just like today and larp will automatically re-import the .hints file and rebuild cleanly on the next launch.
Author
Owner

@⁠christopear on GitHub · 2026-12-06 02:56 UTC · original

I reproduced two retry problems in bundled auto-import on 8fc37b836. Both can leave valid recipes out of the local catalog even when all the required inputs are available on the next run.

Incomplete imports get a permanent success stamp. I made one valid recording with two compute recipes, each referencing a different synthetic container. On the first call I supplied only one container, then supplied both on calls two and three. The catalog stayed at 1, 1, 1. With neither container initially available it stayed at 0, 0, 0. Both runs wrote the checksum on the first call. The complete control gave 2, 2, 2 and correctly skipped subsequent work.

An earlier broken copy can hide a valid bundle. Put the first 48 bytes of a valid recording in a.hints and the complete file in b.hints in the same discovery directory. With both containers available the catalog stayed empty. The first header reserves the checksum before payload validation, so the good copy is never tried.

I ran each case three times using the PR's auto-import and discovery functions in a Linux test harness, with the real recording encoder, decoder and cache writer. Only the game scanner was replaced with a deterministic fixture lookup. The four existing recording tests also passed.

Two small changes confirmed the diagnosis. Deduplicate new candidates only after successful decoding, and withhold completion stamps while recipes are unresolved. All four cases then reached two recipes by the second call and skipped work on the third, in three repetitions each.

For production I'd distinguish a partial import from a completed one per bundle. A clear retry option for partial imports would avoid rescanning permanently unmatched game versions every launch. The fully resolved fast path can stay as it is. This is separate from invalidating translated shaders after a code change.

Standalone regression fixture for this revision

In a disposable checkout, save the Rust block as crates/larp-pipeline/tests/retry.rs (create the tests directory if needed). Append the unmodified import and discovery functions from the CLI, then run each case in a fresh temporary directory. The printed tuples give the return value, catalog count and whether the stamp file exists.

sed -n '/^pub fn auto_import_bundled_hints(/,$p' apps/larp/src/shaders_cmd.rs >> crates/larp-pipeline/tests/retry.rs
for mode in complete partial empty duplicate; do
    root=$(mktemp -d) || exit 1
    mkdir "$root/hints" || exit 1
    CASE="$mode" LARP_SHADERS_HINTS="$root/hints" cargo test --locked -p larp-pipeline --test retry -- --nocapture
done
use anyhow::{Context, Result};
use larp_pipeline::recording::{self, Recording};
use std::{
    collections::{HashMap, HashSet},
    io::Write,
    path::{Path, PathBuf},
    time::Instant,
};
const IMPORTED_HINTS_FILE: &str = "imported-hints.txt";
fn scan_game_shaders(
    paths: &[PathBuf],
    needed: &HashSet<u64>,
    _: Option<usize>,
) -> HashMap<u64, Vec<u8>> {
    std::fs::read_dir(&paths[0])
        .unwrap()
        .map(|f| std::fs::read(f.unwrap().path()).unwrap())
        .map(|v| (recording::short_hash_u64(&v), v))
        .filter(|(k, _)| needed.contains(k))
        .collect()
}
fn recipe(data: &[u8]) -> Vec<u8> {
    let mut b = vec![1, 5];
    b.extend(recording::short_hash_u64(data).to_le_bytes());
    b.push(0);
    b
}
#[test]
fn retry_import() {
    let mode = std::env::var("CASE").unwrap();
    let dir = PathBuf::from(std::env::var_os("LARP_SHADERS_HINTS").unwrap());
    let root = dir.parent().unwrap();
    let game = root.join("game");
    std::fs::create_dir(&game).unwrap();
    let cfg = larp_core::Config {
        game_dir: Some(game.clone()),
        cache_dir: root.join("cache"),
        ..Default::default()
    };
    let cache = cfg.cache_subdir("pipelines").unwrap();
    let rec = Recording {
        pipelines: vec![recipe(b"a"), recipe(b"b")],
        ..Default::default()
    };
    rec.write_to(&dir.join("b.hints")).unwrap();
    if mode == "duplicate" {
        let bytes = rec.encode().unwrap();
        std::fs::write(dir.join("a.hints"), &bytes[..48]).unwrap();
    }
    if mode != "empty" {
        std::fs::write(game.join("a"), b"a").unwrap();
    }
    if mode == "complete" || mode == "duplicate" {
        std::fs::write(game.join("b"), b"b").unwrap();
    }
    let mut observations = vec![];
    for i in 0..3 {
        if i == 1 {
            std::fs::write(game.join("a"), b"a").unwrap();
            std::fs::write(game.join("b"), b"b").unwrap();
        }
        let imported = auto_import_bundled_hints(&cfg, None).unwrap();
        let n = Recording::from_cache_dir(&cache).unwrap().pipelines.len();
        observations.push((imported, n, cache.join(IMPORTED_HINTS_FILE).exists()));
    }
    println!("OBS {mode} {observations:?}");
    assert_eq!(
        observations[0].1,
        match mode.as_str() {
            "empty" => 0,
            "partial" => 1,
            _ => 2,
        }
    );
    assert_eq!(observations[1].1, 2);
    assert_eq!(observations[2], (false, 2, true));
}
**@⁠christopear** on GitHub · 2026-12-06 02:56 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450319582) I reproduced two retry problems in bundled auto-import on `8fc37b836`. Both can leave valid recipes out of the local catalog even when all the required inputs are available on the next run. **Incomplete imports get a permanent success stamp.** I made one valid recording with two compute recipes, each referencing a different synthetic container. On the first call I supplied only one container, then supplied both on calls two and three. The catalog stayed at 1, 1, 1. With neither container initially available it stayed at 0, 0, 0. Both runs wrote the checksum on the first call. The complete control gave 2, 2, 2 and correctly skipped subsequent work. **An earlier broken copy can hide a valid bundle.** Put the first 48 bytes of a valid recording in `a.hints` and the complete file in `b.hints` in the same discovery directory. With both containers available the catalog stayed empty. The first header reserves the checksum before payload validation, so the good copy is never tried. I ran each case three times using the PR's auto-import and discovery functions in a Linux test harness, with the real recording encoder, decoder and cache writer. Only the game scanner was replaced with a deterministic fixture lookup. The four existing recording tests also passed. Two small changes confirmed the diagnosis. Deduplicate new candidates only after successful decoding, and withhold completion stamps while recipes are unresolved. All four cases then reached two recipes by the second call and skipped work on the third, in three repetitions each. For production I'd distinguish a partial import from a completed one per bundle. A clear retry option for partial imports would avoid rescanning permanently unmatched game versions every launch. The fully resolved fast path can stay as it is. This is separate from invalidating translated shaders after a code change. <details> <summary>Standalone regression fixture for this revision</summary> In a disposable checkout, save the Rust block as `crates/larp-pipeline/tests/retry.rs` (create the tests directory if needed). Append the unmodified import and discovery functions from the CLI, then run each case in a fresh temporary directory. The printed tuples give the return value, catalog count and whether the stamp file exists. ```sh sed -n '/^pub fn auto_import_bundled_hints(/,$p' apps/larp/src/shaders_cmd.rs >> crates/larp-pipeline/tests/retry.rs for mode in complete partial empty duplicate; do root=$(mktemp -d) || exit 1 mkdir "$root/hints" || exit 1 CASE="$mode" LARP_SHADERS_HINTS="$root/hints" cargo test --locked -p larp-pipeline --test retry -- --nocapture done ``` ```rust use anyhow::{Context, Result}; use larp_pipeline::recording::{self, Recording}; use std::{ collections::{HashMap, HashSet}, io::Write, path::{Path, PathBuf}, time::Instant, }; const IMPORTED_HINTS_FILE: &str = "imported-hints.txt"; fn scan_game_shaders( paths: &[PathBuf], needed: &HashSet<u64>, _: Option<usize>, ) -> HashMap<u64, Vec<u8>> { std::fs::read_dir(&paths[0]) .unwrap() .map(|f| std::fs::read(f.unwrap().path()).unwrap()) .map(|v| (recording::short_hash_u64(&v), v)) .filter(|(k, _)| needed.contains(k)) .collect() } fn recipe(data: &[u8]) -> Vec<u8> { let mut b = vec![1, 5]; b.extend(recording::short_hash_u64(data).to_le_bytes()); b.push(0); b } #[test] fn retry_import() { let mode = std::env::var("CASE").unwrap(); let dir = PathBuf::from(std::env::var_os("LARP_SHADERS_HINTS").unwrap()); let root = dir.parent().unwrap(); let game = root.join("game"); std::fs::create_dir(&game).unwrap(); let cfg = larp_core::Config { game_dir: Some(game.clone()), cache_dir: root.join("cache"), ..Default::default() }; let cache = cfg.cache_subdir("pipelines").unwrap(); let rec = Recording { pipelines: vec![recipe(b"a"), recipe(b"b")], ..Default::default() }; rec.write_to(&dir.join("b.hints")).unwrap(); if mode == "duplicate" { let bytes = rec.encode().unwrap(); std::fs::write(dir.join("a.hints"), &bytes[..48]).unwrap(); } if mode != "empty" { std::fs::write(game.join("a"), b"a").unwrap(); } if mode == "complete" || mode == "duplicate" { std::fs::write(game.join("b"), b"b").unwrap(); } let mut observations = vec![]; for i in 0..3 { if i == 1 { std::fs::write(game.join("a"), b"a").unwrap(); std::fs::write(game.join("b"), b"b").unwrap(); } let imported = auto_import_bundled_hints(&cfg, None).unwrap(); let n = Recording::from_cache_dir(&cache).unwrap().pipelines.len(); observations.push((imported, n, cache.join(IMPORTED_HINTS_FILE).exists())); } println!("OBS {mode} {observations:?}"); assert_eq!( observations[0].1, match mode.as_str() { "empty" => 0, "partial" => 1, _ => 2, } ); assert_eq!(observations[1].1, 2); assert_eq!(observations[2], (false, 2, true)); } ``` </details>
Author
Owner

@⁠Mvii7 on GitHub · 2026-12-06 03:03 UTC · original

Great catch @⁠christopear — thanks for the detailed repro and regression harness! Fixed both in 0f084e6:

  1. Deduplicate only after full decode: auto_import_bundled_hints_with now skips only checksums already in imported-hints.txt during the header pass, and only records a checksum in seen_decoded after Recording::read_from succeeds — so an earlier truncated/corrupt file with a valid 48-byte header can no longer shadow a valid bundle.
  2. Per-bundle completion stamping: Each decoded bundle's referenced shader hashes are tracked individually, and a bundle's checksum is only appended to imported-hints.txt when all of its referenced shaders are resolved (either already cached or matched in the scan). Unresolved/partial bundles remain unstamped so they retry when missing game files become available (with a message noting LARP_SHADERS_HINTS=0 to skip rescanning if intentionally running against a mismatched game version).
  3. Regression tests: Added unit tests in apps/larp/src/shaders_cmd.rs (shaders_cmd::tests) covering all four cases (complete, partial, empty, and duplicate) — all 4 pass (cargo test -p larp shaders_cmd::tests).
**@⁠Mvii7** on GitHub · 2026-12-06 03:03 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450395701) Great catch @⁠christopear — thanks for the detailed repro and regression harness! Fixed both in `0f084e6`: 1. **Deduplicate only after full decode**: `auto_import_bundled_hints_with` now skips only checksums already in `imported-hints.txt` during the header pass, and only records a checksum in `seen_decoded` after `Recording::read_from` succeeds — so an earlier truncated/corrupt file with a valid 48-byte header can no longer shadow a valid bundle. 2. **Per-bundle completion stamping**: Each decoded bundle's referenced shader hashes are tracked individually, and a bundle's checksum is only appended to `imported-hints.txt` when all of its referenced shaders are resolved (either already cached or matched in the scan). Unresolved/partial bundles remain unstamped so they retry when missing game files become available (with a message noting `LARP_SHADERS_HINTS=0` to skip rescanning if intentionally running against a mismatched game version). 3. **Regression tests**: Added unit tests in `apps/larp/src/shaders_cmd.rs` (`shaders_cmd::tests`) covering all four cases (`complete`, `partial`, `empty`, and `duplicate`) — all 4 pass (`cargo test -p larp shaders_cmd::tests`).
Author
Owner

@⁠christopear on GitHub · 2026-12-06 03:09 UTC · original

Retested 0f084e6. Both of my earlier findings are resolved in the fixture tests. All four of your cases passed.

I also tried overlapping bundles in the same import, with the incomplete one first. Bundle A needed shader a, bundle B needed a/b/c.

  • With a/b available, the cache held two recipes and only A’s exact checksum was stamped.
  • After adding c, the scanner was asked for c alone. The cache held three recipes and both checksums appeared exactly once.
  • A third call skipped scanning entirely.

That covers the case where a successfully imported bundle shares a shader with one that needs a retry. I ran the CLI import functions and tests in a native Rust harness with the real recording/cache code and a fixture scanner. No game run or archive scanning involved. Thanks for fixing these!

**@⁠christopear** on GitHub · 2026-12-06 03:09 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450467771) Retested `0f084e6`. Both of my earlier findings are resolved in the fixture tests. All four of your cases passed. I also tried overlapping bundles in the same import, with the incomplete one first. Bundle A needed shader a, bundle B needed a/b/c. * With a/b available, the cache held two recipes and only A’s exact checksum was stamped. * After adding c, the scanner was asked for c alone. The cache held three recipes and both checksums appeared exactly once. * A third call skipped scanning entirely. That covers the case where a successfully imported bundle shares a shader with one that needs a retry. I ran the CLI import functions and tests in a native Rust harness with the real recording/cache code and a fixture scanner. No game run or archive scanning involved. Thanks for fixing these!
Author
Owner

@⁠christopear on GitHub · 2026-12-06 03:15 UTC · original

One separate writer needs the same boundary handling as #575. That PR only changes the GPU runtime writer. This branch also appends to quad-pipelines.txt in recording::apply_to_cache_dir.

I started with a complete 32-character key A lacking its final newline, then auto-imported a valid one-recipe bundle containing key B. The import reported success, stamped the bundle and skipped the next call. Reading the catalog returned one 64-character AB entry. Neither exact key survived. I also checked an invalid UTF-8 catalog, where treating a read error as an empty file lets the append report success.

Here's an applicable patch against 0f084e6. It reuses the text already read for deduplication, preserves the existing bytes and propagates read errors other than absence. It assumes a single writer. It prevents new joins and leaves previously joined entries alone.

Both new library tests failed on the original implementation in three runs. With the patch all six library tests passed three times. The stamped auto-import reproduction also passed in six native Rust fixture runs with the production import functions and a synthetic scanner. No gameplay testing.

Patch and regression tests
--- a/crates/larp-pipeline/src/recording.rs
+++ b/crates/larp-pipeline/src/recording.rs
@@ -569,12 +569,15 @@
     // 3. Append any new quad-mask pipeline keys.
     if !recording.quads.is_empty() {
         let quads_path = pipelines_dir.join(QUADS_FILE);
-        let existing_quads: HashSet<String> = std::fs::read_to_string(&quads_path)
-            .unwrap_or_default()
+        let text = match std::fs::read_to_string(&quads_path) {
+            Ok(text) => text,
+            Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(),
+            Err(e) => return Err(e).with_context(|| format!("reading {}", quads_path.display())),
+        };
+        let existing_quads: HashSet<&str> = text
             .lines()
             .map(str::trim)
             .filter(|l| !l.is_empty())
-            .map(str::to_owned)
             .collect();
         let new_quads: Vec<&str> = recording
             .quads
@@ -588,6 +591,9 @@
                 .append(true)
                 .open(&quads_path)
                 .with_context(|| format!("opening {}", quads_path.display()))?;
+            if !text.is_empty() && !text.ends_with('\n') {
+                writeln!(file)?;
+            }
             for key in &new_quads {
                 writeln!(file, "{key}")?;
             }
@@ -918,4 +924,55 @@
         let _ = std::fs::remove_dir_all(src_dir);
         let _ = std::fs::remove_dir_all(dst_dir);
     }
+
+    #[test]
+    fn import_keeps_quad_keys_separate_and_repeatable() {
+        let key = "b".repeat(32);
+        let rec = Recording {
+            quads: vec![key.clone()],
+            ..Default::default()
+        };
+        let a = "a".repeat(32);
+        for tail in [
+            None,
+            Some(String::new()),
+            Some("123".into()),
+            Some(a.clone()),
+            Some(format!("{a}\n")),
+            Some(format!("{a}\r\n")),
+        ] {
+            let dir = temp_dir("quad-tail");
+            let path = dir.join(QUADS_FILE);
+            let old = tail.as_deref().unwrap_or_default();
+            if tail.is_some() {
+                std::fs::write(&path, old).unwrap();
+            }
+            let sep = if old.is_empty() || old.ends_with('\n') {
+                ""
+            } else {
+                "\n"
+            };
+            let expected = format!("{old}{sep}{key}\n");
+            for added in [1, 0] {
+                let report = apply_to_cache_dir(&dir, &rec, &HashMap::new()).unwrap();
+                assert_eq!(report.quads_added, added);
+                assert_eq!(std::fs::read_to_string(&path).unwrap(), expected);
+            }
+            std::fs::remove_dir_all(dir).unwrap();
+        }
+    }
+
+    #[test]
+    fn import_preserves_an_unreadable_quad_catalog() {
+        let dir = temp_dir("quad-invalid");
+        let path = dir.join(QUADS_FILE);
+        std::fs::write(&path, [0xff]).unwrap();
+        let rec = Recording {
+            quads: vec!["b".repeat(32)],
+            ..Default::default()
+        };
+        assert!(apply_to_cache_dir(&dir, &rec, &HashMap::new()).is_err());
+        assert_eq!(std::fs::read(&path).unwrap(), [0xff]);
+        std::fs::remove_dir_all(dir).unwrap();
+    }
 }
**@⁠christopear** on GitHub · 2026-12-06 03:15 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450552138) One separate writer needs the same boundary handling as #575. That PR only changes the GPU runtime writer. This branch also appends to quad-pipelines.txt in `recording::apply_to_cache_dir`. I started with a complete 32-character key A lacking its final newline, then auto-imported a valid one-recipe bundle containing key B. The import reported success, stamped the bundle and skipped the next call. Reading the catalog returned one 64-character AB entry. Neither exact key survived. I also checked an invalid UTF-8 catalog, where treating a read error as an empty file lets the append report success. Here's an applicable patch against `0f084e6`. It reuses the text already read for deduplication, preserves the existing bytes and propagates read errors other than absence. It assumes a single writer. It prevents new joins and leaves previously joined entries alone. Both new library tests failed on the original implementation in three runs. With the patch all six library tests passed three times. The stamped auto-import reproduction also passed in six native Rust fixture runs with the production import functions and a synthetic scanner. No gameplay testing. <details> <summary>Patch and regression tests</summary> ```diff --- a/crates/larp-pipeline/src/recording.rs +++ b/crates/larp-pipeline/src/recording.rs @@ -569,12 +569,15 @@ // 3. Append any new quad-mask pipeline keys. if !recording.quads.is_empty() { let quads_path = pipelines_dir.join(QUADS_FILE); - let existing_quads: HashSet<String> = std::fs::read_to_string(&quads_path) - .unwrap_or_default() + let text = match std::fs::read_to_string(&quads_path) { + Ok(text) => text, + Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(e).with_context(|| format!("reading {}", quads_path.display())), + }; + let existing_quads: HashSet<&str> = text .lines() .map(str::trim) .filter(|l| !l.is_empty()) - .map(str::to_owned) .collect(); let new_quads: Vec<&str> = recording .quads @@ -588,6 +591,9 @@ .append(true) .open(&quads_path) .with_context(|| format!("opening {}", quads_path.display()))?; + if !text.is_empty() && !text.ends_with('\n') { + writeln!(file)?; + } for key in &new_quads { writeln!(file, "{key}")?; } @@ -918,4 +924,55 @@ let _ = std::fs::remove_dir_all(src_dir); let _ = std::fs::remove_dir_all(dst_dir); } + + #[test] + fn import_keeps_quad_keys_separate_and_repeatable() { + let key = "b".repeat(32); + let rec = Recording { + quads: vec![key.clone()], + ..Default::default() + }; + let a = "a".repeat(32); + for tail in [ + None, + Some(String::new()), + Some("123".into()), + Some(a.clone()), + Some(format!("{a}\n")), + Some(format!("{a}\r\n")), + ] { + let dir = temp_dir("quad-tail"); + let path = dir.join(QUADS_FILE); + let old = tail.as_deref().unwrap_or_default(); + if tail.is_some() { + std::fs::write(&path, old).unwrap(); + } + let sep = if old.is_empty() || old.ends_with('\n') { + "" + } else { + "\n" + }; + let expected = format!("{old}{sep}{key}\n"); + for added in [1, 0] { + let report = apply_to_cache_dir(&dir, &rec, &HashMap::new()).unwrap(); + assert_eq!(report.quads_added, added); + assert_eq!(std::fs::read_to_string(&path).unwrap(), expected); + } + std::fs::remove_dir_all(dir).unwrap(); + } + } + + #[test] + fn import_preserves_an_unreadable_quad_catalog() { + let dir = temp_dir("quad-invalid"); + let path = dir.join(QUADS_FILE); + std::fs::write(&path, [0xff]).unwrap(); + let rec = Recording { + quads: vec!["b".repeat(32)], + ..Default::default() + }; + assert!(apply_to_cache_dir(&dir, &rec, &HashMap::new()).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), [0xff]); + std::fs::remove_dir_all(dir).unwrap(); + } } ``` </details>
Author
Owner

@⁠Mvii7 on GitHub · 2026-12-06 03:20 UTC · original

Good catch again @⁠christopear — applied your patch and both regression tests in 6d146aa. All 6 larp-pipeline tests pass.

**@⁠Mvii7** on GitHub · 2026-12-06 03:20 UTC · [original](https://github.com/gamingwithhomie/larp/pull/530#issuecomment-7450614245) Good catch again @⁠christopear — applied your patch and both regression tests in `6d146aa`. All 6 `larp-pipeline` tests pass.
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/530/head:github-bot/gh-530'
git switch 'github-bot/gh-530'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-530'
git switch 'github-bot/gh-530'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-530'
git switch 'github-bot/gh-530'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-530'
git switch 'main'
git merge --squash 'github-bot/gh-530'
git switch 'main'
git merge --ff-only 'github-bot/gh-530'
git switch 'main'
git merge 'github-bot/gh-530'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.