diff --git a/.gitignore b/.gitignore index 616c574..85dd96a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,9 @@ /target Cargo.lock +.codegraph/ +.mcp.json +opencode.jsonc +.claude/ imgs.tar.gz diff --git a/AGENTS.md b/AGENTS.md index d8cd352..0ba80f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,3 +148,14 @@ The full tables live in the docs. The most important ones: `src/voxel_cache/*`, `src/gpu/*`, or `shaders/*`, not in `main.rs`. - **Document discrepancies as observations.** If code and comments disagree, state what the code does, what the comment claims, and your confidence. + + +## CodeGraph + +In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code: + +- **MCP tool** (when available): `codegraph_explore` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them, including dynamic-dispatch hops grep can't follow. Name a file or symbol in the query to read its current line-numbered source. If it's listed but deferred, load it by name via tool search. +- **Shell** (always works): `codegraph explore ""` prints the same output. + +If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision. + diff --git a/docs/pipeline-and-producers.md b/docs/pipeline-and-producers.md index ef89ce2..7157df5 100644 --- a/docs/pipeline-and-producers.md +++ b/docs/pipeline-and-producers.md @@ -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 { @@ -81,28 +90,44 @@ struct InsertionInformation { 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 | diff --git a/docs/shaders.md b/docs/shaders.md index 827a538..45e3dd8 100644 --- a/docs/shaders.md +++ b/docs/shaders.md @@ -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. diff --git a/docs/voxel-cache.md b/docs/voxel-cache.md index 433456e..f971c95 100644 --- a/docs/voxel-cache.md +++ b/docs/voxel-cache.md @@ -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, &'a mut dyn CacheInvalidable), - InternalRequest(&'a CacheInsertionData, &'a CacheRequestBuffer), + ExternalRequest(&'a CacheInsertionData, &'a mut dyn CacheInvalidable), + InternalRequest(&'a CacheInsertionData), } ``` @@ -249,27 +248,43 @@ preparation pass and one timestamp. `CacheInvalidable` is implemented by the structure tables: ```rust -pub trait CacheInvalidable { +pub trait CacheInvalidable { fn invalidate( &mut self, encoder: &mut ScopeEncoder, cache_evictor: &CacheEvictor, invalid_timestamp: u32, ); + + fn validate_insertion( + &mut self, + device: &Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ); } ``` +`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` 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` 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` 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
one per insertion] - B --> C[external invalidation] - C --> D[cache invalidation] - D --> E[write pointers
internal insertions only] - E --> F[frame_timestamp += 1] + A[prepare eviction list] --> B[validate + compact
one per insertion] + B --> C[insertion pass
one per insertion] + C --> D[external invalidation] + D --> E[cache invalidation] + E --> F[write pointers
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::>()` instead of `size_of::()`. | `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 | diff --git a/src/main.rs b/src/main.rs index 0078c24..cf8029d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ use glam::Mat4; use glam::Vec3; use glam::Vec4; use itertools::Itertools; +use rayon::iter::IndexedParallelIterator; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; use wgpu::BindGroupLayout; @@ -65,8 +66,11 @@ use crate::voxel_cache::VoxelCacheInsertion; use crate::voxel_cache::insertion::CacheInsertionData; use crate::voxel_cache::requests::CacheRequestBuffer; use crate::voxel_cache::schema::InsertionInformation; +use crate::voxel_cache::schema::InsertionParent; use crate::voxel_cache::schema::LocationPage; +use crate::voxel_cache::schema::NO_PARENT_PAGE; use crate::voxel_cache::schema::RequestInformation; +use crate::voxel_cache::schema::RequestMeta; use crate::voxel_cache::tables::FixedStructureTable; mod camera; @@ -75,6 +79,7 @@ mod gi_pipeline; mod gpu; pub mod gpu_profiler; mod producers; +mod production; mod sparse_tree; mod terrain; mod voxel_cache; @@ -407,6 +412,7 @@ impl State (terrain_width, terrain_alt, terrain_height), Vec3::ZERO, structure_table_request_buffer.max_requests, + 0, ); let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout); let chunk_instances = (0..terrain_alt) @@ -1292,7 +1298,7 @@ impl State self.request_buffer.host_download_requests( &self.device, &self.queue, - move |request_informations| { + move |request_informations, request_metas| { let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed); if !done { @@ -1310,26 +1316,32 @@ impl State let mut color_attributes = vec![]; let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![]; let mut location_pages = vec![]; + let mut insertion_parents = vec![]; request_informations .par_iter() - .map(|request| { + .zip(request_metas.par_iter()) + .map(|(request, meta)| { fullfill_request( cloned_generator.as_ref(), request, + meta, cloned_map.as_ref(), &cloned_table_1, ) }) .collect::>() .into_iter() - .for_each(|(colors, normals, insertion_info, location)| { + .for_each(|(colors, normals, insertion_info, location, parent)| { insertion_infos.push(insertion_info); color_attributes.push(colors); normal_attributes.push(std::array::from_fn(|i| normals[i].into())); location_pages.push(location); + insertion_parents.push(parent); }); + let request_count = request_informations.len() as u32; + cloned_queue.write_buffer( cloned_insertion_data.insertion_information_buffer(), 0, @@ -1342,6 +1354,12 @@ impl State bytemuck::cast_slice(&location_pages), ); + cloned_queue.write_buffer( + cloned_insertion_data.insertion_parents_buffer(), + 0, + bytemuck::cast_slice(&insertion_parents), + ); + cloned_queue.write_buffer( &cloned_insertion_data.attributes_buffers()[0], 0, @@ -1354,10 +1372,22 @@ impl State bytemuck::cast_slice(&normal_attributes), ); + cloned_queue.write_buffer( + cloned_insertion_data.destination_indices_buffer(), + 0, + bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]), + ); + + cloned_queue.write_buffer( + cloned_insertion_data.valid_count_buffer(), + 0, + bytemuck::bytes_of(&0u32), + ); + cloned_queue.write_buffer( cloned_insertion_data.page_count_buffer(), 0, - bytemuck::bytes_of(&(request_informations.len() as u32)), + bytemuck::bytes_of(&request_count), ); }, ); @@ -1375,7 +1405,7 @@ impl State self.structure_table_request_buffer.host_download_requests( &self.device, &self.queue, - move |request_informations| { + move |request_informations, request_metas| { let done = structure_table_request_buffer_done_1 .load(std::sync::atomic::Ordering::Relaxed); if !done @@ -1395,26 +1425,32 @@ impl State let mut color_attributes = vec![]; let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![]; let mut location_pages = vec![]; + let mut insertion_parents = vec![]; request_informations .par_iter() - .map(|request| { + .zip(request_metas.par_iter()) + .map(|(request, meta)| { fullfill_request( cloned_generator.as_ref(), request, + meta, cloned_map.as_ref(), &cloned_table_2, ) }) .collect::>() .into_iter() - .for_each(|(colors, normals, insertion_info, location)| { + .for_each(|(colors, normals, insertion_info, location, parent)| { insertion_infos.push(insertion_info); color_attributes.push(colors); normal_attributes.push(std::array::from_fn(|i| normals[i].into())); location_pages.push(location); + insertion_parents.push(parent); }); + let request_count = request_informations.len() as u32; + cloned_queue.write_buffer( cloned_st_insertion_data.insertion_information_buffer(), 0, @@ -1427,6 +1463,12 @@ impl State bytemuck::cast_slice(&location_pages), ); + cloned_queue.write_buffer( + cloned_st_insertion_data.insertion_parents_buffer(), + 0, + bytemuck::cast_slice(&insertion_parents), + ); + cloned_queue.write_buffer( &cloned_st_insertion_data.attributes_buffers()[0], 0, @@ -1439,10 +1481,22 @@ impl State bytemuck::cast_slice(&normal_attributes), ); + cloned_queue.write_buffer( + cloned_st_insertion_data.destination_indices_buffer(), + 0, + bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]), + ); + + cloned_queue.write_buffer( + cloned_st_insertion_data.valid_count_buffer(), + 0, + bytemuck::bytes_of(&0u32), + ); + cloned_queue.write_buffer( cloned_st_insertion_data.page_count_buffer(), 0, - bytemuck::bytes_of(&(request_informations.len() as u32)), + bytemuck::bytes_of(&request_count), ); }, ); @@ -1614,7 +1668,6 @@ impl State ), &mut VoxelCacheInsertion::InternalRequest( &self.cache_insertion, - &self.request_buffer, ), ], ); @@ -1623,7 +1676,6 @@ impl State &self.device, &mut scoped_encoder, &self.structure_table_cache_insertion, - &self.structure_table_request_buffer, ); } @@ -1762,6 +1814,7 @@ pub struct ChunkImmediate fn fullfill_request( generator: &dyn ChunkedProducer, request: &RequestInformation, + meta: &RequestMeta, map: &HashMap, table: &Arc>, ) -> ( @@ -1769,6 +1822,7 @@ fn fullfill_request( [[f32; 3]; N * N * N], InsertionInformation, LocationPage, + InsertionParent, ) where [(); N * N * N]:, @@ -1795,14 +1849,19 @@ where let location; let node; - if request.node_id == 0 + let parent; + if meta.page_index == NO_PARENT_PAGE { - // Produce root node + // Produce root node. An external (structure-table) request is the only + // one without a parent page; `node_id == 0` also happens for child 0 of + // the root, so it cannot be used to detect roots. node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z)); location = LocationPage { structure_id: request.structure_id, node_id: NTreeNodeLocator::<4>::root().as_usize() as u32, + producer_id: request.producer_id, }; + parent = InsertionParent::external(request.structure_id, request.producer_id); } else { @@ -1824,7 +1883,14 @@ where location = LocationPage { structure_id: request.structure_id, node_id: child_locator.as_usize() as u32, + producer_id: request.producer_id, }; + parent = InsertionParent::internal( + meta, + request.structure_id, + request.node_id, + request.producer_id, + ); } ( @@ -1834,5 +1900,6 @@ where children: node.children, }, location, + parent, ) } diff --git a/src/production.rs b/src/production.rs index 9e08eea..c5b52e9 100644 --- a/src/production.rs +++ b/src/production.rs @@ -9,11 +9,14 @@ pub mod tree_locator; /// Facilities for voxel production on the host (CPU) side pub mod host_production; +/// Bounded, deduplicating, priority-ordered cache request queue +pub mod request_queue; + /// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`] /// A cache might hold data owned by multiple different producers. To discriminate where to route the /// request, a node is always tagged by a [`ProducerId`]. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)] #[repr(transparent)] pub struct ProducerId(pub u32); @@ -21,13 +24,13 @@ pub struct ProducerId(pub u32); /// As such a producer can tag, to its discretion, its own structure with an Id. /// /// All node of a same tree thus share the same structure Id -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)] #[repr(transparent)] pub struct StructureId(pub u32); /// A request can come from anywhere inside the structure. The producer can thus tag each node with /// a locator, to know where the request was issued. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)] #[repr(transparent)] pub struct StructureLocator(pub u32); diff --git a/src/production/host_production.rs b/src/production/host_production.rs index 9c9345e..1cbef71 100644 --- a/src/production/host_production.rs +++ b/src/production/host_production.rs @@ -39,7 +39,7 @@ where insertion: &CacheInsertionData, ) { - request_buffer.host_download_requests(device, queue, |requests| {}); + request_buffer.host_download_requests(device, queue, |_requests, _metas| {}); } pub fn produce_requests( diff --git a/src/production/request_queue.rs b/src/production/request_queue.rs index a694ec9..f84cede 100644 --- a/src/production/request_queue.rs +++ b/src/production/request_queue.rs @@ -1,21 +1,190 @@ -use std::collections::BTreeMap; +use std::cmp::Ordering; use std::collections::BTreeSet; use std::collections::HashMap; use crate::production::ProducerId; use crate::production::StructureId; use crate::production::StructureLocator; +use crate::voxel_cache::schema::InsertionParent; +use crate::voxel_cache::schema::NO_PARENT_PAGE; use crate::voxel_cache::schema::RequestInformation; +use crate::voxel_cache::schema::RequestMeta; -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] -pub struct RequestKey +/// Monotonic frame counter owned by the host. Using `u64` avoids concerns about +/// the cache's `u32` timestamp wrapping. +pub type FrameId = u64; + +/// The target of a request. +/// +/// An external root request and an internal request for child 0 of the root +/// both carry `(node_id = 0, children_index = 0)` on the wire, so the key must +/// distinguish them explicitly. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub enum RequestTarget { - producer_id: ProducerId, - structure_id: StructureId, - structure_locator: StructureLocator, - children_index: u32, + /// Request for the root node of a structure (structure-table request). + Root, + + /// Request for a child of a resident node. + Child + { + parent: StructureLocator, + children_index: u32, + }, } +/// Unique identity of an outstanding request. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub struct RequestKey +{ + pub producer_id: ProducerId, + pub structure_id: StructureId, + pub target: RequestTarget, +} + +impl RequestKey +{ + pub fn root(producer_id: ProducerId, structure_id: StructureId) -> Self + { + Self { + producer_id, + structure_id, + target: RequestTarget::Root, + } + } + + pub fn child( + producer_id: ProducerId, + structure_id: StructureId, + parent: StructureLocator, + children_index: u32, + ) -> Self + { + Self { + producer_id, + structure_id, + target: RequestTarget::Child { + parent, + children_index, + }, + } + } + + pub fn is_root(&self) -> bool + { + matches!(self.target, RequestTarget::Root) + } +} + +/// Scheduling priority. Higher is more urgent. +/// +/// Ordering is: +/// 1. class (roots before children) +/// 2. demand (higher first) +/// 3. depth (shallower first) +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct RequestPriority +{ + pub class: u8, + pub demand: u32, + pub depth: u32, +} + +impl RequestPriority +{ + pub const ROOT_CLASS: u8 = 1; + pub const CHILD_CLASS: u8 = 0; + + pub fn new(class: u8, demand: u32, depth: u32) -> Self + { + Self { + class, + demand, + depth, + } + } + + pub fn root(demand: u32) -> Self + { + Self::new(Self::ROOT_CLASS, demand, 0) + } + + pub fn child(demand: u32, depth: u32) -> Self + { + Self::new(Self::CHILD_CLASS, demand, depth) + } +} + +impl Ord for RequestPriority +{ + fn cmp(&self, other: &Self) -> Ordering + { + self.class + .cmp(&other.class) + .then_with(|| self.demand.cmp(&other.demand)) + // Shallower nodes are more urgent. + .then_with(|| other.depth.cmp(&self.depth)) + } +} + +impl PartialOrd for RequestPriority +{ + fn partial_cmp(&self, other: &Self) -> Option + { + Some(self.cmp(other)) + } +} + +/// A request as ingested from the host. +#[derive(Clone, Copy, Debug)] +pub struct IncomingRequest +{ + pub key: RequestKey, + pub priority: RequestPriority, + + /// Parent page information captured at the latest emission. + pub meta: RequestMeta, +} + +impl IncomingRequest +{ + /// Builds an incoming request from the wire request/meta pair emitted by the + /// cache. An external root is identified by its missing parent page, not by + /// `node_id == 0` (which also describes child 0 of the root). + pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self + { + let producer_id = ProducerId(request.producer_id); + let structure_id = StructureId(request.structure_id); + + let (key, priority) = if meta.page_index == NO_PARENT_PAGE + { + ( + RequestKey::root(producer_id, structure_id), + RequestPriority::root(request.demand), + ) + } + else + { + ( + RequestKey::child( + producer_id, + structure_id, + StructureLocator(request.node_id), + request.children_index, + ), + RequestPriority::child(request.demand, meta.depth), + ) + }; + + Self { + key, + priority, + meta: *meta, + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum JobState { Queued, @@ -23,66 +192,1160 @@ pub enum JobState Ready, } -pub struct Job +/// A job handed to a worker. +#[derive(Clone, Copy, Debug)] +pub struct WorkItem { - state: JobState, - priority: u32, - emit_timestamp: u32, + pub key: RequestKey, + pub generation: u64, + pub attempt: u32, + pub meta: RequestMeta, } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct RequestPriority +/// A completed job waiting to be inserted. +#[derive(Debug)] +pub struct ReadyItem { - priority: u32, + pub key: RequestKey, + pub meta: RequestMeta, + pub payload: T, +} + +impl ReadyItem +{ + /// Attachment information to carry in the insertion batch so the GPU can + /// validate and link the produced page without the request buffer. + pub fn insertion_parent(&self) -> InsertionParent + { + match self.key.target + { + RequestTarget::Root => + { + InsertionParent::external(self.key.structure_id.0, self.key.producer_id.0) + } + RequestTarget::Child { + parent, + children_index, + } => + { + // The key and the meta should agree; prefer the key so the + // attachment point can never drift from the identity used for + // deduplication. + let meta = RequestMeta { + children_index, + ..self.meta + }; + InsertionParent::internal( + &meta, + self.key.structure_id.0, + parent.0, + self.key.producer_id.0, + ) + } + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum CompleteOutcome +{ + Accepted, + Discarded, +} + +#[derive(Clone, Copy, Debug)] +pub struct QueueConfig +{ + /// Maximum number of undispatched jobs. + pub max_queued: usize, + + /// Maximum number of jobs simultaneously handed to workers. + pub max_in_flight: usize, + + /// Maximum number of produced results waiting for insertion. + /// + /// Dispatch is throttled so that `ready + in_flight <= max_ready`. + pub max_ready: usize, + + /// Number of frames a job may go unseen before it is dropped. + pub stale_after: u64, + + /// Number of worker attempts before a job is dropped. + pub max_attempts: u32, +} + +impl Default for QueueConfig +{ + fn default() -> Self + { + Self { + max_queued: 4096, + max_in_flight: 4, + max_ready: 1024, + stale_after: 8, + max_attempts: 3, + } + } +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct IngestStats +{ + pub new: usize, + pub refreshed: usize, + pub evicted: usize, + pub expired: usize, + pub dropped: usize, +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct QueueStats +{ + pub queued: usize, + pub in_flight: usize, + pub ready: usize, + pub total_ingested: u64, + pub total_evicted: u64, + pub total_expired: u64, + pub total_dropped: u64, + pub total_completed: u64, + pub total_stale_completions: u64, +} + +struct Job +{ + key: RequestKey, + state: JobState, + priority: RequestPriority, + first_seen: FrameId, + last_seen: FrameId, + meta: RequestMeta, + generation: u64, + attempt: u32, + payload: Option, +} + +/// Entry in the queued/ready ordered sets. Larger means more urgent. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct QueueEntry +{ + priority: RequestPriority, + first_seen: FrameId, key: RequestKey, } -pub struct RequestQueue +impl Ord for QueueEntry { - cap: usize, - count: usize, - jobs: HashMap, - priorities: BTreeSet, + fn cmp(&self, other: &Self) -> Ordering + { + self.priority + .cmp(&other.priority) + // Older jobs win ties, limiting starvation. + .then_with(|| other.first_seen.cmp(&self.first_seen)) + .then_with(|| self.key.cmp(&other.key)) + } } -impl RequestQueue +impl PartialOrd for QueueEntry { - pub fn new(cap: usize) -> Self + fn partial_cmp(&self, other: &Self) -> Option + { + Some(self.cmp(other)) + } +} + +fn entry_of(job: &Job) -> QueueEntry +{ + QueueEntry { + priority: job.priority, + first_seen: job.first_seen, + key: job.key, + } +} + +pub struct RequestQueue +{ + config: QueueConfig, + frame: FrameId, + next_generation: u64, + + jobs: HashMap>, + queued: BTreeSet, + ready: BTreeSet, + + in_flight: usize, + stats: QueueStats, +} + +impl RequestQueue +{ + pub fn new(config: QueueConfig) -> Self { Self { - cap, - count: 0, + config, + frame: 0, + next_generation: 0, jobs: HashMap::new(), - priorities: BTreeMap::new(), + queued: BTreeSet::new(), + ready: BTreeSet::new(), + in_flight: 0, + stats: QueueStats::default(), } } - pub fn ingest(&mut self, timestamp: u32, requests: &[RequestInformation]) + pub fn config(&self) -> &QueueConfig { - let mut new_requests = vec![]; + &self.config + } - for (i, request) in requests.iter().enumerate() + pub fn frame(&self) -> FrameId + { + self.frame + } + + /// Ingests all requests emitted for `frame`. + /// + /// Duplicate keys are collapsed. Jobs that have not been seen for more + /// than `config.stale_after` frames are removed afterwards. + pub fn ingest(&mut self, frame: FrameId, requests: I) -> IngestStats + where + I: IntoIterator, + { + debug_assert!(frame >= self.frame, "frame counter must be monotonic"); + self.frame = frame; + + let mut stats = IngestStats::default(); + + for request in requests { - let key = RequestKey { - producer_id: 0u32.into(), // TODO: Support produer ids - structure_id: request.structure_id.into(), - structure_locator: request.node_id.into(), - children_index: request.children_index, + if let Some(job) = self.jobs.get_mut(&request.key) + { + // Refresh an existing job. It may be queued, in flight, or + // ready; in all cases only the scheduling metadata changes. + let old_entry = entry_of(job); + + match job.state + { + JobState::Queued => + { + self.queued.remove(&old_entry); + } + JobState::Ready => + { + self.ready.remove(&old_entry); + } + JobState::InFlight => + {} + } + + job.priority = request.priority; + job.meta = request.meta; + job.last_seen = frame; + + match job.state + { + JobState::Queued => + { + self.queued.insert(entry_of(job)); + } + JobState::Ready => + { + self.ready.insert(entry_of(job)); + } + JobState::InFlight => + {} + } + + stats.refreshed += 1; + continue; + } + + // New request. Enforce the queued bound by evicting the lowest + // priority queued job, but only when the newcomer is strictly more + // urgent. Otherwise the newcomer is dropped; the cache will emit it + // again next frame if it is still needed. + if self.queued.len() >= self.config.max_queued + { + let victim = self.queued.first().copied(); + let should_evict = victim + .map(|victim| victim.priority < request.priority) + .unwrap_or(false); + + if should_evict + { + if let Some(victim) = victim + { + self.remove_job(&victim.key); + stats.evicted += 1; + } + } + else + { + stats.dropped += 1; + continue; + } + } + + let generation = self.next_generation; + self.next_generation = self.next_generation.wrapping_add(1); + + let job = Job { + key: request.key, + state: JobState::Queued, + priority: request.priority, + first_seen: frame, + last_seen: frame, + meta: request.meta, + generation, + attempt: 0, + payload: None, }; - // Check for exitence in the queue - if self.jobs.contains_key(&key) + self.queued.insert(entry_of(&job)); + self.jobs.insert(request.key, job); + stats.new += 1; + } + + self.expire(frame, &mut stats); + + self.stats.total_ingested += (stats.new + stats.refreshed) as u64; + self.stats.total_evicted += stats.evicted as u64; + self.stats.total_expired += stats.expired as u64; + self.stats.total_dropped += stats.dropped as u64; + + stats + } + + /// Takes the most urgent queued job and marks it in flight. + pub fn pop(&mut self) -> Option + { + if self.in_flight >= self.config.max_in_flight + { + return None; + } + + // Reserve room for every in-flight result to become ready. + if self.ready.len() + self.in_flight >= self.config.max_ready + { + return None; + } + + let entry = self.queued.pop_last()?; + let job = self + .jobs + .get_mut(&entry.key) + .expect("queued entry without job"); + + debug_assert_eq!(job.state, JobState::Queued); + + job.state = JobState::InFlight; + job.attempt = job.attempt.wrapping_add(1); + self.in_flight += 1; + + Some(WorkItem { + key: job.key, + generation: job.generation, + attempt: job.attempt, + meta: job.meta, + }) + } + + /// Accepts a worker result. + /// + /// Results for evicted, expired, or retried jobs are discarded. + pub fn complete(&mut self, item: WorkItem, payload: T) -> CompleteOutcome + { + let Some(job) = self.jobs.get_mut(&item.key) + else + { + self.stats.total_stale_completions += 1; + return CompleteOutcome::Discarded; + }; + + if job.state != JobState::InFlight + || job.generation != item.generation + || job.attempt != item.attempt + { + self.stats.total_stale_completions += 1; + return CompleteOutcome::Discarded; + } + + self.in_flight = self.in_flight.saturating_sub(1); + job.state = JobState::Ready; + job.payload = Some(payload); + self.ready.insert(entry_of(job)); + self.stats.total_completed += 1; + + CompleteOutcome::Accepted + } + + /// Reports a failed worker attempt. The job is retried until + /// `config.max_attempts` is reached, then dropped. + pub fn fail(&mut self, item: WorkItem) + { + let Some(job) = self.jobs.get(&item.key) + else + { + self.stats.total_stale_completions += 1; + return; + }; + + if job.state != JobState::InFlight + || job.generation != item.generation + || job.attempt != item.attempt + { + self.stats.total_stale_completions += 1; + return; + } + + let attempt = job.attempt; + + self.in_flight = self.in_flight.saturating_sub(1); + + if attempt >= self.config.max_attempts + { + self.jobs.remove(&item.key); + self.stats.total_dropped += 1; + return; + } + + // Requeue. Make room by evicting the lowest priority queued job if + // necessary; the failed job is already admitted, so it is not dropped + // just because the queued bound was reached while it was in flight. + if self.queued.len() >= self.config.max_queued + { + if let Some(victim) = self.queued.first().copied() { - // Update priority - self.priorities.remove(&key); + self.remove_job(&victim.key); + self.stats.total_evicted += 1; } - else + } + + let job = self + .jobs + .get_mut(&item.key) + .expect("failed job disappeared while requeueing"); + job.state = JobState::Queued; + job.payload = None; + self.queued.insert(entry_of(job)); + } + + /// Drains ready jobs that were seen in `frame` and satisfy `keep`. + /// + /// Results are returned highest priority first. Jobs that are not drained + /// stay in the ready set until they are drained or become stale. + pub fn drain_ready_matching( + &mut self, + frame: FrameId, + max: usize, + mut keep: F, + ) -> Vec> + where + F: FnMut(&RequestKey) -> bool, + { + if max == 0 + { + return Vec::new(); + } + + let candidates: Vec = self.ready.iter().rev().copied().collect(); + let mut result = Vec::new(); + + for entry in candidates + { + if result.len() >= max { - // Brand new request, to add - new_requests.push(i); + break; } - // Insert new job + let Some(job) = self.jobs.get(&entry.key) + else + { + continue; + }; + + if job.last_seen != frame || !keep(&entry.key) + { + continue; + } + + let Some(job) = self.remove_job(&entry.key) + else + { + continue; + }; + + if let Some(payload) = job.payload + { + result.push(ReadyItem { + key: job.key, + meta: job.meta, + payload, + }); + } + } + + result + } + + /// Removes every job belonging to a structure. + /// + /// Used when a structure slot is invalidated or reused (for example when + /// the toroidal structure table moves). + pub fn invalidate_structure(&mut self, structure: StructureId) -> usize + { + self.invalidate_matching(|key| key.structure_id == structure) + } + + /// Removes every job belonging to a producer. + pub fn invalidate_producer(&mut self, producer: ProducerId) -> usize + { + self.invalidate_matching(|key| key.producer_id == producer) + } + + fn invalidate_matching(&mut self, mut predicate: F) -> usize + where + F: FnMut(&RequestKey) -> bool, + { + let keys: Vec = self + .jobs + .keys() + .copied() + .filter(|key| predicate(key)) + .collect(); + + let count = keys.len(); + for key in keys + { + self.remove_job(&key); + } + count + } + + fn expire(&mut self, frame: FrameId, stats: &mut IngestStats) + { + let keys: Vec = self + .jobs + .iter() + .filter(|(_, job)| frame.saturating_sub(job.last_seen) > self.config.stale_after) + .map(|(key, _)| *key) + .collect(); + + for key in keys + { + self.remove_job(&key); + stats.expired += 1; + } + } + + fn remove_job(&mut self, key: &RequestKey) -> Option> + { + let job = self.jobs.remove(key)?; + let entry = entry_of(&job); + + match job.state + { + JobState::Queued => + { + self.queued.remove(&entry); + } + JobState::Ready => + { + self.ready.remove(&entry); + } + JobState::InFlight => + { + self.in_flight = self.in_flight.saturating_sub(1); + } + } + + Some(job) + } + + pub fn len(&self) -> usize + { + self.jobs.len() + } + + pub fn is_empty(&self) -> bool + { + self.jobs.is_empty() + } + + pub fn queued_len(&self) -> usize + { + self.queued.len() + } + + pub fn in_flight_len(&self) -> usize + { + self.in_flight + } + + pub fn ready_len(&self) -> usize + { + self.ready.len() + } + + pub fn contains(&self, key: &RequestKey) -> bool + { + self.jobs.contains_key(key) + } + + pub fn state_of(&self, key: &RequestKey) -> Option + { + self.jobs.get(key).map(|job| job.state) + } + + pub fn stats(&self) -> QueueStats + { + QueueStats { + queued: self.queued.len(), + in_flight: self.in_flight, + ready: self.ready.len(), + ..self.stats } } } + +#[cfg(test)] +mod tests +{ + use super::*; + + const PRODUCER: ProducerId = ProducerId(0); + const STRUCTURE: StructureId = StructureId(1); + + fn meta(page: u32, child: u32, depth: u32) -> RequestMeta + { + RequestMeta { + page_index: page, + children_index: child, + depth, + } + } + + fn child_key(parent: u32, child: u32) -> RequestKey + { + RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(parent), child) + } + + fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest + { + IncomingRequest { + key, + priority, + meta: meta(0, 0, 0), + } + } + + fn wire( + structure: u32, + node: u32, + child: u32, + producer: u32, + demand: u32, + parent_page: u32, + depth: u32, + ) -> (RequestInformation, RequestMeta) + { + ( + RequestInformation { + structure_id: structure, + node_id: node, + children_index: child, + producer_id: producer, + demand, + }, + RequestMeta { + page_index: parent_page, + children_index: child, + depth, + }, + ) + } + + fn queue(max_queued: usize, max_in_flight: usize, max_ready: usize) -> RequestQueue + { + RequestQueue::new(QueueConfig { + max_queued, + max_in_flight, + max_ready, + stale_after: 4, + max_attempts: 3, + }) + } + + #[test] + fn root_and_root_child_zero_do_not_collide() + { + let mut q = queue(8, 1, 8); + let root = RequestKey::root(PRODUCER, STRUCTURE); + let child = child_key(0, 0); + + q.ingest( + 0, + [ + incoming(root, RequestPriority::root(1)), + incoming(child, RequestPriority::child(1, 0)), + ], + ); + + assert_eq!(q.len(), 2); + assert!(q.contains(&root)); + assert!(q.contains(&child)); + } + + #[test] + fn from_wire_distinguishes_root_from_root_child_zero() + { + let (root_info, root_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX); + let (child_info, child_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0); + + let root = IncomingRequest::from_wire(&root_info, &root_meta); + let child = IncomingRequest::from_wire(&child_info, &child_meta); + + assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE)); + assert_eq!( + child.key, + RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(0), 0) + ); + assert_ne!(root.key, child.key); + } + + #[test] + fn from_wire_carries_demand_and_depth_into_priority() + { + let (info, meta) = wire(STRUCTURE.0, 5, 2, PRODUCER.0, 11, 9, 3); + let request = IncomingRequest::from_wire(&info, &meta); + + assert_eq!(request.priority, RequestPriority::child(11, 3)); + assert_eq!(request.meta.page_index, 9); + assert_eq!(request.meta.children_index, 2); + } + + #[test] + fn ready_item_builds_stateless_insertion_parent() + { + let mut q = queue(8, 2, 8); + let root = RequestKey::root(PRODUCER, STRUCTURE); + let child = child_key(4, 2); + + q.ingest( + 0, + [ + incoming(root, RequestPriority::root(1)), + IncomingRequest { + key: child, + priority: RequestPriority::child(1, 3), + meta: meta(7, 2, 3), + }, + ], + ); + + let root_item = q.pop().unwrap(); + q.complete(root_item, 1); + let child_item = q.pop().unwrap(); + q.complete(child_item, 2); + + let ready = q.drain_ready_matching(0, 8, |_| true); + assert_eq!(ready.len(), 2); + + let external = ready[0].insertion_parent(); + assert!(external.is_external()); + assert_eq!(external.page_index, NO_PARENT_PAGE); + assert_eq!(external.structure_id, STRUCTURE.0); + assert_eq!(external.producer_id, PRODUCER.0); + + let internal = ready[1].insertion_parent(); + assert!(internal.is_internal()); + assert_eq!(internal.page_index, 7); + assert_eq!(internal.children_index, 2); + assert_eq!(internal.depth, 3); + assert_eq!(internal.node_id, 4); + assert_eq!(internal.structure_id, STRUCTURE.0); + } + + #[test] + fn ready_item_prefers_key_child_slot_over_meta() + { + let mut q = queue(8, 1, 8); + let child = child_key(4, 2); + + q.ingest( + 0, + [IncomingRequest { + key: child, + priority: RequestPriority::child(1, 3), + meta: meta(7, 5, 3), + }], + ); + + let item = q.pop().unwrap(); + q.complete(item, 1); + let ready = q.drain_ready_matching(0, 8, |_| true); + let parent = ready[0].insertion_parent(); + + assert_eq!(parent.children_index, 2); + assert_eq!(parent.page_index, 7); + assert_eq!(parent.depth, 3); + } + + #[test] + fn producer_id_disambiguates_identical_structure_keys() + { + let mut q = queue(8, 1, 8); + let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(7), 3); + let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(7), 3); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(1, 0)), + incoming(b, RequestPriority::child(1, 0)), + ], + ); + + assert_eq!(q.len(), 2); + assert!(q.contains(&a)); + assert!(q.contains(&b)); + } + + #[test] + fn duplicate_keys_are_deduplicated() + { + let mut q = queue(8, 1, 8); + let key = child_key(1, 2); + let req = incoming(key, RequestPriority::child(1, 0)); + + let stats = q.ingest(0, [req, req, req]); + assert_eq!(stats.new, 1); + assert_eq!(stats.refreshed, 2); + assert_eq!(q.len(), 1); + assert_eq!(q.queued_len(), 1); + } + + #[test] + fn priority_ordering_prefers_higher_demand() + { + let mut q = queue(8, 8, 8); + let low = child_key(1, 0); + let high = child_key(2, 0); + + q.ingest( + 0, + [ + incoming(low, RequestPriority::child(1, 0)), + incoming(high, RequestPriority::child(9, 0)), + ], + ); + + assert_eq!(q.pop().unwrap().key, high); + assert_eq!(q.pop().unwrap().key, low); + } + + #[test] + fn roots_outrank_children() + { + let mut q = queue(8, 8, 8); + let root = RequestKey::root(PRODUCER, STRUCTURE); + let child = child_key(0, 0); + + q.ingest( + 0, + [ + incoming(child, RequestPriority::child(100, 0)), + incoming(root, RequestPriority::root(1)), + ], + ); + + assert_eq!(q.pop().unwrap().key, root); + } + + #[test] + fn shallower_children_are_more_urgent() + { + let mut q = queue(8, 8, 8); + let deep = child_key(1, 0); + let shallow = child_key(2, 0); + + q.ingest( + 0, + [ + incoming(deep, RequestPriority::child(5, 4)), + incoming(shallow, RequestPriority::child(5, 1)), + ], + ); + + assert_eq!(q.pop().unwrap().key, shallow); + } + + #[test] + fn priority_updates_reorder_queued_jobs() + { + let mut q = queue(8, 8, 8); + let a = child_key(1, 0); + let b = child_key(2, 0); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(1, 0)), + incoming(b, RequestPriority::child(5, 0)), + ], + ); + + // Promote a above b. + q.ingest(1, [incoming(a, RequestPriority::child(10, 0))]); + + assert_eq!(q.pop().unwrap().key, a); + assert_eq!(q.pop().unwrap().key, b); + } + + #[test] + fn queued_bound_evicts_lowest_priority() + { + let mut q = queue(2, 8, 8); + let a = child_key(1, 0); + let b = child_key(2, 0); + let c = child_key(3, 0); + + let stats = q.ingest( + 0, + [ + incoming(a, RequestPriority::child(1, 0)), + incoming(b, RequestPriority::child(2, 0)), + incoming(c, RequestPriority::child(3, 0)), + ], + ); + + assert_eq!(stats.evicted, 1); + assert_eq!(q.len(), 2); + assert!(!q.contains(&a)); + assert!(q.contains(&b)); + assert!(q.contains(&c)); + } + + #[test] + fn lower_priority_newcomer_is_dropped_when_full() + { + let mut q = queue(1, 8, 8); + let a = child_key(1, 0); + let b = child_key(2, 0); + + q.ingest(0, [incoming(a, RequestPriority::child(5, 0))]); + let stats = q.ingest(0, [incoming(b, RequestPriority::child(1, 0))]); + + assert_eq!(stats.dropped, 1); + assert_eq!(q.len(), 1); + assert!(q.contains(&a)); + assert!(!q.contains(&b)); + } + + #[test] + fn unseen_jobs_expire_after_grace_period() + { + let mut q = queue(8, 8, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + q.ingest(1, []); + assert!(q.contains(&key)); + + q.ingest(5, []); + assert!(!q.contains(&key)); + } + + #[test] + fn in_flight_jobs_expire_and_their_completion_is_discarded() + { + let mut q = queue(8, 8, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + let item = q.pop().unwrap(); + + q.ingest(5, []); + assert_eq!(q.in_flight_len(), 0); + assert!(!q.contains(&key)); + + assert_eq!(q.complete(item, 42), CompleteOutcome::Discarded); + } + + #[test] + fn stale_completion_after_recreation_is_discarded() + { + let mut q = queue(8, 8, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + let old_item = q.pop().unwrap(); + + q.ingest(5, []); + assert!(!q.contains(&key)); + + q.ingest(6, [incoming(key, RequestPriority::child(1, 0))]); + let new_item = q.pop().unwrap(); + + assert_eq!(q.complete(old_item, 1), CompleteOutcome::Discarded); + assert_eq!(q.complete(new_item, 2), CompleteOutcome::Accepted); + } + + #[test] + fn completed_jobs_become_ready_and_drain() + { + let mut q = queue(8, 8, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + let item = q.pop().unwrap(); + assert_eq!(q.complete(item, 99), CompleteOutcome::Accepted); + + assert_eq!(q.ready_len(), 1); + assert_eq!(q.state_of(&key), Some(JobState::Ready)); + + let ready = q.drain_ready_matching(0, 8, |_| true); + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].key, key); + assert_eq!(ready[0].payload, 99); + assert!(q.is_empty()); + } + + #[test] + fn drain_only_returns_jobs_seen_in_the_requested_frame() + { + let mut q = queue(8, 8, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + let item = q.pop().unwrap(); + q.complete(item, 1); + + // Was not refreshed at frame 1, so it must wait. + q.ingest(1, []); + assert!(q.drain_ready_matching(1, 8, |_| true).is_empty()); + assert_eq!(q.ready_len(), 1); + + // It is still current at frame 0 and can be drained then. + let ready = q.drain_ready_matching(0, 8, |_| true); + assert_eq!(ready.len(), 1); + } + + #[test] + fn drain_respects_keep_predicate() + { + let mut q = queue(8, 8, 8); + let a = child_key(1, 0); + let b = child_key(2, 0); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(2, 0)), + incoming(b, RequestPriority::child(1, 0)), + ], + ); + let first = q.pop().unwrap(); + q.complete(first, 1); + let second = q.pop().unwrap(); + q.complete(second, 2); + + let ready = q.drain_ready_matching(0, 8, |key| *key == b); + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].key, b); + assert_eq!(q.ready_len(), 1); + } + + #[test] + fn ready_backpressure_stops_dispatch() + { + let mut q = queue(8, 4, 2); + let a = child_key(1, 0); + let b = child_key(2, 0); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(2, 0)), + incoming(b, RequestPriority::child(1, 0)), + ], + ); + + assert!(q.pop().is_some()); + assert!(q.pop().is_some()); + assert!(q.pop().is_none()); + + assert_eq!(q.in_flight_len(), 2); + assert_eq!(q.ready_len(), 0); + } + + #[test] + fn fail_requeues_until_max_attempts() + { + let mut q = queue(8, 1, 8); + let key = child_key(1, 0); + + q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + + for attempt in 1..=3 + { + let item = q.pop().unwrap(); + assert_eq!(item.attempt, attempt); + q.fail(item); + } + + assert!(!q.contains(&key)); + } + + #[test] + fn invalidation_removes_queued_and_ready_jobs() + { + let mut q = queue(8, 8, 8); + let a = child_key(1, 0); + let b = child_key(9, 0); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(2, 0)), + incoming(b, RequestPriority::child(1, 0)), + ], + ); + let item = q.pop().unwrap(); + q.complete(item, 1); + + assert_eq!(q.invalidate_structure(STRUCTURE), 2); + assert!(q.is_empty()); + assert_eq!(q.in_flight_len(), 0); + assert_eq!(q.ready_len(), 0); + } + + #[test] + fn invalidate_producer_only_removes_that_producer() + { + let mut q = queue(8, 8, 8); + let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(1), 0); + let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(1), 0); + + q.ingest( + 0, + [ + incoming(a, RequestPriority::child(1, 0)), + incoming(b, RequestPriority::child(1, 0)), + ], + ); + + assert_eq!(q.invalidate_producer(ProducerId(0)), 1); + assert!(q.contains(&b)); + } + + #[test] + fn zero_queued_capacity_drops_everything() + { + let mut q = queue(0, 1, 8); + let key = child_key(1, 0); + let stats = q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); + assert_eq!(stats.dropped, 1); + assert!(q.is_empty()); + } +} diff --git a/src/terrain.rs b/src/terrain.rs index 528536a..43e667f 100644 --- a/src/terrain.rs +++ b/src/terrain.rs @@ -47,6 +47,7 @@ impl ToroidalStructureTable extent: (usize, usize, usize), initial_position: Vec3, max_requests: usize, + producer_id: u32, ) -> Self { let size = extent.0 * extent.1 * extent.2; @@ -81,7 +82,12 @@ impl ToroidalStructureTable ToroidalStructureTable { extent, - fixed_structure_table: FixedStructureTable::new(device, size, max_requests), + fixed_structure_table: FixedStructureTable::new( + device, + size, + max_requests, + producer_id, + ), position: initial_position, current_offset, invalidation_pass, @@ -89,13 +95,37 @@ impl ToroidalStructureTable } /// Moves the center position to `new_position`. - /// This requires updating to structure table to remove disapearing chunks - pub fn move_position(&mut self, encoder: &mut CommandEncoder, new_position: Vec3) + /// This requires updating to structure table to remove disapearing chunks. + /// + /// Returns the structure slots whose world position changed. The host must + /// invalidate any pending request/insertion work for those slots before it + /// batches insertions for this frame. + pub fn move_position( + &mut self, + encoder: &mut CommandEncoder, + new_position: Vec3, + ) -> Vec { let previous_offset = self.current_offset; - self.current_offset = Self::offset_from_center(self.extent, new_position); + let new_offset = Self::offset_from_center(self.extent, new_position); + self.current_offset = new_offset; self.position = new_position; + let mut invalidated = Vec::new(); + if previous_offset != new_offset + { + let size = self.extent.0 * self.extent.1 * self.extent.2; + for id in 0..size + { + let previous = Self::position_for_offset(self.extent, id, previous_offset); + let current = Self::position_for_offset(self.extent, id, new_offset); + if previous != current + { + invalidated.push(id as u32); + } + } + } + let invalidation_parameters = ToroidalInvalidationImmediates { extent: [ self.extent.0 as u32, @@ -130,23 +160,30 @@ impl ToroidalStructureTable self.extent.1.div_ceil(4) as u32, self.extent.2.div_ceil(4) as u32, ); + + invalidated } /// Given the structure id, returns the position of the requesting chunk pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize) { - let (ex, ey, ez) = ( - self.extent.0 as isize, - self.extent.1 as isize, - self.extent.2 as isize, - ); + Self::position_for_offset(self.extent, structure_id as usize, self.current_offset) + } + + fn position_for_offset( + extent: (usize, usize, usize), + structure_id: usize, + offset: (isize, isize, isize), + ) -> (isize, isize, isize) + { + let (ex, ey, ez) = (extent.0 as isize, extent.1 as isize, extent.2 as isize); let id = structure_id as isize; let sx = id % ex; let sz = (id / ex) % ez; let sy = id / (ex * ez); - let (ox, oy, oz) = self.current_offset; + let (ox, oy, oz) = offset; ( ox + (sx - ox).rem_euclid(ex), @@ -181,12 +218,11 @@ impl ToroidalStructureTable device: &wgpu::Device, encoder: &mut crate::gpu_profiler::ScopeEncoder, insertion: &voxel_cache::insertion::CacheInsertionData, - request: &voxel_cache::requests::CacheRequestBuffer, ) where [(); N * N * N]:, { self.fixed_structure_table - .insert(device, encoder, insertion, request); + .insert(device, encoder, insertion); } pub fn gather_requests( @@ -201,8 +237,20 @@ impl ToroidalStructureTable } } -impl voxel_cache::CacheInvalidable for ToroidalStructureTable +impl voxel_cache::CacheInvalidable for ToroidalStructureTable +where + [(); N * N * N]:, { + fn validate_insertion( + &mut self, + device: &wgpu::Device, + encoder: &mut crate::gpu_profiler::ScopeEncoder, + insertion: &voxel_cache::insertion::CacheInsertionData, + ) { + self.fixed_structure_table + .validate_insertion(device, encoder, insertion); + } + fn invalidate( &mut self, encoder: &mut crate::gpu_profiler::ScopeEncoder, diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 4bb6b43..f4a7242 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -108,7 +108,9 @@ where frame_timestamp: u32, } -pub trait CacheInvalidable +pub trait CacheInvalidable +where + [(); N * N * N]:, { fn invalidate( &mut self, @@ -116,14 +118,23 @@ pub trait CacheInvalidable cache_evictor: &CacheEvictor, invalid_timestamp: u32, ); + + /// Validates an external insertion batch against the structure table and + /// compacts the valid entries before the cache allocates pages for them. + fn validate_insertion( + &mut self, + device: &Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ); } pub enum VoxelCacheInsertion<'a, const N: usize> where [(); N * N * N]:, { - ExternalRequest(&'a CacheInsertionData, &'a mut dyn CacheInvalidable), - InternalRequest(&'a CacheInsertionData, &'a CacheRequestBuffer), + ExternalRequest(&'a CacheInsertionData, &'a mut dyn CacheInvalidable), + InternalRequest(&'a CacheInsertionData), } impl VoxelCache @@ -243,12 +254,36 @@ where &mut encoder, ); + // Validate everything before allocating any page, so stale insertions + // can never consume a recycled page. + for insertion in insertions.iter_mut() + { + match insertion + { + VoxelCacheInsertion::ExternalRequest(cache_insertion_data, invalidable) => + { + invalidable.validate_insertion(device, &mut encoder, cache_insertion_data); + } + VoxelCacheInsertion::InternalRequest(cache_insertion_data) => + { + self.cache_insertion_pass.encode_validation( + device, + &mut encoder, + &self.attributes, + &self.structure, + cache_insertion_data, + &self.evictor, + ); + } + } + } + for insertion in insertions.iter() { match insertion { VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _) - | VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) => + | VoxelCacheInsertion::InternalRequest(cache_insertion_data) => { self.cache_insertion_pass.encode( device, @@ -283,13 +318,12 @@ where // Write internal requests pointers for insertion in insertions.iter_mut() { - if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion + if let VoxelCacheInsertion::InternalRequest(insertion) = insertion { self.write_pointers_pass.encode( &mut encoder, device, &self.structure, - request, insertion, ); } diff --git a/src/voxel_cache/insertion.rs b/src/voxel_cache/insertion.rs index 18a1720..e05039d 100644 --- a/src/voxel_cache/insertion.rs +++ b/src/voxel_cache/insertion.rs @@ -6,6 +6,7 @@ use wgpu::ShaderStages; use crate::voxel_cache::layout::CacheLayout; use crate::voxel_cache::schema::InsertionInformation; +use crate::voxel_cache::schema::InsertionParent; use crate::voxel_cache::schema::LocationPage; /// Data to be inserted in a cache insertion operation @@ -31,6 +32,15 @@ where /// Contains the indicies of the page in which the data was written destination_indices: wgpu::Buffer, + /// Parent/attachment information for every entry : dense array of [`InsertionParent`] + insertion_parents: wgpu::Buffer, + + /// Indices of the entries that passed validation, written by the validation pass + valid_indices: wgpu::Buffer, + + /// Amount of entries written to [`Self::valid_indices`] + valid_count: wgpu::Buffer, + bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, bind_group_no_attributes: wgpu::BindGroup, @@ -65,11 +75,32 @@ where let destination_indices = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheInsertionData::destination_indices"), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + size: (size_of::() * max_page_count) as u64, + }); + + let insertion_parents = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::insertion_parents"), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + size: (size_of::() * max_page_count) as u64, + }); + + let valid_indices = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::valid_indices"), usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false, size: (size_of::() * max_page_count) as u64, }); + let valid_count = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::valid_count"), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + size: size_of::() as u64, + }); + let attributes = layout .attributes .iter() @@ -105,6 +136,18 @@ where binding: 3, resource: destination_indices.as_entire_binding(), }, + wgpu::BindGroupEntry { + binding: 4, + resource: insertion_parents.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: valid_indices.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 6, + resource: valid_count.as_entire_binding(), + }, ]; let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None); @@ -114,7 +157,7 @@ where entries: &entries, }); entries.push(wgpu::BindGroupEntry { - binding: 4, + binding: 7, resource: wgpu::BindingResource::BufferArray(&bind_group_bindings), }); @@ -131,6 +174,9 @@ where insertion_information, location_pages, destination_indices, + insertion_parents, + valid_indices, + valid_count, attributes, bind_group_layout, @@ -155,53 +201,31 @@ where layout: Option<&CacheLayout>, ) -> BindGroupLayout { + let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry { + binding, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + let mut entries = vec![ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 3, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, + storage_entry(0), // page count + storage_entry(1), // insertion information + storage_entry(2), // location pages + storage_entry(3), // destination indices + storage_entry(4), // insertion parents + storage_entry(5), // valid indices + storage_entry(6), // valid count ]; if let Some(layout) = layout { entries.push(wgpu::BindGroupLayoutEntry { - binding: 4, + binding: 7, visibility: ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, @@ -248,6 +272,26 @@ where &self.location_pages } + pub fn destination_indices_buffer(&self) -> &wgpu::Buffer + { + &self.destination_indices + } + + pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer + { + &self.insertion_parents + } + + pub fn valid_indices_buffer(&self) -> &wgpu::Buffer + { + &self.valid_indices + } + + pub fn valid_count_buffer(&self) -> &wgpu::Buffer + { + &self.valid_count + } + pub fn attributes_buffers(&self) -> &[wgpu::Buffer] { &self.attributes diff --git a/src/voxel_cache/pipelines.rs b/src/voxel_cache/pipelines.rs index ff52927..016be73 100644 --- a/src/voxel_cache/pipelines.rs +++ b/src/voxel_cache/pipelines.rs @@ -160,6 +160,9 @@ where /// Copies new pages into cache using LRU order write_pipeline: ComputePipeline, + /// Validates internal insertions and compacts their indices + validate_internal_pipeline: ComputePipeline, + /// u32 buffer containing amount of inserted data of current pass inserted_count: wgpu::Buffer, inserted_count_bind_group: wgpu::BindGroup, @@ -244,8 +247,19 @@ where cache: None, }); + let validate_internal_pipeline = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheInsertionPass::validate_internal_pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("validate_internal"), + compilation_options: Default::default(), + cache: None, + }); + Self { write_pipeline, + validate_internal_pipeline, consume_pipeline, inserted_count, inserted_count_bind_group, @@ -253,6 +267,45 @@ where } } + /// Validates internal insertions and compacts them into the insertion data's + /// `valid_indices` buffer. + /// + /// External roots are validated by the structure table that requested them. + #[allow(clippy::too_many_arguments)] + pub fn encode_validation( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + cache_attributes: &CacheAttributes, + cache_structure: &CacheStructure, + insertion_data: &CacheInsertionData, + cache_evictor: &CacheEvictor, + ) + { + gpu_profiler::begin_scope!(encoder, "PageInsertionValidation"); + + let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count( + device, + &mut encoder, + insertion_data.page_count_buffer(), + 256, + ); + + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("CacheInsertionPass::validation_pass"), + timestamp_writes: None, + }); + + pass.set_bind_group(0, cache_attributes.bind_group(), &[]); + pass.set_bind_group(1, cache_structure.bind_group(), &[]); + pass.set_bind_group(2, insertion_data.bind_group(), &[]); + pass.set_bind_group(3, cache_evictor.bind_group(), &[]); + pass.set_bind_group(4, &self.inserted_count_bind_group, &[]); + + pass.set_pipeline(&self.validate_internal_pipeline); + pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0); + } + #[allow(clippy::too_many_arguments)] pub fn encode( &self, @@ -396,8 +449,6 @@ where let bindings = [ // To find where pages are pointing Some(&CacheStructure::::create_bind_group_layout(device)), - // To find where the requests came from - Some(&CacheRequestBuffer::create_bind_group_layout(device)), // To find where the request's response went Some(&CacheInsertionData::::create_bind_group_layout( device, @@ -438,7 +489,6 @@ where encoder: &mut ScopeEncoder, device: &Device, cache_structure: &CacheStructure, - request_buffer: &CacheRequestBuffer, cache_insertion_data: &CacheInsertionData, ) { @@ -458,8 +508,7 @@ where pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, cache_structure.bind_group(), &[]); - pass.set_bind_group(1, request_buffer.bind_group(), &[]); - pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]); + pass.set_bind_group(1, cache_insertion_data.bind_group(), &[]); pass.dispatch_workgroups_indirect(indirect_buffer, 0); } diff --git a/src/voxel_cache/requests.rs b/src/voxel_cache/requests.rs index 522ddde..c05a974 100644 --- a/src/voxel_cache/requests.rs +++ b/src/voxel_cache/requests.rs @@ -150,7 +150,7 @@ impl CacheRequestHandler let bind_group = create_multi_buffers_bind_group( device, &bind_group_layout, - &[&request_count, &sorted_requests], + &[&request_count, &sorted_requests, &request_counts_pages], Some("CacheRequestHandler::bind_group"), ); @@ -299,7 +299,7 @@ impl CacheRequestHandler { create_multi_buffers_bind_group_layout( device, - 2, + 3, Some("CacheRequestHandler::bind_group_layout"), ) } @@ -390,14 +390,16 @@ impl CacheRequestBuffer &self.bind_group } - pub fn host_download_requests( + pub fn host_download_requests< + F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static, + >( &self, device: &Device, queue: &wgpu::Queue, callback: F, ) { - // Once the two required buffer have been mapped, the requestMapState will automatically + // Once the three required buffers have been mapped, the requestMapState will automatically // fire the callback let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback))); @@ -433,33 +435,58 @@ impl CacheRequestBuffer .set_request_infos(request_infos); }, ); + + let request_map_state_3 = request_map_state.clone(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &self.request_meta.slice(..), + move |buffer| { + let mapped_buffer = buffer.expect("Could not map request buffer (meta)."); + let request_metas: Vec = + bytemuck::pod_collect_to_vec(&mapped_buffer); + + request_map_state_3 + .lock() + .unwrap() + .set_request_metas(request_metas); + }, + ); } } -struct RequestMapState () + Send + Sync + 'static> +struct RequestMapState { request_count: Option, request_infos: Option>, + request_metas: Option>, callback: F, } -impl () + Send + Sync + 'static> RequestMapState +impl RequestMapState { pub fn new(callback: F) -> Self { Self { request_count: None, request_infos: None, + request_metas: None, callback, } } fn try_callback(&mut self) { - if let (Some(request_count), Some(request_infos)) = - (self.request_count, &self.request_infos) + if let (Some(request_count), Some(request_infos), Some(request_metas)) = ( + self.request_count, + &self.request_infos, + &self.request_metas, + ) { - (self.callback)(&request_infos[0..request_count]) + (self.callback)( + &request_infos[0..request_count], + &request_metas[0..request_count], + ) } } @@ -474,4 +501,10 @@ impl () + Send + Sync + 'static> RequestMapSt self.request_infos = Some(request_infos); self.try_callback(); } + + pub fn set_request_metas(&mut self, request_metas: Vec) + { + self.request_metas = Some(request_metas); + self.try_callback(); + } } diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs index e76877e..9b96657 100644 --- a/src/voxel_cache/schema.rs +++ b/src/voxel_cache/schema.rs @@ -110,6 +110,9 @@ pub struct LocationPage /// Identifier for locating this particular node within the structure pub node_id: u32, + + /// Identifier of the producer that owns this node + pub producer_id: u32, } /// Page storing the depth of the current node related to its root. @@ -150,6 +153,12 @@ pub struct RequestInformation /// The index of the children on which the request was issued pub children_index: u32, + + /// Identifier of the producer that owns the requesting node + pub producer_id: u32, + + /// The amount of times this request was emitted this frame. Higher means more urgent. + pub demand: u32, } /// Metainformation kept along each request, to know which node made the demand @@ -168,6 +177,105 @@ pub struct RequestMeta pub depth: u32, } +/// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a +/// request/insertion that has no cache parent (an external root requested by a structure table). +pub const NO_PARENT_PAGE: u32 = u32::MAX; + +/// Kind of parent an insertion is attached to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable, Pod)] +#[repr(transparent)] +pub struct InsertionParentKind(u32); + +impl InsertionParentKind +{ + /// The new page is a child of a resident cache page. + pub const INTERNAL: Self = Self(0); + + /// The new page is the root of a structure owned by a structure table. + pub const EXTERNAL: Self = Self(1); + + pub fn raw(self) -> u32 + { + self.0 + } +} + +/// Identity and attachment point of the page being inserted. +/// +/// This makes an insertion batch self-describing: the GPU can validate that the parent is still +/// the node the request was issued on, and link the new page without reading the request buffer. +#[derive(Clone, Copy, Debug, Zeroable, Pod)] +#[repr(C)] +pub struct InsertionParent +{ + /// [`InsertionParentKind`]. + pub kind: u32, + + /// Cache page of the parent. [`NO_PARENT_PAGE`] for external roots. + pub page_index: u32, + + /// Child slot inside the parent. `0` for external roots. + pub children_index: u32, + + /// Depth of the parent. [`NO_PARENT_PAGE`] for external roots. + pub depth: u32, + + /// Structure the parent belongs to. + pub structure_id: u32, + + /// Locator of the parent inside the structure. `0` for external roots. + pub node_id: u32, + + /// Producer that owns the parent. + pub producer_id: u32, +} + +impl InsertionParent +{ + /// Parent information for a child of a resident cache page. + pub fn internal( + meta: &RequestMeta, + structure_id: u32, + node_id: u32, + producer_id: u32, + ) -> Self + { + Self { + kind: InsertionParentKind::INTERNAL.raw(), + page_index: meta.page_index, + children_index: meta.children_index, + depth: meta.depth, + structure_id, + node_id, + producer_id, + } + } + + /// Parent information for the root of an external structure. + pub fn external(structure_id: u32, producer_id: u32) -> Self + { + Self { + kind: InsertionParentKind::EXTERNAL.raw(), + page_index: NO_PARENT_PAGE, + children_index: 0, + depth: NO_PARENT_PAGE, + structure_id, + node_id: 0, + producer_id, + } + } + + pub fn is_external(&self) -> bool + { + self.kind == InsertionParentKind::EXTERNAL.raw() + } + + pub fn is_internal(&self) -> bool + { + self.kind == InsertionParentKind::INTERNAL.raw() + } +} + /// Structure information about the children of a node. /// Used when inserting data in the cache, to setup structure pointers /// diff --git a/src/voxel_cache/shaders/common.wgsl b/src/voxel_cache/shaders/common.wgsl index 20ecf28..4bef236 100644 --- a/src/voxel_cache/shaders/common.wgsl +++ b/src/voxel_cache/shaders/common.wgsl @@ -9,7 +9,9 @@ struct RequestInformation { structure_id: u32, node_id: u32, - children_index: u32 + children_index: u32, + producer_id: u32, + demand: u32 } struct RequestMeta @@ -19,6 +21,22 @@ struct RequestMeta depth: u32 } +// No cache parent (external root insertion). +const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu; +const INSERTION_PARENT_INTERNAL: u32 = 0u; +const INSERTION_PARENT_EXTERNAL: u32 = 1u; + +struct InsertionParent +{ + kind: u32, + page_index: u32, + children_index: u32, + depth: u32, + structure_id: u32, + node_id: u32, + producer_id: u32, +} + struct AttributeArray { values: array @@ -28,6 +46,7 @@ struct LocationPage { structure_id: u32, node_id: u32, + producer_id: u32, } fn child_information_occupied(info: u32) -> bool diff --git a/src/voxel_cache/shaders/fixed_table/insertion.wgsl b/src/voxel_cache/shaders/fixed_table/insertion.wgsl index 09a9a8a..a78d381 100644 --- a/src/voxel_cache/shaders/fixed_table/insertion.wgsl +++ b/src/voxel_cache/shaders/fixed_table/insertion.wgsl @@ -6,27 +6,46 @@ @group(1) @binding(1) var insertion_data_information: array; // UNUSED @group(1) @binding(2) var insertion_data_location_pages: array; @group(1) @binding(3) var insertion_data_destination_indices: array; -@group(1) @binding(4) var insertion_data_attributes: binding_array; +@group(1) @binding(4) var insertion_data_parents: array; +@group(1) @binding(5) var insertion_data_valid_indices: array; +@group(1) @binding(6) var insertion_data_valid_count: atomic; -/// Group 2: Request buffer -@group(2) @binding(0) var request_buffer_count: u32; // Request count -@group(2) @binding(1) var request_buffer_informations: array; -@group(2) @binding(2) var request_buffer_meta: array; +const DESTINATION_NONE: u32 = 0xFFFFFFFFu; @compute @workgroup_size(256, 1, 1) fn insertion(@builtin(global_invocation_id) gid: vec3) { let index = gid.x; - if(index >= insertion_data_page_count_buffer) + let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents)); + if(index >= entry_count) + { + return; + } + + let parent = insertion_data_parents[index]; + if(parent.kind != INSERTION_PARENT_EXTERNAL) { return; } let destination = insertion_data_destination_indices[index]; - if(destination != 0xFFFFFFFF) + if(destination == DESTINATION_NONE) { - let request_location = request_buffer_informations[index].structure_id; - fixed_table_pointers[request_location] = child_pointer_make_available(insertion_data_destination_indices[index]); + return; } + + if(parent.structure_id >= arrayLength(&fixed_table_pointers)) + { + return; + } + + // Re-check that the slot is still waiting for this root. + let pointer = fixed_table_pointers[parent.structure_id]; + if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer)) + { + return; + } + + fixed_table_pointers[parent.structure_id] = child_pointer_make_available(destination); } diff --git a/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl new file mode 100644 index 0000000..bee37e9 --- /dev/null +++ b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl @@ -0,0 +1,56 @@ +// Group 0: Table pointers +@group(0) @binding(0) var fixed_table_pointers: array; + +// Group 1: Cache insertion data +@group(1) @binding(0) var insertion_data_page_count_buffer: u32; +@group(1) @binding(1) var insertion_data_information: array; // UNUSED +@group(1) @binding(2) var insertion_data_location_pages: array; +@group(1) @binding(3) var insertion_data_destination_indices: array; +@group(1) @binding(4) var insertion_data_parents: array; +@group(1) @binding(5) var insertion_data_valid_indices: array; +@group(1) @binding(6) var insertion_data_valid_count: atomic; + +const DESTINATION_NONE: u32 = 0xFFFFFFFFu; + +/// Validates external root insertions against the structure table. +/// +/// A root is still wanted while its table slot is subdivisible but not yet +/// available. Slots that were already satisfied (or whose structure was +/// invalidated before the request was dispatched) are dropped here, before the +/// cache allocates any page for them. +@compute +@workgroup_size(256, 1, 1) +fn validate_external(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents)); + if(index >= entry_count) + { + return; + } + + let parent = insertion_data_parents[index]; + + // Reset every destination; only validated entries that are allocated get a + // page written back by the cache insertion pass. + insertion_data_destination_indices[index] = DESTINATION_NONE; + + if(parent.kind != INSERTION_PARENT_EXTERNAL) + { + return; + } + + if(parent.structure_id >= arrayLength(&fixed_table_pointers)) + { + return; + } + + let pointer = fixed_table_pointers[parent.structure_id]; + if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer)) + { + return; + } + + let slot = atomicAdd(&insertion_data_valid_count, 1u); + insertion_data_valid_indices[slot] = index; +} diff --git a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl index cb04c55..57c7bda 100644 --- a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl +++ b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl @@ -1,12 +1,15 @@ /// Group 0: Cache request handler @group(0) @binding(0) var request_handler_count: u32; // Request count @group(0) @binding(1) var request_handler_requests: array; +@group(0) @binding(2) var request_handler_counts: array; /// Group 1: Request buffer @group(1) @binding(0) var request_buffer_count: u32; // Request count @group(1) @binding(1) var request_buffer_informations: array; @group(1) @binding(2) var request_buffer_meta: array; +var table_producer_id: u32; + @compute @workgroup_size(256, 1, 1) fn write_requests(@builtin(global_invocation_id) gid: vec3) @@ -18,13 +21,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) return; } + let structure_id = request_handler_requests[index]; + var request_info: RequestInformation; - request_info.structure_id = request_handler_requests[index]; + request_info.structure_id = structure_id; request_info.node_id = 0; request_info.children_index = 0; + request_info.producer_id = table_producer_id; + request_info.demand = request_handler_counts[structure_id]; var request_meta: RequestMeta; - request_meta.page_index = 0; + // External requests have no parent page. + request_meta.page_index = 0xFFFFFFFF; request_meta.children_index = 0; // u32s wrap arround request_meta.depth = 0xFFFFFFFF; diff --git a/src/voxel_cache/shaders/insertion.wgsl b/src/voxel_cache/shaders/insertion.wgsl index 78e97b6..54bdd86 100644 --- a/src/voxel_cache/shaders/insertion.wgsl +++ b/src/voxel_cache/shaders/insertion.wgsl @@ -12,7 +12,10 @@ @group(2) @binding(1) var insertion_data_information: array; @group(2) @binding(2) var insertion_data_location_pages: array; @group(2) @binding(3) var insertion_data_destination_indices: array; -@group(2) @binding(4) var insertion_data_attributes: binding_array; +@group(2) @binding(4) var insertion_data_parents: array; +@group(2) @binding(5) var insertion_data_valid_indices: array; +@group(2) @binding(6) var insertion_data_valid_count: atomic; +@group(2) @binding(7) var insertion_data_attributes: binding_array; // Group 3: Cache evictor @group(3) @binding(0) var cache_evictor_timestamps: array; @@ -24,13 +27,79 @@ var new_timestamp: u32; -// Computes amount of available LRU pages -fn available_amount() -> u32 +const DESTINATION_NONE: u32 = 0xFFFFFFFFu; + +fn insertion_entry_count() -> u32 +{ + return min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents)); +} + +/// Checks that the parent page still holds the node the request was issued on, +/// and that the requested child slot is still waiting for a page. +fn internal_parent_is_valid(parent: InsertionParent) -> bool +{ + if(parent.page_index >= PAGE_COUNT) + { + return false; + } + + let location = structure_location_pages[parent.page_index]; + if(location.structure_id != parent.structure_id || + location.node_id != parent.node_id || + location.producer_id != parent.producer_id) + { + return false; + } + + if(structure_depth_pages[parent.page_index] != parent.depth) + { + return false; + } + + let pointer = structure_pointer_pages[parent.page_index].pointers[parent.children_index]; + return child_pointer_subdivided(pointer) && !child_pointer_available(pointer); +} + +/// Validates a batch of internal insertions and compacts the valid ones into +/// `insertion_data_valid_indices`. +/// +/// This must run before page allocation so that stale insertions never consume +/// an evicted page. External roots are validated by the structure table that +/// requested them (see `fixed_table/validate_insertion.wgsl`). +@compute +@workgroup_size(256, 1, 1) +fn validate_internal(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + if(index >= insertion_entry_count()) + { + return; + } + + let parent = insertion_data_parents[index]; + + // Reset the destination of every entry. Only entries compacted into + // `valid_indices` and actually allocated by the insertion pass get a page; + // this keeps invalid/stale insertions from reusing a previous batch's + // destination if the host did not pre-fill the buffer. + insertion_data_destination_indices[index] = DESTINATION_NONE; + + if(parent.kind != INSERTION_PARENT_INTERNAL) + { + return; + } + + if(internal_parent_is_valid(parent)) + { + let slot = atomicAdd(&insertion_data_valid_count, 1u); + insertion_data_valid_indices[slot] = index; + } +} + +fn available_amount(valid_count: u32) -> u32 { let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count; - let available_amount = min(lru_remaining, insertion_data_page_count_buffer); - - return available_amount; + return min(lru_remaining, valid_count); } @compute @@ -38,7 +107,7 @@ fn available_amount() -> u32 fn consume(@builtin(global_invocation_id) gid: vec3) { // Report consumed amount of LRU pages to cache evictor - // So that subsequent insertions can can continue to use new pages + // So that subsequent insertions can can continue to use new pages cache_evictor_consumed_count += atomicLoad(&pass_inserted_count); atomicStore(&pass_inserted_count, 0); } @@ -47,48 +116,57 @@ fn consume(@builtin(global_invocation_id) gid: vec3) @workgroup_size(256, 1, 1) fn insertion(@builtin(global_invocation_id) gid: vec3) { - let index = gid.x; - //let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer); - let insertion_count = available_amount(); - - if(index >= insertion_data_page_count_buffer) + let slot = gid.x; + let entry_count = insertion_entry_count(); + if(slot >= entry_count) { return; } - if(index >= insertion_count) - { - // Report that page was not written - insertion_data_destination_indices[index] = 0xFFFFFFFF; - return; + let valid_count = atomicLoad(&insertion_data_valid_count); + if(slot >= valid_count) + { + return; + } + + // Compacted entry index in the host-provided arrays. + let index = insertion_data_valid_indices[slot]; + let insertion_count = available_amount(valid_count); + + if(slot >= insertion_count) + { + // Report that page was not written. The host also pre-fills the whole + // destination array with DESTINATION_NONE, so this is defensive. + insertion_data_destination_indices[index] = DESTINATION_NONE; + return; } // Get a page to evict - let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count]; + let page_index = cache_evictor_lru_pages[slot + cache_evictor_consumed_count]; let page_timestamp = cache_evictor_timestamps[page_index]; if(page_timestamp >= new_timestamp - 1) { // Do not insert page - insertion_data_destination_indices[index] = 0xFFFFFFFF; - return; + insertion_data_destination_indices[index] = DESTINATION_NONE; + return; } atomicAdd(&pass_inserted_count, 1); insertion_data_destination_indices[index] = page_index; // Copy new location - structure_location_pages[page_index] = insertion_data_location_pages[index]; + structure_location_pages[page_index] = insertion_data_location_pages[index]; // Copy new pointers let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]); - structure_pointer_pages[page_index] = new_pointers; + structure_pointer_pages[page_index] = new_pointers; // Mark page as dirty for invalidation cache_evictor_timestamps[page_index] = new_timestamp; - // Set default depth - structure_depth_pages[page_index] = 0; + // Set default depth. `write_pointers` refines it for internal insertions. + structure_depth_pages[page_index] = 0; // Copy attributes for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++) @@ -116,7 +194,7 @@ fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage var occupancy_low = u32(0); var occupancy_high = u32(0); - for(var i = u32(0); i < CHILDREN_COUNT; i++) + for(var i = u32(0); i < CHILDREN_COUNT; i++) { let insert_info = info.children[i]; diff --git a/src/voxel_cache/shaders/write_pointers.wgsl b/src/voxel_cache/shaders/write_pointers.wgsl index 615aa0d..9eedb1a 100644 --- a/src/voxel_cache/shaders/write_pointers.wgsl +++ b/src/voxel_cache/shaders/write_pointers.wgsl @@ -3,34 +3,61 @@ @group(0) @binding(1) var structure_location_pages: array; @group(0) @binding(2) var structure_depth_pages: array; -/// Group 1: Request buffer -@group(1) @binding(0) var request_buffer_count: u32; // Request count -@group(1) @binding(1) var request_buffer_informations: array; -@group(1) @binding(2) var request_buffer_meta: array; +// Group 1: Cache insertion data +@group(1) @binding(0) var insertion_data_page_count_buffer: u32; +@group(1) @binding(1) var insertion_data_information: array; +@group(1) @binding(2) var insertion_data_location_pages: array; +@group(1) @binding(3) var insertion_data_destination_indices: array; +@group(1) @binding(4) var insertion_data_parents: array; +@group(1) @binding(5) var insertion_data_valid_indices: array; +@group(1) @binding(6) var insertion_data_valid_count: atomic; +@group(1) @binding(7) var insertion_data_attributes: binding_array; -// Group 2: Cache insertion data -@group(2) @binding(0) var insertion_data_page_count_buffer: u32; -@group(2) @binding(1) var insertion_data_information: array; -@group(2) @binding(2) var insertion_data_location_pages: array; -@group(2) @binding(3) var insertion_data_destination_indices: array; -@group(2) @binding(4) var insertion_data_attributes: binding_array; +const DESTINATION_NONE: u32 = 0xFFFFFFFFu; +/// Links inserted pages into their parent, using only the insertion batch's own +/// parent description. No request buffer is involved, so a batch may be +/// produced on a different frame than the one that emitted the requests. @compute @workgroup_size(256, 1, 1) fn write_pointers(@builtin(global_invocation_id) gid: vec3) { let index = gid.x; - if(index >= request_buffer_count || index >= insertion_data_page_count_buffer) { return; } - - // The write pages pass establishes a one-to-one corresepondancy - // between requests and recycled pages - let meta_inf = request_buffer_meta[index]; - let page_index = insertion_data_destination_indices[index]; - - if(page_index != 0xFFFFFFFF) + let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents)); + if(index >= entry_count) { - structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index] - = child_pointer_make_available(page_index); - structure_depth_pages[page_index] = meta_inf.depth + 1; + return; } + + let parent = insertion_data_parents[index]; + if(parent.kind != INSERTION_PARENT_INTERNAL) + { + return; + } + + let page_index = insertion_data_destination_indices[index]; + if(page_index == DESTINATION_NONE) + { + return; + } + + // The parent page may have been recycled while this insertion batch was in + // flight. Only link if it still describes the same node, and never link a + // page to itself. + if(parent.page_index >= PAGE_COUNT || parent.page_index == page_index) + { + return; + } + + let location = structure_location_pages[parent.page_index]; + if(location.structure_id != parent.structure_id || + location.node_id != parent.node_id || + location.producer_id != parent.producer_id) + { + return; + } + + structure_pointer_pages[parent.page_index].pointers[parent.children_index] + = child_pointer_make_available(page_index); + structure_depth_pages[page_index] = parent.depth + 1; } diff --git a/src/voxel_cache/shaders/write_requests.wgsl b/src/voxel_cache/shaders/write_requests.wgsl index 597cd56..fa04ece 100644 --- a/src/voxel_cache/shaders/write_requests.wgsl +++ b/src/voxel_cache/shaders/write_requests.wgsl @@ -8,6 +8,7 @@ /// Group 1: Cache request handler @group(1) @binding(0) var request_handler_count: u32; // Request count @group(1) @binding(1) var request_handler_requests: array; +@group(1) @binding(2) var request_handler_counts: array; /// Group 3: Request buffer @group(2) @binding(0) var request_buffer_count: u32; // Request count @@ -35,6 +36,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) request_information.structure_id = structure_location_pages[page_index].structure_id; request_information.node_id = structure_location_pages[page_index].node_id; request_information.children_index = request_location.children_index; + request_information.producer_id = structure_location_pages[page_index].producer_id; + request_information.demand = request_handler_counts[request_index]; // Fill out request meta information var request_meta: RequestMeta; diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs index b9b0145..a33a7c1 100644 --- a/src/voxel_cache/tables.rs +++ b/src/voxel_cache/tables.rs @@ -47,10 +47,14 @@ pub struct FixedStructureTable common_ressources: CacheRessources<1>, request_handler: CacheRequestHandler<1>, + /// Producer that owns the root structures stored by this table + producer_id: u32, + // To dispatch write request passes per request count indirect_buffer: IndirectBuffer1D, write_requests_pass: wgpu::ComputePipeline, invalidation_pass: wgpu::ComputePipeline, + validation_pass: wgpu::ComputePipeline, insertion_pass: wgpu::ComputePipeline, // Raytrace @@ -60,7 +64,12 @@ pub struct FixedStructureTable impl FixedStructureTable { - pub fn new(device: &wgpu::Device, size: usize, max_requests: usize) -> Self + pub fn new( + device: &wgpu::Device, + size: usize, + max_requests: usize, + producer_id: u32, + ) -> Self { let pointer = CachePointer::new(Some(None)); let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -98,7 +107,7 @@ impl FixedStructureTable device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("FixedStructureTable::pipeline_layout"), bind_group_layouts: &write_requests_bindings, - immediate_size: 0, + immediate_size: size_of::() as u32, }); let write_requests_shader_module = device.create_shader_module(include_table_wgsl!( @@ -153,7 +162,6 @@ impl FixedStructureTable Some(&CacheInsertionData::<1>::create_bind_group_layout( device, None, )), - Some(&CacheRequestBuffer::create_bind_group_layout(device)), ]; let insertion_pipeline_layout = @@ -175,15 +183,30 @@ impl FixedStructureTable cache: None, }); + let validation_shader_module = device.create_shader_module(include_table_wgsl!( + "./shaders/fixed_table/validate_insertion.wgsl" + )); + + let validation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("FixedStructureTable::validation_pass"), + layout: Some(&insertion_pipeline_layout), + module: &validation_shader_module, + entry_point: Some("validate_external"), + compilation_options: Default::default(), + cache: None, + }); + Self { size, pointers, pointers_bind_group, common_ressources, request_handler, + producer_id, indirect_buffer: IndirectBuffer1D::new(device), write_requests_pass, invalidation_pass, + validation_pass, insertion_pass, raytrace_bind_group, @@ -229,10 +252,10 @@ impl FixedStructureTable timestamp_writes: None, }); + write_requests_pass.set_pipeline(&self.write_requests_pass); write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]); write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]); - - write_requests_pass.set_pipeline(&self.write_requests_pass); + write_requests_pass.set_immediates(0, bytemuck::bytes_of(&self.producer_id)); write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0); } @@ -249,7 +272,6 @@ impl FixedStructureTable device: &wgpu::Device, encoder: &mut ScopeEncoder, insertion: &CacheInsertionData, - request: &CacheRequestBuffer, ) where [(); N * N * N]:, { @@ -268,7 +290,6 @@ impl FixedStructureTable insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]); insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]); - insertion_pass.set_bind_group(2, request.bind_group(), &[]); insertion_pass.set_pipeline(&self.insertion_pass); insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0); @@ -296,8 +317,35 @@ impl FixedStructureTable } } -impl CacheInvalidable for FixedStructureTable +impl CacheInvalidable for FixedStructureTable +where + [(); N * N * N]:, { + fn validate_insertion( + &mut self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) { + let workgroup_count_buffer = self.indirect_buffer.workgroup_count( + device, + encoder, + insertion.page_count_buffer(), + 256, + ); + + let mut validate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("FixedStructureTable::validate_pass"), + timestamp_writes: None, + }); + + validate_pass.set_bind_group(0, &self.pointers_bind_group, &[]); + validate_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]); + + validate_pass.set_pipeline(&self.validation_pass); + validate_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0); + } + fn invalidate( &mut self, encoder: &mut ScopeEncoder,