Starting decoupling requests

This commit is contained in:
2026-11-08 21:25:40 +01:00
parent 82c952c6d8
commit d44da4520c
23 changed files with 2386 additions and 306 deletions
+130 -58
View File
@@ -29,13 +29,13 @@ sequenceDiagram
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 (structure_id, node_id, child)
T-->>H: table request buffer (slot, 0, 0)
H->>H: produce one node per request (parallel)
H->>I: upload CacheInsertionData (info, locations, attributes, count)
I->>C: recycle pages, write pages, invalidate stale pointers
C-->>H: request buffer (structure_id, node_id, child, producer, demand)
T-->>H: table request buffer (slot, 0, 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: point table slots at new root pages
I->>T: validate/point table slots at new root pages
Note over R: next frame sees the new pages
```
@@ -54,25 +54,34 @@ struct RequestInformation {
structure_id: u32, // which structure (chunk/table slot)
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
}
struct RequestMeta {
page_index: u32, // parent page (internal) or sentinel (external)
page_index: u32, // parent page (internal) or 0xFFFFFFFF (external)
children_index: u32,
depth: u32,
depth: u32, // parent depth
}
```
- The producer only sees `RequestInformation`. `RequestMeta` stays on the GPU
and is used by `write_pointers` / table insertion.
- For external requests from a structure table: `node_id = 0`,
`children_index = 0`, and `structure_id` is the table slot.
- 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`, and `structure_id` is the
table slot.
- 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.
### 2.2 Response
One `CacheInsertionData` entry per request, in the **same order**:
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<N> {
@@ -81,28 +90,44 @@ struct InsertionInformation<N> {
struct LocationPage {
structure_id: u32,
node_id: u32,
node_id: u32, // locator of the node itself
producer_id: u32,
}
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
structure_id: u32,
node_id: u32, // parent locator (0 for an external root)
producer_id: u32,
}
```
Plus one attribute payload per page (color and normal in the demo).
Plus one attribute payload per entry (color and normal in the demo).
The cache fills `destination_indices[i]` with the page that received slot `i`,
or `0xFFFFFFFF` if it could not insert. The producer does not need to read it in
the current demo, but a real implementation should, because the cache can silently
drop pages when it is full or when candidate pages were used in the previous
frame.
Before allocating pages, the cache validates every entry against the current
parent:
### 2.3 Why order matters
- internal: the parent page must still have the same identity and the child slot
must still be `subdividable, unavailable`;
- external: the table slot must still be `subdividable, unavailable`.
`write_pointers.wgsl` and `fixed_table/insertion.wgsl` assume:
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.
```text
request_informations[i] <-> insertion_data[i] <-> destination_indices[i]
```
### 2.3 Ordering and staleness
If a producer reorders, filters, or duplicates requests, pages will be linked to
the wrong parents. There is no validation.
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.
---
@@ -156,15 +181,20 @@ The demo's `fullfill_request` (`src/main.rs`) does:
1. Map `structure_id` to an absolute chunk coordinate using
`ToroidalStructureTable::get_request_position`.
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
3. If `node_id == 0`, produce the chunk root at depth 0 and emit the root
locator.
4. Otherwise:
3. If `request_meta.page_index == 0xFFFFFFFF` (an external table request),
produce the chunk root at depth 0, emit the root locator, and emit
`InsertionParent::external(structure_id, producer_id)`.
4. Otherwise (an internal child request):
- decode the parent `NTreeNodeLocator<4>` from `node_id`;
- decode `children_index` into `(child_x, child_y, child_z)` with x fastest;
- compute the child locator;
- produce the child node at `parent_depth + 1` with the child's node
coordinates;
- emit the child locator as the new `LocationPage.node_id`.
- emit the child locator as the new `LocationPage.node_id`;
- emit `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
of the root also has `node_id = 0`.
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
chunk dimensions of 20×20×20 and a 4-ary tree.
@@ -195,8 +225,8 @@ Relevant code: `State::render` and `fullfill_request` in `src/main.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 two asynchronous reads per request buffer (count and
informations).
3. **Download** starts three asynchronous reads per request buffer (count,
informations, meta).
4. **Busy-wait**:
```rust
@@ -207,14 +237,17 @@ Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
```
`finished` counts completed callbacks (one cache, one table), so completion
does not require all four reads to land independently.
5. **Produce** on the CPU with rayon: one `fullfill_request` per request. The
results are copied into dense vectors, then uploaded with
`queue.write_buffer` into:
does not require all six reads to land independently.
5. **Produce** on the CPU with rayon: one `fullfill_request` per
`(RequestInformation, RequestMeta)` pair. The results are copied into dense
vectors, then uploaded with `queue.write_buffer` into:
- `insertion_information_buffer()`
- `location_pages_buffer()`
- `insertion_parents_buffer()`
- `attributes_buffers()[0]` (color)
- `attributes_buffers()[1]` (normal)
- `destination_indices_buffer()` (pre-filled with `0xFFFFFFFF`)
- `valid_count_buffer()` (`0`)
- `page_count_buffer()`
6. **Insert** encodes:
@@ -222,16 +255,16 @@ Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
cache.insert(&device, &mut encoder, &mut [
&mut VoxelCacheInsertion::ExternalRequest(
&structure_table_cache_insertion, &mut *structure_table),
&mut VoxelCacheInsertion::InternalRequest(
&cache_insertion, &request_buffer),
&mut VoxelCacheInsertion::InternalRequest(&cache_insertion),
]);
structure_table.insert(&device, &mut encoder,
&structure_table_cache_insertion, &structure_table_request_buffer);
&structure_table_cache_insertion);
```
One eviction preparation is shared by both batches. It orders pages by
timestamp first (least recently used first) and depth second (deepest first
among equal timestamps).
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).
7. **Submit** and read back the insertion profile.
Because the external insertion is processed first, newly produced chunk roots
@@ -278,11 +311,11 @@ branching logic based on `depth <= 2`.
---
## 6. The unwired production subsystem
## 6. The production subsystem
These files are **not declared as modules in `main.rs`**, so they are not part of
the running binary. They represent earlier or planned designs. Treat them as
reference material, not current architecture.
`src/production.rs` and its children are compiled (`mod production;`), but the
demo driver in `main.rs` still uses its synchronous `fullfill_request` path. The
production types are the durable contract; the driver is still the playground.
### 6.1 `src/production.rs`
@@ -331,7 +364,41 @@ callback. `produce_requests` does the real parallel mapping.
### 6.4 `src/production/request_queue.rs`
Untracked WIP. Do not depend on it.
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,
structure_id,
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.
- `invalidate_structure(id)` and `invalidate_producer(id)` remove all matching
queued/in-flight/ready jobs. Use the former for toroidal slot reuse.
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
batch from the latest `RequestMeta`.
The queue is unit-tested without a GPU (`cargo test production::request_queue`).
### 6.5 `src/host_production.rs`
@@ -379,21 +446,25 @@ Minimum viable path with the current demo interface:
- attribute words in the cache layout order.
3. Wire the producer into `fullfill_request` (or replace that function).
Request → coordinates:
- external: `node_id == 0`, produce chunk root;
- external (`RequestMeta.page_index == 0xFFFFFFFF`), produce chunk root;
- internal: decode `node_id`, decode `children_index`, produce child at
`depth + 1`.
4. Emit a `LocationPage` matching the produced node. For internal requests,
it must be `parent.child(child_x, child_y, child_z)`.
5. Ensure the output order matches the request order and the batch size matches
`page_count_buffer`.
6. Update the size passed to `CacheInsertionData::new` if the maximum batch can
5. Emit an `InsertionParent`:
- external: `InsertionParent::external(structure_id, producer_id)`;
- internal: `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
6. Set `page_count_buffer` to the number of entries. Order does not matter, but
every entry must have matching information, location, parent, and attributes.
7. Update the size passed to `CacheInsertionData::new` if the maximum batch can
exceed `max_requests`.
A production-ready producer should additionally:
- use the unwired `VoxelProducer`/`VoxelAttributes` abstraction (or an
equivalent) so attributes are not hardcoded;
- run on a worker thread and stream results without blocking the render loop;
- use the `VoxelProducer`/`VoxelAttributes` abstraction (or an equivalent) 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;
@@ -406,13 +477,14 @@ A production-ready producer should additionally:
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High |
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `src/main.rs:1762-1838` | Not generic; offsets only make sense for the demo terrain. | High |
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `src/main.rs:1814-1905` | Not generic; offsets only make sense for the demo terrain. | High |
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. The queue exists but `main.rs` does not schedule through it yet. | `src/main.rs` (`render`), `src/production/request_queue.rs` | No overlap between production and rendering in the demo. The durable contract is ready for an async scheduler. | High |
| `page_count_buffer` is set to `request_informations.len()`, which may exceed `CacheInsertionData`'s `max_page_count` (1024) if `max_requests` is raised without resizing. | `src/main.rs` (write of `page_count_buffer`), `CacheInsertionData::new` | Buffer overrun / truncated production. | 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. | `src/producers.rs:207-263,330` | Not robust to different chunk resolutions. | High |
| `BallGenerator` implements the old `Producer` trait, not `ChunkedProducer`. | `src/producers.rs:31-116` | Copying it as a template will not work with the current driver. | High |
| The `production/` subsystem is not compiled into the binary but looks authoritative. | `src/production.rs`, `src/production/*` | Agents may "fix" dead code or assume it is live. | High |
| `src/production/request_queue.rs` is untracked WIP. | same | Brittle; may change or disappear. | High |
| The `production/` subsystem is compiled but not used by the demo driver. | `src/production.rs`, `src/production/*` | Agents may assume the queue is on the live path; it is the durable target, while `fullfill_request` is still the active playground path. | High |
| `src/production/request_queue.rs` is new. | same | Its API may still change; `main.rs` does not depend on it yet. | Medium |
| The demo uploads all attribute payloads with `bytemuck::cast_slice` of Rust arrays, so layout mismatches (padding, alignment) are not checked. | `src/main.rs` upload section | Silent corruption if the Rust struct layout diverges from the WGSL/Slang layout. | Medium |
| The `+5000` offset plus `chunk_y.abs()` means negative chunk coordinates fold onto positive ones. | `src/main.rs:1785-1789` | Duplicate chunks / visual artifacts at negative y. | Medium |
+8 -5
View File
@@ -397,8 +397,9 @@ Structure-table shaders use a simpler concatenation:
`common.wgsl` + pass file.
`common.wgsl` starts with `enable wgpu_binding_array;` and defines the shared
`CacheIndex`, `RequestInformation`, `RequestMeta`, `AttributeArray`,
`LocationPage`, and child-pointer helpers so the Rust and WGSL sides share names.
`CacheIndex`, `RequestInformation`, `RequestMeta`, `InsertionParent`,
`AttributeArray`, `LocationPage`, and child-pointer helpers so the Rust and WGSL
sides share names.
### 9.2 WGSL modules and entry points
@@ -407,11 +408,12 @@ Structure-table shaders use a simpler concatenation:
| `shaders/requests.wgsl` | `reset_requests` | Zero all per-child request counters. |
| `shaders/gather_requests.wgsl` | `gather_requests` | Copy selected top-K counts/indices into radix key/value buffers. |
| `shaders/write_requests.wgsl` | `write_requests` | Convert sorted flat indices into `RequestInformation`/`RequestMeta`. |
| `shaders/insertion.wgsl` | `insertion`, `consume` | Recycle pages, write pointer/location/depth/attributes, advance consumed count. |
| `shaders/insertion.wgsl` | `validate_internal`, `insertion`, `consume` | Validate/compact internal entries, recycle pages, write pointer/location/depth/attributes, advance consumed count. |
| `shaders/invalidation.wgsl` | `invalidation` | Clear cache pointers that reference pages recycled this insert. |
| `shaders/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages. |
| `shaders/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages using the batch's `InsertionParent`. |
| `shaders/eviction.wgsl` | `reset_lru_list`, `indirect_copy` | Build the eviction candidate list: descending depth sort, then gather timestamps for the stable timestamp sort. |
| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots. |
| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose slot still waits for a page. |
| `fixed_table/insertion.wgsl` | `insertion` | Point table slots at inserted root pages. |
| `fixed_table/invalidation.wgsl` | `invalidation` | Clear table slots pointing at recycled pages. |
| `terrain/shaders/toroidal_structure.wgsl` | `invalidate_new` | Reset table slots whose world position changed. |
@@ -425,7 +427,8 @@ Cache shaders consistently bind:
- group 0 — cache structure (pointer, location, depth pages), except
`insertion.wgsl` where group 0 is attributes and group 1 is structure;
- group 1 — request handler, evictor, or request buffer depending on the pass;
- group 1 — request handler, evictor, insertion data, or request buffer
depending on the pass;
- group 2 — request buffer, insertion data, or scratch buffer;
- group 3 — evictor or insertion data;
- group 4 — inserted-count atomic.
+129 -46
View File
@@ -26,9 +26,8 @@ entry points into the cache.
Key invariants:
1. `page_index` must fit in 30 bits (`CachePointer` stores it in bits 0..29).
2. Request index `i` and insertion slot `i` are **one-to-one**. The producer
fills `CacheInsertionData` in the same order as the request buffer, and
`write_pointers.wgsl` relies on that.
2. An insertion is identified by its own `InsertionParent`, not by its position
in a request buffer. Request order and insertion order may differ.
3. Slang consumers assume a child count of 64 and the demo attribute order.
Changing the cache layout requires editing the Slang shaders.
4. A page's `LocationPage` must describe the node the page represents, not its
@@ -232,8 +231,8 @@ count** (2 in the demo). This naming collision is a common source of confusion.
```rust
pub enum VoxelCacheInsertion<'a, const N: usize> {
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
```
@@ -249,27 +248,43 @@ preparation pass and one timestamp.
`CacheInvalidable` is implemented by the structure tables:
```rust
pub trait CacheInvalidable {
pub trait CacheInvalidable<const N: usize> {
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
```
`validate_insertion` runs before page allocation: the table checks that each
external root's slot is still `subdividable, unavailable` and compacts the valid
entries. This prevents a stale root response from consuming a page, and lets a
slot be reused (toroidal move) without accepting a response for its old world
position.
### 4.3 Insertion data
`CacheInsertionData::new(device, max_page_count, layout)` allocates:
| Buffer | Contents |
|---|---|
| `page_count` | number of pages in this batch |
| `insertion_information` | dense `InsertionInformation<N>` per page |
| `location_pages` | dense `LocationPage` per page |
| `destination_indices` | filled by the cache: destination page or `0xFFFFFFFF` |
| attribute buffers | dense per-page attribute payloads |
| `page_count` | number of entries in this batch |
| `insertion_information` | dense `InsertionInformation<N>` per entry |
| `location_pages` | dense `LocationPage` per entry (includes `producer_id`) |
| `insertion_parents` | dense `InsertionParent` per entry |
| `destination_indices` | reset to `0xFFFFFFFF` by the validation pass; the insertion pass writes the destination page for accepted entries |
| `valid_indices` | filled by the validation pass: compacted indices of valid entries |
| `valid_count` | host writes `0`; the validation pass fills the amount of valid entries |
| attribute buffers | dense per-entry attribute payloads |
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
`ChildInformation` uses the four-state encoding below.
@@ -279,6 +294,25 @@ bit 31 = subdividable
bit 30 = occupied
```
`InsertionParent` makes the batch self-describing. It is what replaces the
former request-buffer lookup:
```rust
struct InsertionParent {
kind: u32, // 0 = internal child, 1 = external root
page_index: u32, // parent cache page, or 0xFFFFFFFF for an external root
children_index: u32, // child slot in the parent
depth: u32, // parent depth, or 0xFFFFFFFF for an external root
structure_id: u32, // structure the parent belongs to
node_id: u32, // locator of the parent (0 for an external root)
producer_id: u32, // producer that owns the parent
}
```
A batch no longer has to be ordered like the request buffer. The host may
reorder, filter, or produce entries on different frames; the GPU validates each
entry independently.
The insertion shader converts child information into a `PointerPage`:
- every child pointer starts as `empty(subdividable)`;
@@ -286,8 +320,8 @@ The insertion shader converts child information into a `PointerPage`:
- attributes are copied for `External` attributes only.
`destination_indices` is an output used by `write_pointers` and by the structure
table insertion pass. `0xFFFFFFFF` means "not inserted" (out of capacity or too
recently used).
table insertion pass. `0xFFFFFFFF` means "not inserted" (out of capacity, too
recently used, or invalid).
---
@@ -339,6 +373,8 @@ struct RequestInformation {
structure_id: u32, // from LocationPage
node_id: u32, // from LocationPage (the parent node)
children_index: u32, // requested child
producer_id: u32, // from LocationPage
demand: u32, // request counter for this slot this frame
}
struct RequestMeta {
@@ -348,6 +384,15 @@ struct RequestMeta {
}
```
`producer_id` lets a cache mix several producers and lets the host queue route
requests without guessing. `demand` is the raw request counter; the queue uses it
as the primary priority key.
The external-root marker is `RequestMeta.page_index == 0xFFFFFFFF`, **not**
`node_id == 0`. Both an external root and child 0 of the root carry
`node_id = 0, children_index = 0`, so a queue keyed on those fields alone would
collapse them.
5. **Reset** (`requests.wgsl`): zeroes all request counters for the next frame.
`request_count` is copied from `top_k.selected_count` and then clamped in
@@ -355,10 +400,10 @@ struct RequestMeta {
### 5.3 Host download
`CacheRequestBuffer::host_download_requests(device, queue, callback)` uses two
`DownloadBuffer::read_buffer` calls (count + informations). A small
`RequestMapState` waits for both and invokes the callback with
`&request_informations[0..count]`.
`CacheRequestBuffer::host_download_requests(device, queue, callback)` uses three
`DownloadBuffer::read_buffer` calls (count + informations + meta). A small
`RequestMapState` waits for all three and invokes the callback with
`&request_informations[0..count]` and `&request_meta[0..count]`.
The callback is asynchronous by API, but the demo blocks on it with a
`device.poll` loop. See [`pipeline-and-producers.md`](./pipeline-and-producers.md).
@@ -371,13 +416,19 @@ For an **internal** request:
- `children_index` identifies which child is missing.
- The producer must generate that child node and emit a `LocationPage` for the
child (typically `parent_locator.child(x, y, z)`).
- The output order must match the request order.
- It must also emit an internal `InsertionParent` carrying the parent page,
child index, depth, and parent identity.
For an **external** (structure-table) request:
- `structure_id` is the table slot.
- `node_id` and `children_index` are 0.
- The producer must generate a chunk root and emit its `LocationPage`.
- `node_id` and `children_index` are 0, and `RequestMeta.page_index` is
`0xFFFFFFFF`.
- The producer must generate a chunk root and emit its `LocationPage` plus an
external `InsertionParent`.
There is no output-order requirement. Each insertion is attached to its parent
by its own `InsertionParent`.
---
@@ -387,11 +438,12 @@ For an **external** (structure-table) request:
```mermaid
flowchart TD
A[prepare eviction list] --> B[insertion pass<br/>one per insertion]
B --> C[external invalidation]
C --> D[cache invalidation]
D --> E[write pointers<br/>internal insertions only]
E --> F[frame_timestamp += 1]
A[prepare eviction list] --> B[validate + compact<br/>one per insertion]
B --> C[insertion pass<br/>one per insertion]
C --> D[external invalidation]
D --> E[cache invalidation]
E --> F[write pointers<br/>internal insertions only]
F --> G[frame_timestamp += 1]
```
### 6.1 Eviction preparation
@@ -410,14 +462,28 @@ flowchart TD
The resulting order is **timestamp-major, depth-minor**: least recently used
first, with deeper pages first among equal timestamps. See §7.
### 6.2 Insertion
### 6.2 Validation and insertion
For each insertion, `CacheInsertionPass::encode`:
Before any page is allocated, each batch is validated:
- **Internal** (`insertion.wgsl`, `validate_internal`): the parent page must
still have the same `structure_id`, `node_id`, `producer_id`, and depth, and
the requested child pointer must still be `subdividable, unavailable`.
- **External** (`fixed_table/validate_insertion.wgsl`): the table slot must still
be `subdividable, unavailable`.
Valid entries are compacted into `valid_indices` and counted in `valid_count`.
The validation pass resets every `destination_indices` entry to `0xFFFFFFFF`,
so invalid entries never get a page even if the host reuses an insertion buffer.
For each insertion, `CacheInsertionPass::encode` then:
1. Dispatches `insertion` indirectly from `page_count`.
2. Computes `available_amount = min(page_count_free - consumed, batch_size)`.
3. For slot `i`:
- if `i >= available_amount`, mark `destination_indices[i] = 0xFFFFFFFF`;
2. Reads `valid_count` and computes
`available_amount = min(page_count_free - consumed, valid_count)`.
3. For compacted slot `i`:
- if `i >= available_amount`, leave `destination_indices[entry]` at
`0xFFFFFFFF` (already reset by validation);
- pick `page_index = lru_list[i + consumed_count]`;
- if `timestamp_pages[page_index] >= new_timestamp - 1`, do not insert
(protects pages touched in the previous frame). **Note:** on the very
@@ -448,16 +514,25 @@ be requested later.
### 6.5 Write pointers
For each internal insertion, `write_pointers.wgsl`:
For each internal insertion, `write_pointers.wgsl` reads the batch's own
`InsertionParent` (there is no request buffer):
```wgsl
structure_pointer_pages[meta.page_index].pointers[meta.children_index]
= child_pointer_make_available(destination_index);
structure_depth_pages[destination_index] = meta.depth + 1;
let parent = insertion_data_parents[index];
if(parent.kind == INSERTION_PARENT_INTERNAL &&
insertion_data_destination_indices[index] != 0xFFFFFFFF &&
parent.page_index != insertion_data_destination_indices[index] &&
location_pages[parent.page_index] still has parent's identity)
{
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(destination_index);
structure_depth_pages[destination_index] = parent.depth + 1;
}
```
This is the step that actually links the new pages into the tree. It relies on
request index == insertion index.
This is the step that actually links the new pages into the tree. The identity
re-check catches the case where the parent page itself was recycled by the same
insertion batch.
### 6.6 Timestamp advance
@@ -515,10 +590,14 @@ root page? Structure tables answer that and emit requests when it is missing.
- `raytrace_bind_group`: bindings `[pointers, request_counts]` (group 1 in the
render pipeline).
- `gather_requests`: top-K + sort + `fixed_table/write_requests.wgsl`; emits
`structure_id = slot`, `node_id = 0`, `children_index = 0`.
- `insert`: `fixed_table/insertion.wgsl` reads
`request_informations[i].structure_id` and sets
`pointers[slot] = available(destination_indices[i])`.
`structure_id = slot`, `node_id = 0`, `children_index = 0`,
`producer_id = table producer`, `demand = slot counter`, and
`RequestMeta.page_index = 0xFFFFFFFF`.
- `validate_insertion`: `fixed_table/validate_insertion.wgsl` keeps only slots
that are still `subdividable, unavailable` and compacts their indices.
- `insert`: `fixed_table/insertion.wgsl` reads each entry's `InsertionParent`
and sets `pointers[slot] = available(destination_indices[i])` for external
roots whose slot is still waiting.
- `invalidate`: clears slots pointing at pages recycled this insert.
The table is dense: allocation is `slot_count * 4` bytes for pointers plus
@@ -534,6 +613,10 @@ The table is dense: allocation is `slot_count * 4` bytes for pointers plus
- `move_position` computes a new integer offset around the camera and runs
`terrain/shaders/toroidal_structure.wgsl`: any slot whose world position
changed is reset to `subdividable, unavailable`, so it will be re-requested.
It also returns the list of changed slot ids on the CPU. The host must feed
that list to the request queue (`invalidate_structure`) before batching
insertions, otherwise a response produced for the slot's old position could
be accepted after the toroidal move.
- `get_request_position(structure_id)` maps a slot back to an absolute chunk
coordinate using the current offset and `rem_euclid`.
- Everything else delegates to the fixed table.
@@ -575,7 +658,7 @@ Used by write-requests, insertion, invalidation, and write-pointers passes.
| `WriteRequestsPass` | structure | request handler (count + sorted) | request buffer | — | — |
| `CacheInsertionPass` | cache attributes | structure | insertion data | evictor | inserted count |
| `CacheInvalidationPass` | structure | evictor | — | — | — |
| `WritePointersPass` | structure | request buffer | insertion data | — | — |
| `WritePointersPass` | structure | insertion data | — | — | — |
| Eviction reset / indirect copy | evictor | structure | scratch | — | — |
---
@@ -618,9 +701,9 @@ Memory example at 150k pages and 2 attributes is tabulated in
| `CacheStructure::new` allocates `location_pages` with `size_of::<StructurePage<N>>()` instead of `size_of::<LocationPage>()`. | `src/voxel_cache/structure.rs:44` | At N=4, 264 B/page instead of 8 B/page: ~39.6 MB instead of ~1.2 MB for 150k pages. No correctness issue because shaders index by `LocationPage` stride. | High |
| `StructurePage` (Rust, `u64` mask) and `PointerPage` (WGSL, two `u32`) are duplicated layout definitions. | `src/voxel_cache/schema.rs:89-100`, `src/voxel_cache/shaders/cache_common.wgsl:3-8` | Little-endian compatible today; any field reorder breaks silently. `StructurePage` is only used for sizing. | High |
| `request_buffer_count` is written by every invocation of `write_requests.wgsl` with the same value. | `src/voxel_cache/shaders/write_requests.wgsl:50` | Benign data race (identical writes), but unnecessary and confusing. | Medium |
| Insertion relies on request index == insertion index; nothing validates the contract. | `write_pointers.wgsl`, `CacheInsertionData` construction | Silent wrong pointers if a producer reorders or drops requests. | High |
| `CacheInsertionPass` can silently insert fewer pages than requested (`0xFFFFFFFF` slots) with no host feedback. | `src/voxel_cache/shaders/insertion.wgsl:59-75` | Producer believes data is resident; requests may repeat or data may be missing. | High |
| The first `VoxelCache::insert` call inserts nothing: `new_timestamp = 1`, unused pages have timestamp 0, and the guard rejects `0 >= new_timestamp - 1` (`0 >= 0`). | `src/voxel_cache.rs:237`, `src/voxel_cache/shaders/insertion.wgsl:70-75` | One-frame startup delay; any external roots submitted in the first batch are dropped and must be re-requested. | High |
| Insertion order no longer matters: each entry is validated against its `InsertionParent` and linked statelessly. | `insertion.wgsl`, `write_pointers.wgsl`, `fixed_table/insertion.wgsl` | A producer may reorder or filter results; unchanged request order is no longer a correctness requirement. | High |
| `CacheInsertionPass` can silently insert fewer pages than requested (`0xFFFFFFFF` destinations) with no host feedback. | `src/voxel_cache/shaders/insertion.wgsl` | Producer believes data is resident; requests may repeat or data may be missing. | High |
| The first `VoxelCache::insert` call inserts nothing: `new_timestamp = 1`, unused pages have timestamp 0, and the guard rejects `0 >= new_timestamp - 1` (`0 >= 0`). | `src/voxel_cache.rs:248`, `src/voxel_cache/shaders/insertion.wgsl:141-146` | One-frame startup delay; any external roots submitted in the first batch are dropped and must be re-requested. | High |
| Pointer/page-count limits are implicit (`< 2^30`, total elements `< 2^32`). | `schema.rs`, `requests.rs:82-85` | Large configurations fail via asserts or truncation. | High |
| `CacheAttributeInit::DontTouch` attributes can become stale after a page is recycled; the cache deliberately does not clear them. | `src/voxel_cache/shaders/insertion.wgsl:94-110` | Any consumer of such an attribute must tolerate garbage for recycled pages. | Medium |
| The cache exposes `usage_timestamps()` for debugging only; timestamps are also used internally for invalidation and eviction. | `src/voxel_cache.rs:410-414` | Easy to corrupt cache behaviour by writing to that buffer. | Medium |
| `CacheAttributeInit::DontTouch` attributes can become stale after a page is recycled; the cache deliberately does not clear them. | `src/voxel_cache/shaders/insertion.wgsl:164-178` | Any consumer of such an attribute must tolerate garbage for recycled pages. | Medium |
| The cache exposes `usage_timestamps()` for debugging only; timestamps are also used internally for invalidation and eviction. | `src/voxel_cache.rs:445-449` | Easy to corrupt cache behaviour by writing to that buffer. | Medium |