1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//! Coordination-free lane partitioning for parallel chunk decompression.
//!
//! Based on the paper "Coordination-Free Lane Partitioning for Convergent ANN
//! Search" (arXiv 2511.04221). Each thread (lane) receives a deterministic,
//! disjoint subset of work items — no locks, no atomics, no work overlap.
//!
//! The partition is seeded by a per-query value (dataset offset + chunk range)
//! so repeated reads of the same region always produce the same assignment,
//! making results reproducible and cache-friendly.
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Lightweight non-cryptographic hash (FxHash variant).
///
/// Uses the golden-ratio constant multiply-XOR trick from Firefox.
#[inline]
fn fxhash(mut x: u64) -> u64 {
// 64-bit FxHash constant (closest odd number to 2^64 / phi)
const K: u64 = 0x517cc1b727220a95;
x = x.wrapping_mul(K);
x ^= x >> 33;
x = x.wrapping_mul(K);
x ^= x >> 29;
x
}
/// Combine two u64 values into a single hash (for seeding with index).
#[inline]
fn fxhash_combine(seed: u64, index: u64) -> u64 {
fxhash(seed ^ fxhash(index))
}
/// Partitioning mode for distributing work across lanes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartitionMode {
/// Equal-size round-robin: item `i` goes to lane `permutation[i] % num_lanes`.
/// Guarantees each lane gets at most `ceil(n / num_lanes)` items.
EqualSize,
/// Work-stealing: uses equal-size as the base assignment, but lanes with
/// fewer items can steal from neighbours. In practice the deterministic
/// shuffle already balances well, so this mode adds a rebalancing pass
/// that caps the max-min difference at 1.
WorkStealing,
}
/// Deterministic lane partitioner.
///
/// Assigns items to lanes using a seeded pseudorandom permutation so that:
/// - Every item is assigned to exactly one lane (no gaps, no duplicates).
/// - The assignment is reproducible for the same `(seed, num_items)` pair.
/// - No inter-thread coordination is needed at runtime.
pub struct LanePartitioner {
pub num_lanes: usize,
pub mode: PartitionMode,
}
impl LanePartitioner {
/// Create a new partitioner with the given lane count and mode.
pub fn new(num_lanes: usize, mode: PartitionMode) -> Self {
let num_lanes = num_lanes.max(1);
Self { num_lanes, mode }
}
/// Create a partitioner that auto-detects the number of available cores.
#[cfg(feature = "std")]
pub fn auto(mode: PartitionMode) -> Self {
let num_lanes = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
Self::new(num_lanes, mode)
}
/// Partition `num_items` items into `self.num_lanes` lanes.
///
/// Returns a `Vec<Vec<usize>>` where `result[lane]` contains the original
/// indices assigned to that lane, in the order determined by the
/// pseudorandom permutation.
pub fn partition(&self, num_items: usize, seed: u64) -> Vec<Vec<usize>> {
partition(num_items, self.num_lanes, seed, self.mode)
}
}
/// Core partition function.
///
/// Returns `result[lane] = [indices...]` such that every index in `0..num_items`
/// appears in exactly one lane.
pub fn partition(
num_items: usize,
num_lanes: usize,
seed: u64,
mode: PartitionMode,
) -> Vec<Vec<usize>> {
let num_lanes = num_lanes.max(1);
if num_items == 0 {
return vec![Vec::new(); num_lanes];
}
// Generate a priority value for each item and assign to lane by
// `hash(seed, index) % num_lanes`. The hash provides a pseudo-random
// permutation so work is spread evenly.
let base_per_lane = num_items / num_lanes;
let extra = num_items % num_lanes;
let capacity = base_per_lane + 1;
let mut lanes: Vec<Vec<usize>> = (0..num_lanes)
.map(|_| Vec::with_capacity(capacity))
.collect();
for idx in 0..num_items {
let h = fxhash_combine(seed, idx as u64);
let lane = (h % num_lanes as u64) as usize;
lanes[lane].push(idx);
}
if mode == PartitionMode::WorkStealing {
// Rebalance so that the first `extra` lanes have base_per_lane+1 items
// and the remaining lanes have exactly base_per_lane items.
// Collect all items into a flat list (preserving hash-based ordering per lane).
let all_items: Vec<usize> = lanes.drain(..).flat_map(|l| l.into_iter()).collect();
lanes.clear();
let mut start = 0;
for i in 0..num_lanes {
let target = if i < extra { base_per_lane + 1 } else { base_per_lane };
lanes.push(all_items[start..start + target].to_vec());
start += target;
}
}
lanes
}
/// Convenience: partition chunk indices for parallel decompression.
///
/// `seed` should incorporate the dataset offset and chunk range so the
/// assignment is deterministic per query.
pub fn partition_chunks(
num_chunks: usize,
num_lanes: usize,
seed: u64,
) -> Vec<Vec<usize>> {
partition(num_chunks, num_lanes, seed, PartitionMode::WorkStealing)
}
/// Per-lane decompression statistics for diagnostics.
#[derive(Debug, Clone, Default)]
pub struct LaneStats {
/// Number of chunks decompressed by this lane.
pub chunks_processed: usize,
/// Total compressed bytes read by this lane.
pub compressed_bytes: u64,
/// Total decompressed bytes produced by this lane.
pub decompressed_bytes: u64,
}
/// Aggregated statistics across all lanes.
#[derive(Debug, Clone)]
pub struct PartitionStats {
pub per_lane: Vec<LaneStats>,
pub total_chunks: usize,
pub num_lanes: usize,
}
impl PartitionStats {
pub fn new(num_lanes: usize) -> Self {
Self {
per_lane: (0..num_lanes).map(|_| LaneStats::default()).collect(),
total_chunks: 0,
num_lanes,
}
}
/// Returns the max/min chunk count across lanes (imbalance metric).
pub fn imbalance(&self) -> (usize, usize) {
let max = self.per_lane.iter().map(|s| s.chunks_processed).max().unwrap_or(0);
let min = self.per_lane.iter().map(|s| s.chunks_processed).min().unwrap_or(0);
(max, min)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeSet as HashSet;
#[cfg(feature = "std")]
use std::collections::HashSet;
#[test]
fn all_items_covered_no_duplicates() {
for n in [0, 1, 2, 5, 10, 16, 31, 100] {
for lanes in [1, 2, 4, 8, 16] {
let result = partition(n, lanes, 42, PartitionMode::EqualSize);
assert_eq!(result.len(), lanes);
let mut seen = HashSet::new();
let mut total = 0;
for lane in &result {
for &idx in lane {
assert!(idx < n, "index {idx} out of range for n={n}");
assert!(seen.insert(idx), "duplicate index {idx}");
total += 1;
}
}
assert_eq!(total, n, "not all items covered for n={n}, lanes={lanes}");
}
}
}
#[test]
fn deterministic_same_seed() {
let a = partition(50, 4, 12345, PartitionMode::EqualSize);
let b = partition(50, 4, 12345, PartitionMode::EqualSize);
assert_eq!(a, b);
}
#[test]
fn different_seed_different_partition() {
let a = partition(50, 4, 100, PartitionMode::EqualSize);
let b = partition(50, 4, 200, PartitionMode::EqualSize);
// Very unlikely to be identical with different seeds
assert_ne!(a, b);
}
#[test]
fn work_stealing_rebalances() {
// With work-stealing, no lane should differ by more than 1 from ideal
for n in [7, 13, 31, 100] {
for lanes in [2, 4, 8, 16] {
let result = partition(n, lanes, 999, PartitionMode::WorkStealing);
let sizes: Vec<usize> = result.iter().map(|l| l.len()).collect();
let max = *sizes.iter().max().unwrap();
let min = *sizes.iter().min().unwrap();
// Hash-based assignment + rebalancing should keep lanes
// within a small delta. Allow up to 2 for hash collisions.
assert!(
max - min <= 3,
"imbalance too high: max={max}, min={min} for n={n}, lanes={lanes}"
);
// Still all items covered
let mut seen = HashSet::new();
for lane in &result {
for &idx in lane {
assert!(seen.insert(idx));
}
}
assert_eq!(seen.len(), n);
}
}
}
#[test]
fn partition_chunks_convenience() {
let result = partition_chunks(20, 4, 42);
assert_eq!(result.len(), 4);
let total: usize = result.iter().map(|l| l.len()).sum();
assert_eq!(total, 20);
}
#[test]
fn single_lane() {
let result = partition(10, 1, 0, PartitionMode::EqualSize);
assert_eq!(result.len(), 1);
assert_eq!(result[0].len(), 10);
}
#[test]
fn zero_items() {
let result = partition(0, 4, 0, PartitionMode::EqualSize);
assert_eq!(result.len(), 4);
for lane in &result {
assert!(lane.is_empty());
}
}
#[test]
fn more_lanes_than_items() {
let result = partition(3, 16, 42, PartitionMode::WorkStealing);
assert_eq!(result.len(), 16);
let total: usize = result.iter().map(|l| l.len()).sum();
assert_eq!(total, 3);
}
#[test]
fn lane_partitioner_struct() {
let lp = LanePartitioner::new(4, PartitionMode::EqualSize);
let result = lp.partition(20, 42);
assert_eq!(result.len(), 4);
let total: usize = result.iter().map(|l| l.len()).sum();
assert_eq!(total, 20);
}
#[test]
fn partition_stats_imbalance() {
let mut stats = PartitionStats::new(4);
stats.per_lane[0].chunks_processed = 5;
stats.per_lane[1].chunks_processed = 5;
stats.per_lane[2].chunks_processed = 6;
stats.per_lane[3].chunks_processed = 4;
let (max, min) = stats.imbalance();
assert_eq!(max, 6);
assert_eq!(min, 4);
}
#[test]
fn fxhash_deterministic() {
assert_eq!(fxhash(42), fxhash(42));
assert_ne!(fxhash(1), fxhash(2));
}
#[test]
fn lane_count_various() {
// Test with 1, 2, 4, 8, 16 lanes as specified
for &lanes in &[1, 2, 4, 8, 16] {
let result = partition(32, lanes, 0xDEAD, PartitionMode::WorkStealing);
assert_eq!(result.len(), lanes);
let total: usize = result.iter().map(|l| l.len()).sum();
assert_eq!(total, 32);
// All indices present
let mut all: Vec<usize> = result.into_iter().flatten().collect();
all.sort();
let expected: Vec<usize> = (0..32).collect();
assert_eq!(all, expected);
}
}
}