hn.today

Testing WebGPU data layouts with Facet

mattkeeter.com82 points6 comments
Screenshot of Testing WebGPU data layouts with Facet

This describes a practical solution for detecting subtle data-layout mismatches between Rust host structs and WGSL shader structs used with WebGPU compute shaders. A common pattern is to write configuration structs directly into GPU buffers via zerocopy, but layout rules differ: WGSL pads each row of a mat3x3 to 16 bytes (48 bytes total) while a tightly packed Rust 3x3 f32 array is 36 bytes, which can cause hard-to-debug GPU hangs. An initial approach used naga to parse WGSL and hand-checked member offsets against Rust's std::mem::offset_of!, which successfully found a mismatch but was awkward and produced poor diagnostics.

The solution implemented is a generic unit-test checker that leverages facet for runtime reflection of Rust types together with naga for WGSL introspection. The checker parses the shader, locates the named struct, asserts overall size (handling possible trailing runtime-sized arrays), iterates facet-provided fields to compare offsets and sizes against naga's type sizes, and ensures every WGSL member exists in Rust. Facet is derived only in tests via cfg_attr(test), so these validations add no runtime overhead. The result is automated, clearer error reporting for layout mismatches and a repeatable test harness applied across multiple shader configs (merge, shade, ssao, blur).

Read on mattkeeter.com6 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Security

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.