graph_sketch.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/graph_sketch.rs
1//! Buffered external vertex sketches with bounded cut-edge extraction.2//!3//! This implements a fixed-width GF(2) cutset-sampling instance of the4//! vertex-based transformation in Bender et al., *The Case for External Graph5//! Sketching*, sections 4.1–4.2 and 5:6//! <https://arxiv.org/html/2504.17563v1>. Each edge contributes only to its two7//! endpoint sketches; summing a vertex subset cancels every internal edge.8//! Four domain-seeded rows and 32 geometric sampling levels use9//! XOR edge IDs and XOR 64-bit checksums. A verified singleton yields an edge10//! crossing the requested cut. No adjacency list or complete edge set is stored.11//!12//! The stream is a strict simple undirected graph: insert an absent edge or13//! delete a present edge exactly once. The caller authorizes this against its14//! exact graph. As in the paper's transformation, this sketch cannot check edge15//! multiplicities. Insert/delete are the same GF(2) toggle; duplicates violate16//! the contract. Self loops, out-of-range vertices and oversized batches reject.17//!18//! Endpoint copies are sorted into bounded group batches. Two 2 KiB vertex19//! sketches occupy one aligned 4 KiB node. Each group has a durable 16-endpoint20//! update buffer; full buffers flush immediately, and remaining buffers drain21//! with explicit bounded progress. Counts, flushing cursors and immutable hash22//! configuration are retained with the two owning Minima collections.23//!24//! This supports cutset sampling, not the paper's complete Boruvka connectivity,25//! MST, sparsification or external sorting algorithms. Online bounded routing26//! is not the paper's unbounded external permutation and inherits no asymptotic27//! I/O optimality claim. NoSample means no verified singleton was found, not28//! that the cut is empty. Seeded XXH64 is noncryptographic; no malicious-input29//! probability guarantee is claimed. See `graph_sketch_provenance.md`.3031const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("graph_sketch.rs");3233use crate::hash::{XXH64_POLICY, Xxh64Word};34use crate::{Collection, Error, Fixed, NODE_BYTES, Result, Storage, Workspace};35use cdk_rsx_engine_nyxus::NyxusData;3637pub const GRAPH_MAX_VERTICES: u32 = 4096;38pub const GRAPH_ROWS: usize = 4;39pub const GRAPH_LEVELS: usize = 32;40pub const GRAPH_VERTEX_BYTES: usize = GRAPH_ROWS * GRAPH_LEVELS * 16;41pub const GRAPH_VERTICES_PER_GROUP: usize = NODE_BYTES / GRAPH_VERTEX_BYTES;42pub const GRAPH_MAX_BATCH: usize = 256;43pub const GRAPH_BUFFER_ENDPOINTS: usize = 16;44pub const GRAPH_MAX_FLUSH_GROUPS: u32 = 128;45pub const GRAPH_MAX_PREFIX_QUERIES: usize = 4096;46const MAX_GROUPS: usize = GRAPH_MAX_VERTICES as usize / GRAPH_VERTICES_PER_GROUP;47const BUFFER_STRIDE: u64 = 256;48const ENDPOINT_BYTES: usize = 12;49const BUFFER_BYTES: usize = GRAPH_BUFFER_ENDPOINTS * ENDPOINT_BYTES;50const CHECKSUM_DOMAIN: u64 = 0xa409_3822_299f_31d0;51const ROW_DOMAINS: [u64; GRAPH_ROWS] = [52 0x243f_6a88_85a3_08d3,53 0x1319_8a2e_0370_7344,54 0x082e_fa98_ec4e_6c89,55 0x4528_21e6_38d0_1377,56];57const _: () = {58 assert!(GRAPH_VERTEX_BYTES == 2048);59 assert!(GRAPH_VERTICES_PER_GROUP == 2);60 assert!(BUFFER_BYTES <= BUFFER_STRIDE as usize);61 assert!(NODE_BYTES.is_multiple_of(BUFFER_STRIDE as usize));62};6364pub const GRAPH_SKETCH_POLICY: [u8; 32] = crate::contract(65 "MinimaExternalVertexCutset/gf2/4x32/u32-pairs/v1",66 &[],67 &[crate::MINIMA_POLICY, SOURCE_POLICY, XXH64_POLICY],68);6970#[derive(Clone, Copy, Debug, PartialEq, Eq)]71pub enum EdgeChange {72 Insert,73 Delete,74}7576/// The caller must authorize each change against its exact simple graph.77#[derive(Clone, Copy, Debug, PartialEq, Eq)]78pub struct EdgeUpdate {79 pub u: u32,80 pub v: u32,81 pub change: EdgeChange,82}8384/// Transient caller-owned grouping scratch. Contents confer no retained access.85#[derive(Clone, Copy, Debug, Default)]86pub struct GraphBatchEntry {87 vertex: u32,88 edge: u64,89}9091/// Provider traffic excluding allocator initialization and zeroing. These are92/// byte/call counts, not metered pages or IC instructions. Buffers are read in93/// exact occupied spans and sketches are read/written as aligned 4 KiB nodes.94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]95pub struct GraphIoStats {96 pub endpoint_updates: u32,97 pub groups_flushed: u32,98 pub read_calls: u32,99 pub write_calls: u32,100 pub bytes_read: u64,101 pub bytes_written: u64,102}103104#[derive(Clone, Copy, Debug, PartialEq, Eq)]105pub struct GraphFlushProgress {106 pub done: bool,107 pub groups_visited: u32,108 pub pending_endpoints: u32,109 pub io: GraphIoStats,110}111112#[derive(Clone, Copy, Debug, PartialEq, Eq)]113pub enum CutSample {114 Edge {115 u: u32,116 v: u32,117 },118 /// Random sampling found no verified singleton. This is not an empty-cut119 /// certificate; callers may use an independently seeded sketch or exact data.120 NoSample,121}122#[derive(Clone, Copy, Debug, PartialEq, Eq)]123pub struct CutQueryResult {124 pub sample: CutSample,125 pub revision: u64,126 pub groups_read: u32,127 pub bytes_read: u64,128}129130/// Actual provider traffic for a batch of nested vertex-prefix cuts. This131/// counts shared reads once, rather than summing hypothetical scalar reads.132#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]133pub struct CutPrefixStats {134 pub queries: u32,135 pub revision: u64,136 pub groups_read: u32,137 pub bytes_read: u64,138}139140/// Borrowed query scratch, 2 KiB of transient inline XOR accumulators.141pub struct CutScratch {142 cells: [u64; GRAPH_VERTEX_BYTES / 8],143}144impl CutScratch {145 pub const fn new() -> Self {146 Self {147 cells: [0; GRAPH_VERTEX_BYTES / 8],148 }149 }150}151impl Default for CutScratch {152 fn default() -> Self {153 Self::new()154 }155}156157/// Move-only descriptor. Keep this and the shared Root in private root-attached158/// Nyxus Data. All counts/progress are inline; no Global Vec, provider, borrowed159/// workspace or callback is retained. Buffers and sketches own disjoint blocks160/// through the same Minima authority. Drop retires only these two owners.161#[repr(C)]162pub struct ExternalGraphSketch {163 sketches: Collection,164 buffers: Collection,165 seed: u64,166 revision: u64,167 vertices: u32,168 pending: u32,169 flush_cursor: u32,170 flushing: bool,171 counts: [u8; MAX_GROUPS],172}173// SAFETY: two retained Collection owners plus complete inline interpretation174// and bounded buffer progress. No transient or externally owned storage.175unsafe impl NyxusData for ExternalGraphSketch {176 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;177}178179impl ExternalGraphSketch {180 pub const CONTRACT: [u8; 32] = GRAPH_SKETCH_POLICY;181 /// Lazy payloads; at 4,096 vertices, maximum allocated sketch capacity is182 /// 8 MiB plus 512 KiB of update buffers, in separate 64 KiB owner blocks.183 pub fn new(storage: &mut dyn Storage, vertices: u32, seed: u64) -> Result<Self> {184 if vertices == 0 || vertices > GRAPH_MAX_VERTICES {185 return Err(Error::Capacity);186 }187 Ok(Self {188 sketches: Collection::new(storage)?,189 buffers: Collection::new(storage)?,190 seed,191 revision: 0,192 vertices,193 pending: 0,194 flush_cursor: 0,195 flushing: false,196 counts: [0; MAX_GROUPS],197 })198 }199 pub fn vertices(&self) -> u32 {200 self.vertices201 }202 pub fn seed(&self) -> u64 {203 self.seed204 }205 pub fn revision(&self) -> u64 {206 self.revision207 }208 pub fn pending_endpoints(&self) -> u32 {209 self.pending210 }211 pub fn allocated_blocks(&self) -> usize {212 self.sketches.block_count() + self.buffers.block_count()213 }214 fn groups(&self) -> u32 {215 self.vertices.div_ceil(GRAPH_VERTICES_PER_GROUP as u32)216 }217 fn validate(&self, storage: &dyn Storage) -> Result<()> {218 self.sketches.validate(storage)?;219 self.buffers.validate(storage)220 }221 pub fn batch_scratch_len(updates: usize) -> Result<usize> {222 if updates > GRAPH_MAX_BATCH {223 Err(Error::Capacity)224 } else {225 Ok(updates * 2)226 }227 }228229 /// Convenience bounded transient allocation (at most 512 16-byte entries).230 /// Use ingest_with_scratch to supply reusable scratch explicitly.231 pub fn ingest(232 &mut self,233 storage: &mut dyn Storage,234 updates: &[EdgeUpdate],235 w: &mut Workspace<'_>,236 ) -> Result<GraphIoStats> {237 let n = Self::batch_scratch_len(updates.len())?;238 let mut scratch = Vec::new();239 scratch.try_reserve_exact(n).map_err(|_| Error::Capacity)?;240 scratch.resize(n, GraphBatchEntry::default());241 self.ingest_with_scratch(storage, updates, &mut scratch, w)242 }243244 /// Preflight complete external bounds before mutation. Endpoint copies are245 /// permuted by group/vertex, appended as contiguous spans to durable group246 /// buffers and applied when full. Changes commute over GF(2); the caller's247 /// authoritative graph supplies the exactly-once validity of each toggle.248 /// Payload allocation may initialize a bounded prefix of the configured249 /// owner image; allocation cost is additional to returned traffic counts.250 pub fn ingest_with_scratch(251 &mut self,252 storage: &mut dyn Storage,253 updates: &[EdgeUpdate],254 scratch: &mut [GraphBatchEntry],255 w: &mut Workspace<'_>,256 ) -> Result<GraphIoStats> {257 let n = Self::batch_scratch_len(updates.len())?;258 if scratch.len() < n {259 return Err(Error::Bounds);260 }261 if self.flushing {262 return Err(Error::InvalidInput("Graph flush in progress"));263 }264 if updates265 .iter()266 .any(|e| e.u == e.v || e.u >= self.vertices || e.v >= self.vertices)267 {268 return Err(Error::InvalidInput(269 "Graph requires distinct in-range endpoints",270 ));271 }272 let next_revision = if updates.is_empty() {273 self.revision274 } else {275 self.revision.checked_add(1).ok_or(Error::Overflow)?276 };277 self.validate(storage)?;278 if updates.is_empty() {279 return Ok(GraphIoStats::default());280 }281 for (i, e) in updates.iter().enumerate() {282 let edge = edge_id(e.u, e.v);283 scratch[i * 2] = GraphBatchEntry { vertex: e.u, edge };284 scratch[i * 2 + 1] = GraphBatchEntry { vertex: e.v, edge };285 }286 let scratch = &mut scratch[..n];287 scratch.sort_unstable_by_key(|e| {288 (e.vertex / GRAPH_VERTICES_PER_GROUP as u32, e.vertex, e.edge)289 });290 self.buffers291 .ensure_nodes(292 storage,293 (u64::from(self.groups()) * BUFFER_STRIDE).div_ceil(NODE_BYTES as u64),294 )295 .expect("Graph admitted buffer allocation");296 let mut stats = GraphIoStats::default();297 let mut at = 0;298 while at < n {299 let group = scratch[at].vertex / GRAPH_VERTICES_PER_GROUP as u32;300 let mut end = at + 1;301 while end < n && scratch[end].vertex / GRAPH_VERTICES_PER_GROUP as u32 == group {302 end += 1;303 }304 while at < end {305 let count = self.counts[group as usize] as usize;306 let take = (GRAPH_BUFFER_ENDPOINTS - count).min(end - at);307 if count + take == GRAPH_BUFFER_ENDPOINTS {308 // A full buffer is consumed in this same synchronous call.309 // Keep its admitted suffix in scratch instead of appending310 // bytes that would immediately be read back and discarded.311 let mut updates = [0u8; BUFFER_BYTES];312 if count != 0 {313 self.buffers314 .read_at(315 storage,316 u64::from(group) * BUFFER_STRIDE,317 &mut updates[..count * ENDPOINT_BYTES],318 )319 .expect("Graph admitted update buffer read");320 stats.read_calls += 1;321 stats.bytes_read += (count * ENDPOINT_BYTES) as u64;322 }323 for (entry, encoded) in scratch[at..at + take]324 .iter()325 .zip(updates[count * ENDPOINT_BYTES..].chunks_exact_mut(ENDPOINT_BYTES))326 {327 entry.vertex.encode(&mut encoded[..4]);328 entry.edge.encode(&mut encoded[4..]);329 }330 self.apply_group(storage, group, &updates, w, &mut stats);331 self.counts[group as usize] = 0;332 self.pending -= count as u32;333 stats.endpoint_updates += take as u32;334 at += take;335 continue;336 }337 let bytes = &mut w.bytes_mut()[..take * ENDPOINT_BYTES];338 for (i, entry) in scratch[at..at + take].iter().enumerate() {339 let out = &mut bytes[i * ENDPOINT_BYTES..(i + 1) * ENDPOINT_BYTES];340 entry.vertex.encode(&mut out[..4]);341 entry.edge.encode(&mut out[4..]);342 }343 self.buffers344 .write_at(345 storage,346 u64::from(group) * BUFFER_STRIDE + (count * ENDPOINT_BYTES) as u64,347 &w.bytes()[..take * ENDPOINT_BYTES],348 )349 .expect("Graph admitted buffer append");350 self.counts[group as usize] += take as u8;351 self.pending += take as u32;352 stats.endpoint_updates += take as u32;353 stats.write_calls += 1;354 stats.bytes_written += (take * ENDPOINT_BYTES) as u64;355 at += take;356 }357 }358 self.revision = next_revision;359 Ok(stats)360 }361362 fn flush_group(363 &mut self,364 storage: &mut dyn Storage,365 group: u32,366 w: &mut Workspace<'_>,367 stats: &mut GraphIoStats,368 ) {369 let count = self.counts[group as usize] as usize;370 if count == 0 {371 return;372 }373 let mut updates = [0u8; BUFFER_BYTES];374 self.buffers375 .read_at(376 storage,377 u64::from(group) * BUFFER_STRIDE,378 &mut updates[..count * ENDPOINT_BYTES],379 )380 .expect("Graph admitted update buffer read");381 stats.read_calls += 1;382 stats.bytes_read += (count * ENDPOINT_BYTES) as u64;383 self.apply_group(storage, group, &updates[..count * ENDPOINT_BYTES], w, stats);384 self.counts[group as usize] = 0;385 self.pending -= count as u32;386 }387388 fn apply_group(389 &mut self,390 storage: &mut dyn Storage,391 group: u32,392 updates: &[u8],393 w: &mut Workspace<'_>,394 stats: &mut GraphIoStats,395 ) {396 self.sketches397 .ensure_nodes(storage, u64::from(group) + 1)398 .expect("Graph admitted sketch allocation");399 self.sketches400 .read_node(storage, u64::from(group), w)401 .expect("Graph admitted sketch read");402 for encoded in updates.chunks_exact(ENDPOINT_BYTES) {403 let vertex = u32::decode(&encoded[..4]).expect("Graph stored endpoint");404 let edge = u64::decode(&encoded[4..]).expect("Graph stored edge");405 let vertex_at = vertex as usize % GRAPH_VERTICES_PER_GROUP * GRAPH_VERTEX_BYTES;406 let hash = Xxh64Word::new(edge);407 let check = hash.hash(self.seed ^ CHECKSUM_DOMAIN);408 for (row, domain) in ROW_DOMAINS.iter().enumerate() {409 let last =410 (hash.hash(self.seed ^ domain).trailing_zeros() as usize).min(GRAPH_LEVELS - 1);411 for level in 0..=last {412 let at = vertex_at + (row * GRAPH_LEVELS + level) * 16;413 xor_word(&mut w.bytes_mut()[at..at + 8], edge);414 xor_word(&mut w.bytes_mut()[at + 8..at + 16], check);415 }416 }417 }418 self.sketches419 .write_node(storage, u64::from(group), w.bytes())420 .expect("Graph admitted sketch write");421 stats.groups_flushed += 1;422 stats.read_calls += 1;423 stats.write_calls += 1;424 stats.bytes_read += NODE_BYTES as u64;425 stats.bytes_written += NODE_BYTES as u64;426 }427428 /// Drain at most max_groups group positions, including empty positions.429 /// The cursor and occupied buffer counts persist across calls/reopen. No430 /// ingestion or extraction interleaves an unfinished drain. Each visited431 /// populated group uses one occupied-buffer read, one 4 KiB sketch read and432 /// one 4 KiB sketch write, plus bounded allocation initialization if needed.433 pub fn flush(434 &mut self,435 storage: &mut dyn Storage,436 max_groups: u32,437 w: &mut Workspace<'_>,438 ) -> Result<GraphFlushProgress> {439 if max_groups == 0 || max_groups > GRAPH_MAX_FLUSH_GROUPS {440 return Err(Error::Capacity);441 }442 self.validate(storage)?;443 if !self.flushing && self.pending == 0 {444 return Ok(GraphFlushProgress {445 done: true,446 groups_visited: 0,447 pending_endpoints: 0,448 io: GraphIoStats::default(),449 });450 }451 if !self.flushing {452 self.flushing = true;453 self.flush_cursor = 0;454 }455 let mut stats = GraphIoStats::default();456 let start = self.flush_cursor;457 let end = (start + max_groups).min(self.groups());458 while self.flush_cursor < end {459 self.flush_group(storage, self.flush_cursor, w, &mut stats);460 self.flush_cursor += 1;461 }462 if self.flush_cursor == self.groups() {463 self.flushing = false;464 assert_eq!(self.pending, 0);465 }466 Ok(GraphFlushProgress {467 done: !self.flushing,468 groups_visited: end - start,469 pending_endpoints: self.pending,470 io: stats,471 })472 }473474 /// Query one bounded vertex subset after all admitted updates are flushed.475 /// Vertices must be strictly sorted and within the configured <=4096476 /// universe. Each selected group is read once, using 2 KiB for one vertex477 /// or a complete 4 KiB node for both. Output is at most one cut edge.478 /// NoSample is inconclusive; a returned candidate is checksum/sampling479 /// verified and has exactly one endpoint in the requested vertex subset.480 pub fn sample_cut(481 &self,482 storage: &dyn Storage,483 vertices: &[u32],484 scratch: &mut CutScratch,485 w: &mut Workspace<'_>,486 ) -> Result<CutQueryResult> {487 if self.pending != 0 || self.flushing {488 return Err(Error::InvalidInput(489 "Graph updates must be flushed before extraction",490 ));491 }492 if vertices.len() > self.vertices as usize493 || vertices.last().is_some_and(|v| *v >= self.vertices)494 || vertices.windows(2).any(|p| p[0] >= p[1])495 {496 return Err(Error::InvalidInput(497 "Graph cut vertices must be strictly sorted and in range",498 ));499 }500 self.validate(storage)?;501 scratch.cells.fill(0);502 let mut at = 0;503 let mut groups_read = 0;504 let mut bytes_read = 0;505 while at < vertices.len() {506 let group = vertices[at] / GRAPH_VERTICES_PER_GROUP as u32;507 let first = vertices[at] as usize % GRAPH_VERTICES_PER_GROUP;508 let mut end = at + 1;509 while end < vertices.len() && vertices[end] / GRAPH_VERTICES_PER_GROUP as u32 == group {510 end += 1;511 }512 let count = end - at;513 if u64::from(group) < self.sketches.node_capacity() {514 let span = count * GRAPH_VERTEX_BYTES;515 self.sketches.read_at(516 storage,517 u64::from(group) * NODE_BYTES as u64 + (first * GRAPH_VERTEX_BYTES) as u64,518 &mut w.bytes_mut()[..span],519 )?;520 let (first, second) = w.bytes()[..span].split_at(GRAPH_VERTEX_BYTES);521 if count == 2 {522 // Combine both vertices before touching the accumulator:523 // exactly the same GF(2) sum, with one scratch update per524 // word instead of two. Both source vertices are consumed.525 for ((cell, a), b) in scratch526 .cells527 .iter_mut()528 .zip(first.chunks_exact(8))529 .zip(second.chunks_exact(8))530 {531 *cell ^= u64::from_le_bytes(a.try_into().unwrap())532 ^ u64::from_le_bytes(b.try_into().unwrap());533 }534 } else {535 for (cell, encoded) in scratch.cells.iter_mut().zip(first.chunks_exact(8)) {536 *cell ^= u64::from_le_bytes(encoded.try_into().unwrap());537 }538 }539 groups_read += 1;540 bytes_read += span as u64;541 }542 at = end;543 }544 Ok(CutQueryResult {545 sample: self.extract_cut(vertices, scratch),546 revision: self.revision,547 groups_read,548 bytes_read,549 })550 }551552 /// Sample cuts for nondecreasing prefix lengths of one strictly sorted553 /// vertex list. Repeats and zero are allowed. Results use the same row/level554 /// candidate order as `sample_cut` for each prefix, in request order.555 /// At most 4096 requests and equally many caller-owned output slots are556 /// admitted. Each source group is fetched once in its needed bounding span;557 /// each vertex is XORed once into the shared accumulator. No graph data or558 /// keys are cached between calls. Caller sorting/preparation is separate559 /// work that must be included in complete-call measurements.560 pub fn sample_prefixes(561 &self,562 storage: &dyn Storage,563 vertices: &[u32],564 prefixes: &[u32],565 output: &mut [CutSample],566 scratch: &mut CutScratch,567 w: &mut Workspace<'_>,568 ) -> Result<CutPrefixStats> {569 if self.pending != 0 || self.flushing {570 return Err(Error::InvalidInput(571 "Graph updates must be flushed before extraction",572 ));573 }574 if prefixes.len() > GRAPH_MAX_PREFIX_QUERIES || output.len() != prefixes.len() {575 return Err(Error::Capacity);576 }577 if vertices.len() > self.vertices as usize578 || vertices.last().is_some_and(|v| *v >= self.vertices)579 || vertices.windows(2).any(|p| p[0] >= p[1])580 || prefixes581 .last()582 .is_some_and(|n| *n as usize > vertices.len())583 || prefixes.windows(2).any(|p| p[0] > p[1])584 {585 return Err(Error::InvalidInput("Graph cut prefixes or vertices"));586 }587 self.validate(storage)?;588 let mut stats = CutPrefixStats {589 queries: prefixes.len() as u32,590 revision: self.revision,591 ..CutPrefixStats::default()592 };593 if prefixes.is_empty() {594 return Ok(stats);595 }596 scratch.cells.fill(0);597 let mut query = 0;598 while query < prefixes.len() && prefixes[query] == 0 {599 output[query] = CutSample::NoSample;600 query += 1;601 }602 let limit = *prefixes.last().unwrap() as usize;603 let mut at = 0;604 while at < limit {605 let group = vertices[at] / GRAPH_VERTICES_PER_GROUP as u32;606 let first = vertices[at] as usize % GRAPH_VERTICES_PER_GROUP;607 let mut end = at + 1;608 while end < limit && vertices[end] / GRAPH_VERTICES_PER_GROUP as u32 == group {609 end += 1;610 }611 let loaded = u64::from(group) < self.sketches.node_capacity();612 if loaded {613 let span = (end - at) * GRAPH_VERTEX_BYTES;614 self.sketches.read_at(615 storage,616 u64::from(group) * NODE_BYTES as u64 + (first * GRAPH_VERTEX_BYTES) as u64,617 &mut w.bytes_mut()[..span],618 )?;619 stats.groups_read += 1;620 stats.bytes_read += span as u64;621 }622 let group_start = at;623 while at < end {624 if loaded {625 let offset = (at - group_start) * GRAPH_VERTEX_BYTES;626 for (cell, encoded) in scratch627 .cells628 .iter_mut()629 .zip(w.bytes()[offset..offset + GRAPH_VERTEX_BYTES].chunks_exact(8))630 {631 *cell ^= u64::from_le_bytes(encoded.try_into().unwrap());632 }633 }634 at += 1;635 if query < prefixes.len() && prefixes[query] as usize == at {636 let sample = self.extract_cut(&vertices[..at], scratch);637 while query < prefixes.len() && prefixes[query] as usize == at {638 output[query] = sample;639 query += 1;640 }641 }642 }643 }644 Ok(stats)645 }646647 fn extract_cut(&self, vertices: &[u32], scratch: &CutScratch) -> CutSample {648 for (row, domain) in ROW_DOMAINS.iter().enumerate() {649 for level in 0..GRAPH_LEVELS {650 let at = (row * GRAPH_LEVELS + level) * 2;651 let edge = scratch.cells[at];652 let check = scratch.cells[at + 1];653 let hash = Xxh64Word::new(edge);654 if edge == 0 || hash.hash(self.seed ^ CHECKSUM_DOMAIN) != check {655 continue;656 }657 if hash.hash(self.seed ^ domain).trailing_zeros() < level as u32 {658 continue;659 }660 let u = (edge >> 32) as u32;661 let v = edge as u32;662 if u >= v || v >= self.vertices {663 continue;664 }665 if vertices.binary_search(&u).is_ok() ^ vertices.binary_search(&v).is_ok() {666 return CutSample::Edge { u, v };667 }668 }669 }670 CutSample::NoSample671 }672}673674fn edge_id(u: u32, v: u32) -> u64 {675 (u64::from(u.min(v)) << 32) | u64::from(u.max(v))676}677fn xor_word(bytes: &mut [u8], value: u64) {678 let next = u64::from_le_bytes(bytes.try_into().unwrap()) ^ value;679 bytes.copy_from_slice(&next.to_le_bytes());680}681682#[cfg(test)]683#[path = "graph_sketch_tests.rs"]684mod tests;