Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(render): share the image cap and keep fifo cleanup from blocking
load_texture_async now uses read_capped_image. A regular file over 64
MiB is rejected from its length. A fifo that fills the cap is rejected
without a further read.

The fifo drop test is unix-only, lives in a temp directory, and opens
its cleanup writer with O_NONBLOCK. The trace stamp is 2ce0da5. The
0.275 ms Hi-Z figure is that 1660 Ti capture; the default frame does
not record it.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 21, 2026
commit 36757dad09f0afd1368cab766f1ba5a8c433b0c1
55 changes: 49 additions & 6 deletions astraweave-render/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,50 @@ use image::{DynamicImage, GenericImageView};
#[cfg(feature = "textures")]
use std::path::Path;

/// Read an image file without exceeding [`astraweave_asset::image_limits::MAX_IMAGE_ALLOC`].
///
/// A regular file longer than the cap is rejected from its metadata, before
/// any byte is read. A regular file is then read only up to that length.
/// A fifo or other non-regular file is read with `take(cap)` and stopped
/// there: probing one byte past the cap would block if the writer stalled
/// after exactly that many bytes.
pub(crate) async fn read_capped_image(path: &str) -> Result<Vec<u8>, String> {
use tokio::io::AsyncReadExt;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
let meta = tokio::fs::metadata(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
if meta.is_file() {
if meta.len() > cap {
return Err(format!("image is {} bytes, cap is {cap}", meta.len()));
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(meta.len())
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
return Ok(bytes);
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(cap)
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
if bytes.len() as u64 == cap {
return Err(format!("image exceeds {cap} bytes"));
}
Ok(bytes)
Comment on lines +15 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

read_capped_image is a second image-file reader. astraweave_asset::open_limited_image is the function trace v1.21 names, and it still does std::fs::read of the whole path before decode_limited_image. The 64 MiB decoder cap never runs if that read has already allocated the file.

Callers of that function include validate_texture_assets in this file, material_loader, ibl, impostor_bake, set_smoke_test_texture, the editor material inspector, and aw_asset_cli. Texture::from_file_with_usage (line 231) is the same unbounded std::fs::read on the public sync API of this type. It has no caller outside this module today.

The policy in this function holds. A regular file over the cap is rejected from metadata, and take(meta.len()) keeps a later swap inside a length that already passed len > cap. A fifo that delivers exactly the cap returns here without another read. Rejecting equality on a non-regular stream is the safe side: one more byte is the only way to tell EOF from "more", and that byte is what blocked. A regular file of exactly 64 MiB still loads, which matches MAX_IMAGE_ALLOC as an inclusive bound.

Put the bounded read in astraweave_asset::image_limits and call it from open_limited_image. This async function can stay the fifo-safe wrapper. A second cap means the next loader follows the helper whose read is not capped.

}

/// Defines how a texture should be interpreted for correct color space handling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
Expand Down Expand Up @@ -326,13 +370,12 @@ impl Texture {
path: &str,
usage: TextureUsage,
) -> Result<Self> {
use std::path::Path;

// Phase 1: Async file I/O (off main thread)
let path_buf = Path::new(path).to_path_buf();
let bytes = tokio::fs::read(&path_buf)
// Phase 1: Async file I/O (off main thread). Same 64 MiB cap as
// `texture_streaming::decode_texture`: length is checked before the
// read, and a non-regular file is not probed one byte past the cap.
let bytes = read_capped_image(path)
.await
.map_err(|e| anyhow::anyhow!("Failed to read texture file {}: {}", path, e))?;
.map_err(|e| anyhow::anyhow!("Failed to read texture file {path}: {e}"))?;

// Phase 2: Async image decoding (on thread pool)
let label = path.to_string();
Expand Down
157 changes: 115 additions & 42 deletions astraweave-render/src/texture_streaming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ impl TextureStreamingManager {
}

async fn decode_texture(id: String) -> StreamMsg {
let bytes = match read_capped_image(&id).await {
let bytes = match crate::texture::read_capped_image(&id).await {
Ok(bytes) => bytes,
Err(error) => {
return StreamMsg::Failed { id, error };
Expand All @@ -662,40 +662,6 @@ async fn decode_texture(id: String) -> StreamMsg {
}
}

/// Reject a file whose length is already over the image cap, then read at
/// most that many bytes. A fifo reports length 0, so the `take` is what
/// stops a stream that never ends.
async fn read_capped_image(path: &str) -> Result<Vec<u8>, String> {
let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
let meta = tokio::fs::metadata(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
if meta.len() > cap {
return Err(format!("image is {} bytes, cap is {cap}", meta.len()));
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
use tokio::io::AsyncReadExt;
(&mut file)
.take(cap)
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
if bytes.len() as u64 == cap {
let mut extra = [0u8; 1];
let more = file
.read(&mut extra)
.await
.map_err(|err| format!("read failed: {err}"))?;
if more > 0 {
return Err(format!("image exceeds {cap} bytes"));
}
}
Ok(bytes)
}

fn decode_bytes(bytes: &[u8]) -> anyhow::Result<(u32, u32, Vec<u8>)> {
#[cfg(feature = "textures")]
{
Expand Down Expand Up @@ -991,6 +957,48 @@ mod tests {
}
}

#[cfg(feature = "textures")]
#[test]
fn load_texture_async_rejects_a_file_over_the_cap() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("huge.bin");
let file = std::fs::File::create(&path).expect("create");
let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
file.set_len(cap + 1).expect("set_len");
drop(file);
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let Ok(adapter) =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
compatible_surface: None,
force_fallback_adapter: false,
}))
else {
eprintln!("skip load_texture_async cap: no wgpu adapter");
return;
};
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
.expect("device");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
let err = runtime
.block_on(crate::texture::Texture::load_texture_async(
&device,
&queue,
&path.to_string_lossy(),
crate::texture::TextureUsage::Albedo,
))
.expect_err("file over the cap must fail");
let msg = format!("{err:#}");
assert!(
msg.contains(&cap.to_string()) && msg.contains(&(cap + 1).to_string()),
"{msg}"
);
}

#[cfg(feature = "textures")]
#[test]
fn decode_bytes_rejects_an_edge_past_4096() {
Expand All @@ -1010,29 +1018,94 @@ mod tests {
);
}

#[cfg(unix)]
#[test]
fn drop_returns_while_a_fifo_read_is_blocked() {
let path = format!("/tmp/aw-stream-drop-{}.png", std::process::id());
let _ = std::fs::remove_file(&path);
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("blocked.png");
let made = std::process::Command::new("mkfifo")
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
.arg(&path)
.status()
.expect("mkfifo");
assert!(made.success(), "mkfifo");
let mut mgr = TextureStreamingManager::new(64).expect("texture streaming runtime");
mgr.request_at(&path, Vec3::ZERO);
let path_str = path.to_string_lossy().into_owned();
mgr.request_at(&path_str, Vec3::ZERO);
assert!(mgr.start_one_decode(), "decode should start");
std::thread::sleep(Duration::from_millis(100));
let started = std::time::Instant::now();
drop(mgr);
let elapsed = started.elapsed();
// The abandoned read is still in open. A writer lets that thread exit
// so this process does not stay up after the assertion.
let _ = std::fs::OpenOptions::new().write(true).open(&path);
let _ = std::fs::remove_file(&path);
// O_NONBLOCK: a write open returns ENXIO when no reader is waiting
// instead of blocking until one appears.
unblock_fifo_writer(&path);
assert!(
elapsed < Duration::from_secs(2),
"drop blocked for {elapsed:?} while a fifo read was open"
);
}

#[cfg(unix)]
#[test]
fn fifo_at_the_cap_does_not_read_one_more_byte() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("exact.fifo");
let made = std::process::Command::new("mkfifo")
.arg(&path)
.status()
.expect("mkfifo");
assert!(made.success(), "mkfifo");
let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
let path_for_writer = path.clone();
let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
let writer = std::thread::spawn(move || {
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.write(true)
.open(&path_for_writer)
.expect("fifo writer");
let chunk = vec![0u8; 1024 * 1024];
let mut left = cap;
while left > 0 {
let n = std::cmp::min(left, chunk.len() as u64) as usize;
if file.write_all(&chunk[..n]).is_err() {
return;
}
left -= n as u64;
}
let _ = stop_rx.recv();
});
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
let path_str = path.to_string_lossy().into_owned();
let started = std::time::Instant::now();
let msg = runtime.block_on(crate::texture::read_capped_image(&path_str));
let elapsed = started.elapsed();
let _ = stop_tx.send(());
let _ = writer.join();
match msg {
Err(error) => assert!(error.contains(&cap.to_string()), "{error}"),
Ok(bytes) => panic!("read {} bytes and waited for more", bytes.len()),
}
assert!(
elapsed < Duration::from_secs(30),
"read blocked past the cap for {elapsed:?}"
);
}

#[cfg(unix)]
fn unblock_fifo_writer(path: &std::path::Path) {
use std::os::unix::fs::OpenOptionsExt;
// Linux and Android use 0x800. The other Unix targets use 0x4.
#[cfg(any(target_os = "linux", target_os = "android"))]
const O_NONBLOCK: i32 = 0x800;
#[cfg(not(any(target_os = "linux", target_os = "android")))]
const O_NONBLOCK: i32 = 0x4;
let _ = std::fs::OpenOptions::new()
.write(true)
.custom_flags(O_NONBLOCK)
.open(path);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ domain: rendering
lifecycle_status: active
integration_status: wired
owns: [astraweave-materials, astraweave-render]
doc_version: "1.46"
last_verified_commit: 596eed69
doc_version: "1.47"
last_verified_commit: 2ce0da5d
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
---

# Architecture Trace: Render Pipeline + Material System + Shader Infrastructure
Expand All @@ -20,12 +20,14 @@ last_verified_commit: 596eed69
|---|---|
| **System name** | Render Pipeline + Material System + Shader Infrastructure |
| **Primary crates** | `astraweave-render` (123 Rust files / ~78K LoC + 71 WGSL files), `astraweave-materials` (single-file material-graph crate), `tools/aw_editor/src/viewport/` (editor-side renderer + engine adapter) |
| **Document version** | 1.46 |
| **Last verified against commit** | `596eed69` (v1.46: streamed images use `decode_limited_image` and a 64 MiB read cap; decode shutdown is bounded). Prior `f56b2fa4` (v1.45: the forward `HizPyramid` is gated on `sample_hiz`; `NaniteCullingPipeline` keeps a separate pyramid). Prior `09d49dfe` (v1.41: flat sample on the shard 13 and 14 targets that hit 600s). Prior `0758171bf` (lifecycle RSS); prior `154d723aa` (v1.19, 2026-08-02: L.3.C-resolution — 4-cascade CSM + `FarCascadePolicy` + fit-derived bias cap; trace updated in the same commit as the code, so this names its parent); prior `d4c4479d4` (v1.12, 2026-07-25: T.2d.F tier retirement — see revision notice); prior `8232b150b` (v1.10, 2026-07-21: E3 terrain render-path additions verified first-hand — see revision notice); prior `7c29b8182` (v1.8 verification pass: §2.6 Water surface render path re-verified end-to-end against `water.rs` / `water.wgsl` / `renderer.rs` — every file:line citation confirmed, zero corrections, no markers needed; v1.7 added the subsection + cross-link to `docs/architecture/water.md`); prior: `67c9de7e1` (full trace); water rows W.2a + W.2b.2 + W.2c.2 weave-deformation + W.2c.3 weave producer (2026-06-22) + F.4.2 weave-impact accent machinery + F.4.3 live HDR-overlay composite & combined-frame measurement (2026-06-24) |
| **Document version** | 1.47 |
| **Last verified against commit** | `2ce0da5d` (v1.47: `load_texture_async` uses the same 64 MiB cap; a non-regular file is not probed past the cap). Prior `596eed69` (v1.46: streamed images use `decode_limited_image` and a 64 MiB read cap; decode shutdown is bounded). Prior `f56b2fa4` (v1.45: the forward `HizPyramid` is gated on `sample_hiz`; `NaniteCullingPipeline` keeps a separate pyramid). Prior `09d49dfe` (v1.41: flat sample on the shard 13 and 14 targets that hit 600s). Prior `0758171bf` (lifecycle RSS); prior `154d723aa` (v1.19, 2026-08-02: L.3.C-resolution — 4-cascade CSM + `FarCascadePolicy` + fit-derived bias cap; trace updated in the same commit as the code, so this names its parent); prior `d4c4479d4` (v1.12, 2026-07-25: T.2d.F tier retirement — see revision notice); prior `8232b150b` (v1.10, 2026-07-21: E3 terrain render-path additions verified first-hand — see revision notice); prior `7c29b8182` (v1.8 verification pass: §2.6 Water surface render path re-verified end-to-end against `water.rs` / `water.wgsl` / `renderer.rs` — every file:line citation confirmed, zero corrections, no markers needed; v1.7 added the subsection + cross-link to `docs/architecture/water.md`); prior: `67c9de7e1` (full trace); water rows W.2a + W.2b.2 + W.2c.2 weave-deformation + W.2c.3 weave producer (2026-06-22) + F.4.2 weave-impact accent machinery + F.4.3 live HDR-overlay composite & combined-frame measurement (2026-06-24) |
| **Last verified date** | 2026-08-02 (L.3.C-resolution: 4-cascade CSM, far-cascade refresh policy, fit-derived receiver-bias cap, invariant 20 (e)-(i)); 2026-07-21 (E3 terrain render-path, T.0 trace-sync); 2026-06-25 (§2.6 water render-path verification pass); 2026-06-24 (water render-path subsection authored); 2026-05-10 (full trace) |
| **Status** | **ACTIVE WORKZONE** — Editor Multi-Tool Architecture Campaign Sub-phase 3 (Mediator Brush) is in flight as of campaign-doc commit `e3d07f366` (2026-05-08, Round-8-Closure). Fix 27 Unified Pipeline Campaign is structurally complete (per CLAUDE.md) but deeper editor↔runtime unification continues. Treat this trace as a **navigational map**; per-subsystem detailed traces are follow-up work. |
| **Owner notes** | This trace covers an unusually large system (~78K LoC source + 71 WGSL files + editor viewport). Per the template's "One last thing" rule on scale, this doc is intentionally structured as a **subsystem map + load-bearing-aggregator detail**, not an exhaustive per-file trace. Sub-systems like Lumen GI, MegaLights, Nanite, Atmosphere, GPU Particles, Volumetric Fog, IBL, and TAA each warrant their own dedicated trace if and when they enter focused work. The doc covers terrain materials by reference to `docs/architecture/terrain_materials.md`. |

> **Revision notice — 2026-10-21 (v1.47).** `Texture::load_texture_async` and `decode_texture` share `read_capped_image`. A regular file over 64 MiB is rejected from its length. A fifo that delivers exactly the cap is rejected without a further read. `drop_returns_while_a_fifo_read_is_blocked` is `#[cfg(unix)]`, uses a temp directory, and opens the cleanup writer with `O_NONBLOCK`. The 1660 Ti `hiz` 0.275 ms figure is that capture; the default frame does not record Hi-Z unless `sample_hiz` is set. `last_verified_commit` is `2ce0da5d`.
>
> **Revision notice — 2026-10-21 (v1.46).** `decode_texture` reads at most `MAX_IMAGE_ALLOC` (64 MiB) and decodes with `decode_limited_image` (4096-pixel edge). A longer file is rejected from its length before the read. `DecodeRuntime` calls `shutdown_timeout` (500 ms) so a blocked `std::fs::read` does not hold `Drop`. `stream_fallback` releases its fifo writer on any exit, including a failing alloc assert. `last_verified_commit` is `596eed69`.
>
> **Revision notice — 2026-10-21 (v1.45).** Invariant 21 names the Nanite pyramid in `nanite_gpu_culling.rs` (`src/shaders/nanite_hiz_pyramid.wgsl`). `draw_into` does not record it, and its copy from the previous depth is still a placeholder. §11 no longer says occlusion reads `HizPyramid`. The shader headers on `hiz_pyramid.wgsl` and `hiz_pyramid_copy.wgsl` match the gate. `last_verified_commit` is `f56b2fa4`. `render-device-validation.yml` runs `tests/stream_fallback.rs` on lavapipe. The decode runtime polls on its thread, so that test's reader can open the fifo.
Expand Down Expand Up @@ -662,7 +664,7 @@ This map enumerates the load-bearing files. Per-file traces of every subsystem a
| `astraweave-render/src/subgroup_ops.rs` | Subgroup-optimized shader variants (auto-exposure, prefix sum, bitonic sort) | Active | `SubgroupCapabilities` |
| `astraweave-render/src/asset_index.rs` | `AssetIndex`, `MaterialSetEntry`, `TextureEntry`, `HdriRef as AssetHdriRef` | Active | |
| `astraweave-render/src/residency.rs` | GPU residency manager (`ResidencyManager`) | Active | Streaming-aware texture/mesh lifetime |
| `astraweave-render/src/texture_streaming.rs` | LRU-cache + priority-based texture streaming (`TextureStreamingManager`, `TextureStreamingStats`) | Active | `Renderer` owns it. `new` returns `Result` if the one-thread tokio runtime cannot start. `tick` uploads from a pre-sized ring. `request_at` sorts by camera distance. Reads stop at 64 MiB and decode through `decode_limited_image`. Shutdown waits at most 500 ms |
| `astraweave-render/src/texture_streaming.rs` | LRU-cache + priority-based texture streaming (`TextureStreamingManager`, `TextureStreamingStats`) | Active | `Renderer` owns it. `new` returns `Result` if the one-thread tokio runtime cannot start. `tick` uploads from a pre-sized ring. `request_at` sorts by camera distance. `read_capped_image` caps `decode_texture` and `Texture::load_texture_async` at 64 MiB. A non-regular file is not read past that cap. Decode uses `decode_limited_image`. Shutdown waits at most 500 ms |
| `astraweave-render/src/virtual_texture.rs` | Sparse virtual texturing (page cache, feedback, LRU) | Active | |
| `astraweave-render/src/texture.rs`, `types.rs` | Core texture / vertex / instance types | Active | `Instance`, `Material`, `Mesh`, `SkinnedVertex`, `Vertex` (re-exported at `lib.rs:147`) |
| `astraweave-render/src/camera.rs` | `Camera`, `CameraController` | Active | |
Expand Down
Loading
Loading