# Pipeline and producers This document follows data from a GPU-emitted request to a resident cache page, and describes the producer interface. It also marks which producer code is durable and which is throwaway. > **Temporary code:** `crates/vxls/src/main.rs` and `crates/vxls/src/producers.rs` are a playground/test > harness built alongside the cache. They contain hardcoded parameters and > blocking workarounds. Do not treat them as stable architecture, public API, or > examples of intended concurrency. The `ChunkedProducer` shape and the > insertion/data-flow contract are the durable parts; the concrete generators > (including `SdfGenerator` and `TerrainGenerator`) are throwaway fixtures and > should be replaced. --- ## 1. End-to-end sequence ```mermaid sequenceDiagram participant R as Render pass (GPU) participant C as Voxel cache (GPU) participant T as Structure table (GPU) participant H as Host (main.rs) participant I as Insertion passes (GPU) R->>C: descend pages, mark usage, increment missing-child counters R->>T: trace chunk cells, increment missing-root counters Note over C,T: end of draw C->>C: top-K + gather + descending radix sort T->>T: top-K + gather + descending radix sort C-->>H: request buffer (anchor, node_id, child, producer, demand) T-->>H: table request buffer (anchor, slot, 0, producer, demand) H->>H: queue + produce one node per request (parallel, possibly across frames) H->>I: upload CacheInsertionData (info, location, parent, attributes, count) I->>C: validate/compact, recycle pages, write pages, invalidate stale pointers I->>C: write new child pointers I->>T: validate/point table slots at new root pages Note over R: next frame sees the new pages ``` Timing detail: in the current driver the render pass runs **before** request gathering and insertion in the same `render()` call. Therefore pages produced in response to frame N are first visible in frame N+1. --- ## 2. The request/response contract ### 2.1 Request ```rust struct RequestInformation { node_id: u32, // locator of the *parent* node children_index: u32, // which child is missing producer_id: u32, // owner of the parent node demand: u32, // request counter for this slot this frame anchor: StructureAnchor, // opaque, table-defined content identity } struct RequestMeta { page_index: u32, // parent page (internal) or 0xFFFFFFFF (external) children_index: u32, depth: u32, // parent depth table_slot: u32, // external root placement, NO_TABLE_SLOT internally } ``` - The producer receives both `RequestInformation` and `RequestMeta`, so it can build the insertion's `InsertionParent` without referring back to a request buffer. - For external requests from a structure table: `RequestMeta.page_index = 0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, `anchor` is the table-defined content identity, and `RequestMeta.table_slot` is the current placement. - The root/child distinction must use `RequestMeta.page_index == 0xFFFFFFFF`, **not** `node_id == 0`: child 0 of the root also has `node_id = 0`. - Requests are sorted by demand (highest counter first) and capped at `max_requests`. - `producer_id` and `demand` are on the wire so the host queue can deduplicate and prioritise without guessing. - `anchor` and `table_slot` are two different things: - `StructureAnchor` is the table-defined content identity and the structure identity (for the toroidal table, world position plus a version word); - `table_slot` is table-private placement and may change while the anchor stays the same. It is deliberately not part of a request key. `node_id` and `producer_id` are `StructureLocator` and `ProducerId` on the Rust side (transparent over `u32`); the layout above is the GPU wire layout. ### 2.2 Response One `CacheInsertionData` entry per produced node. Entries do **not** have to be in request order, because each one carries its own attachment point: ```rust struct InsertionInformation { children: [ChildInformation; 64], // bit 31 subdividable, bit 30 occupied } struct LocationPage { node_id: u32, // locator of the node itself producer_id: u32, anchor: StructureAnchor, } struct InsertionParent { kind: u32, // 0 = child of a resident page, 1 = external root page_index: u32, // parent page, or 0xFFFFFFFF for an external root children_index: u32, depth: u32, // parent depth, or 0xFFFFFFFF node_id: u32, // parent locator (0 for an external root) producer_id: u32, anchor: StructureAnchor, table_slot: u32, // external root placement, NO_TABLE_SLOT internally } ``` Plus one attribute payload per entry (color and normal in the demo). Before allocating pages, the cache validates every entry against the current parent: - internal: the parent page must still have the same producer, locator, **and anchor**, and the child slot must still be `subdividable, unavailable`; - external: the named table slot must still carry the same anchor, and its pointer must still be `subdividable, unavailable`. Valid entries are compacted into `valid_indices`/`valid_count`; only those consume eviction pages. The cache fills `destination_indices[i]` with the page that received entry `i`, or `0xFFFFFFFF` if it was rejected (invalid, out of capacity, or too recently used). A real producer should read it and retry the request if needed. ### 2.3 Ordering and staleness There is no longer an ordering requirement between requests and insertion entries. `write_pointers.wgsl` and `fixed_table/insertion.wgsl` use the batch's `InsertionParent`, and re-check parent identity before linking. This is what makes asynchronous, cross-frame production safe: a page produced for a parent that has since been evicted or reused is dropped at insertion time instead of corrupting the tree. --- ## 3. The durable producer shape The durable interface is `vxls-production::Producer`, and the demo driver uses it through `TreeProducer` in `crates/vxls/src/producers.rs`: ```rust pub trait Producer where [(); N * N * N]:, { fn produce( &self, anchor: StructureAnchor, locator: StructureLocator, ) -> ProducedNode; } pub struct ProducedNode where [(); N * N * N]:, { pub insertion: InsertionInformation, pub attributes: [A; N * N * N], } ``` `locator` is the content-local path of the node to produce, obtained from the request with `RequestKey::node_locator::()`. The producer does not need to know whether the request was a structure root or an internal child: the locator already names the node, and the cache derives the matching `LocationPage` from the same key. The cache owns identity, so `ProducedNode` deliberately carries no producer id, anchor, table slot, or location. The host/queue adds those when it builds an `InsertionEntry`. The older `ChunkedProducer` / `ProducedChunk` shape in `crates/vxls/src/producers.rs` is retained only for the unused terrain/ball fixtures. It is not the interface new producers should implement. Interpretation: - A leaf is `subdividable = false`. A node that should be refined later is `subdividable = true`. Occupancy controls hit testing and coarse skipping. - The producer fills one entry per child of the requested node, plus the attributes for those children. - `anchor` is the content identity. A producer must derive world position from it and never from a table slot. ### 3.1 Fulfilling a request `TreeProducer` (`crates/vxls/src/producers.rs`) does: 1. Decode `locator` with `TreeLocator::::from`. 2. If the node is not subdivided, emit a constant page: every child has the node's attribute and `ChildInformation::new(false, occupied)`. 3. Otherwise iterate `locator.children()` and emit each child's `ChildInformation` and `VoxelAttributes`. 4. Return a `ProducedNode`; no location or parent is produced here. The request path is: 1. `RequestQueue` yields a `WorkItem` with a `RequestKey`. 2. The worker calls `producer.produce(key.anchor, key.node_locator::<4>())`. 3. On drain, `ReadyItem::insertion_entry()` combines the payload with `ReadyItem::insertion_parent()` and `ReadyItem::location_page()`. 4. `CacheInsertionData::upload` writes the batch. ### 3.2 Locators `TreeLocator` (`crates/vxls-production/src/tree_locator.rs`) is the locator used by the request queue and the demo producer. Three base-N accumulators (`x`, `y`, `z`) with a leading `1` digit; root is `(1,1,1)`; `depth = ilog_N(x)`; `parent` divides each coordinate by `N`; `child` multiplies by `N` and adds the child digit. `StructureLocator` is a flat interleaved form. `NTree` in `crates/vxls/src/sparse_tree.rs` is keyed by the same locator, so a `RequestKey` can name a produced node directly. Locators must round-trip through the 32-bit `node_id`. --- ## 4. The current driver, step by step Relevant code: `State::render` and `TreeProducer` in `crates/vxls/src/main.rs` / `crates/vxls/src/producers.rs`. 1. **Render** writes G-buffers and request counters. 2. **Gather** encodes both request pipelines (cache + table) into the same command buffer, then submits and presents. 3. **Download** starts three asynchronous reads per request buffer (count, informations, meta). Each callback only ingests the wire requests into the shared `RequestQueue`; it does not drain or upload. 4. **Busy-wait**: ```rust loop { if finished.load(Relaxed) >= 2 { break; } let _ = self.device.poll(wgpu::wgt::PollType::Poll); } ``` `finished` counts completed callbacks (one cache, one table), so completion does not require all six reads to land independently. Each callback increments it only after ingesting. 5. **Drain** the queue once both downloads have landed: ```rust let children = queue.drain_ready_matching( frame_id, cache_insertion.capacity(), |key| !key.is_root()); let roots = queue.drain_ready_matching( frame_id, structure_table_insertion.capacity(), |key| key.is_root()); ``` `frame_id` is a host-owned monotonic counter, not the cache timestamp word. 6. **Produce** on the worker thread with rayon, one `Producer::produce` call per `WorkItem`. Each result is a `ProducedNode` keyed by `RequestKey::node_locator::()`. On drain, `ReadyItem::insertion_entry()` attaches the parent and location, and `CacheInsertionData::upload` writes the whole batch (structure, location, parent, attributes, `valid_count`, `page_count`). `destination_indices` is reset by the validation shaders, not by the host. 7. **Insert** encodes: ```rust cache.insert(&device, &mut encoder, &mut [ &mut VoxelCacheInsertion::ExternalRequest( &structure_table_cache_insertion, &mut *structure_table), &mut VoxelCacheInsertion::InternalRequest(&cache_insertion), ]); structure_table.insert(&device, &mut encoder, &structure_table_cache_insertion); ``` Validation and compaction run first for both batches, then one eviction preparation is shared by both page allocations. It orders pages by timestamp first (least recently used first) and depth second (deepest first among equal timestamps). 8. **Submit** and read back the insertion profile. Because the external insertion is processed first, newly produced chunk roots are resident before the internal child insertion links them. The table insertion then points the slot at the root page. ### 4.1 Problems this creates - The render thread blocks waiting for downloads before it can drain results, so production does not overlap with rendering. - Request buffers are read back every frame even when empty. - `finished >= 2` is a coarse synchronization; it assumes exactly two buffers and no retries. - The worker thread is spawned from the playground, so scheduling and producer ownership are not reusable outside `main.rs`. - No backpressure or prioritisation beyond the top-K request cap. - Rejected insertions (`destination_indices == 0xFFFFFFFF`) are still not reported back to the producer. These are acceptable for a playground and are the first things to redesign for a real engine. --- ## 5. Generators in `crates/vxls/src/producers.rs` All are fixtures. They exist to exercise the cache and should not be treated as stable. | Generator | Status | What it does | |---|---|---| | `TreeProducer` | Used by the demo | Implements the durable `vxls_production::Producer` over an in-memory `NTree`; the request's `node_locator` selects the node. | | `SdfGenerator` | Fixture, unused | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. | | `TerrainGenerator` | Fixture, unused | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. | | `BallGenerator` | Fixture, unused | Implements the local playground `producers::Producer` trait, not the durable one. | `TerrainGenerator` is the closest thing to a realistic producer, but it is single-threaded at load time and uses hardcoded mip factors (8×). It also has branching logic based on `depth <= 2`. `SdfGenerator` demonstrates the attribute math: - `alpha = 0` above the surface, `1` below; - `subdivided = depth < chunk_power - 1` near the surface; - normal from four SDF samples; - color derived from the normal with a small random tint. --- ## 6. The production subsystem `crates/vxls-production/src/lib.rs` and its children are compiled, and the demo driver now uses its durable `Producer` / `ProducedNode` / `RequestQueue` types. The `main.rs` producer remains a playground fixture, but it implements the durable interface. ### 6.1 `crates/vxls-production/src/lib.rs` Defines the producer-facing attribute vocabulary and the production interface. The attribute traits and layouts live in `vxls-attributes` and are re-exported here: ```rust // Identity types live in vxls-voxel-cache::schema and are re-exported here. pub use vxls_attributes::{Attribute, AttributeDescriptor, Attributes, AttributesLayout}; pub use vxls_voxel_cache::schema::{ProducerId, StructureAnchor, StructureLocator}; pub trait Attributes: Attribute { const LAYOUT: AttributesLayout; fn get_attr(&self, index: usize) -> &[u8]; fn get_attr_mut(&mut self, index: usize) -> &mut [u8]; } pub trait Producer { fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode; } pub struct ProducedNode { pub insertion: InsertionInformation, pub attributes: [A; N * N * N], } ``` The cache-facing side is: ```rust let layout = CacheLayout::from_attributes(&A::LAYOUT, &[]); let insertion = CacheInsertionData::new(&device, max_entries, &layout); let entries: Vec> = ...; insertion.upload(&queue, &entries, &voxels)?; ``` Differences from the legacy `ChunkedProducer` fixture interface: - Attributes are abstracted behind `Attributes`, avoiding hardcoded color/normal buffers. - The producer receives a `StructureLocator` rather than depth + coordinates, pushing locator arithmetic into the producer. - `ProducedNode` carries no identity: the request key supplies producer, anchor, parent, and `LocationPage` when the entry is staged. - `anchor` is the content identity. A producer must derive world position from it and never from a table slot. ### 6.1.1 Identity model | Concept | Meaning | |---|---| | `ProducerId` | Which producer fulfils the request. | | `StructureAnchor` | Opaque, table-defined content identity and the only structure identity. Two live slots must never share one anchor. | | `TableSlot` | Table-private placement. Recycled freely and never part of tree identity. | Root identity is `(producer, anchor)`; child identity adds the parent locator and child index. The table slot travels only as attachment metadata. The toroidal table keeps an anchor's identity while it stays in view and retires anchors that leave. An anchor must keep naming the same content if it later re-enters; bump its version word when content generation changes for the same coordinates. ### 6.2 Host production helper (not present) There is no `crates/vxls-production/src/host_production.rs` in this tree. The worker thread and `RequestQueue` in `crates/vxls/src/main.rs` are the current host-side implementation. ### 6.3 `crates/vxls-production/src/tree_locator.rs` `TreeLocator` (described in §3.2) plus `From` / `Into` conversions. ### 6.4 `crates/vxls-production/src/request_queue.rs` A bounded, deduplicating, priority-ordered request queue. It is the durable answer to "the cache re-emits the same request every frame". Key model: ```rust RequestKey { producer_id, anchor, // table-defined content identity target: Root | Child { parent: StructureLocator, children_index }, } ``` `Root` vs `Child` is explicit, so `(node_id = 0, children_index = 0)` (external root and child 0 of the root) do not collide. Properties: - `ingest(frame, requests)` refreshes duplicates in place and drops requests unseen for more than `stale_after` frames. - Priority is `(root before child, higher demand, shallower depth)`, with `first_seen` as a tie-breaker so old requests do not starve. - Separate bounds `max_queued`, `max_in_flight`, and `max_ready`. Dispatch preserves `ready.len() + in_flight <= max_ready`, so backpressure is visible before workers run. - New requests only evict queued jobs when strictly more urgent; otherwise they are dropped and re-emitted next frame. - Each job has a generation and attempt count. Completions from evicted, expired, retried, or invalidated jobs are discarded. - `table_slot` lives in `RequestMeta` as attachment metadata, not part of the key. Because the whole `RequestMeta` is refreshed on every re-emission, including while a job is in flight or ready, a produced root can follow its anchor to a new slot. - `invalidate_producer(id)` and `invalidate_anchor(anchor)` remove matching queued/in-flight/ready jobs. Invalidation is a cancellation/cleanup hint, **not** a correctness mechanism: the GPU rejects stale insertions by checking the current anchor/slot. - `RequestKey::node_locator::()` derives the locator of the requested node (root or child) from the key, so producers and `LocationPage` agree. - `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion batch from the key and the latest `RequestMeta` (which carries `table_slot`). - `ReadyItem::location_page::()` builds the `LocationPage` from the key, not from the producer payload or the table slot. - `ReadyItem::insertion_entry()` combines the payload's `InsertionInformation` with those two into a cache-facing `InsertionEntry`. The queue is unit-tested without a GPU (`cargo test -p vxls-production request_queue`). ### 6.5 `crates/vxls/src/sparse_tree.rs` A CPU `NTree` prototype backed by a `HashMap, NTreeNode>`, with `constant`, `get`, `set`, array conversion, and explicit-structure export. It also provides the packed `Color` helper and PLY loading. Useful for understanding the tree and used by the playground producers, not by the renderer. ### 6.6 `crates/vxls/src/gi_pipeline.rs` + `sparse_set.rs` Compiles (declared in `main.rs`) but `VoxelGiPipeline` is never instantiated. It adds `DontTouch` attributes for a leaf list and radiance, and a `GpuSparseSet` for resident leaves. It is a sketch of a future GI integration, not working code. --- ## 7. Adding a producer Minimum viable path with the current demo interface: 1. Implement the durable `vxls_production::Producer`: ```rust impl Producer<4, MyAttributes> for MyProducer { fn produce( &self, anchor: StructureAnchor, locator: StructureLocator, ) -> ProducedNode<4, MyAttributes> { ... } } ``` 2. Decode `locator` with `TreeLocator::::from` if the producer needs node coordinates. 3. For each child of the requested node, compute: - `subdividable`: can this child be refined? - `occupied`: can it produce a hit? - attribute words in the cache layout order. 4. Return a `ProducedNode` with `InsertionInformation` and the attribute array. Do not emit a `LocationPage` or `InsertionParent`; those are derived from the `RequestKey` when the result is drained. 5. Replace `TreeProducer` in `crates/vxls/src/main.rs` with the new producer. 6. Keep `CacheInsertionData::new` capacity at least as large as the maximum number of entries the queue can drain in one frame. A production-ready producer should additionally: - use the `Attributes` abstraction so attributes are not hardcoded; - run through `RequestQueue` on a worker thread and stream results across frames without blocking the render loop; - handle `destination_indices == 0xFFFFFFFF` by retrying the request; - implement filtering/mip generation for coarser levels so LOD stops do not alias; - support multiple structures/producers per cache via `ProducerId` and anchors. --- ## 8. Known issues | Symptom | Location | Impact | Confidence | |---|---|---|---| | The host request path busy-waits on `device.poll`; production blocks the render thread. | `crates/vxls/src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High | | The demo driver is still synchronous: it downloads, produces, and inserts in one frame. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The queue is on the live path but the scheduler is still frame-blocking. | High | | If `destination_indices[i] == 0xFFFFFFFF`, the producer is not told; the cache will re-request the node later. | `insertion.wgsl`, host callback | Wasted work and repeated requests; no metric for dropped pages. | High | | The external table insertion consumes the same eviction list as the cache insertion; if it inserts fewer roots than requested, the table has missing entries with no host-visible signal. | `VoxelCache::insert`, `fixed_table/insertion.wgsl` | Silent holes in the world. | Medium | | `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `crates/vxls/src/producers.rs` | Not robust to different chunk resolutions. | High | | `BallGenerator` implements the local playground `producers::Producer` trait, not the durable `vxls_production::Producer`. | `crates/vxls/src/producers.rs` | Copying it as a template will not work with the current driver. | High | | The worker thread is owned by `main.rs` rather than `vxls-production`, so queue scheduling and producers are not reusable yet. | `crates/vxls/src/main.rs` | Durable producer types exist, but the host service around them does not. | Medium |