| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use crate::{ |
| 6 |
clubcard::ClubcardIndex, Clubcard, ClubcardIndexEntry, Equation, Filterable, Queryable, |
| 7 |
}; |
| 8 |
use rand::{thread_rng, Rng}; |
| 9 |
use std::collections::BTreeMap; |
| 10 |
use std::fmt; |
| 11 |
|
| 12 |
/// Marker type for checking that, for example, only Exact ribbons are passed to functions such as |
| 13 |
/// Clubcard::collect_exact_ribbons. |
| 14 |
pub struct Exact; |
| 15 |
|
| 16 |
/// A Ribbon Filter that encodes a one bit value for every element of the associated universe. |
| 17 |
pub type ExactRibbon<const W: usize, T> = Ribbon<W, T, Exact>; |
| 18 |
|
| 19 |
/// Marker type for checking that, for example, only Approximate ribbons are passed to functions such as |
| 20 |
/// Clubcard::collect_approximate_ribbons. |
| 21 |
pub struct Approximate; |
| 22 |
|
| 23 |
/// A Ribbon Filter that identifies a subset of a universe with a false positive rate of |
| 24 |
/// roughly |subset| / |universe|. |
| 25 |
pub type ApproximateRibbon<const W: usize, T> = Ribbon<W, T, Approximate>; |
| 26 |
|
| 27 |
/// A RibbonBuilder collects a set of items for insertion into a Ribbon. If the optional filter is |
| 28 |
/// provided, then only items that are contained in the filter will be inserted. |
| 29 |
pub struct RibbonBuilder<'a, const W: usize, T: Filterable<W>> { |
| 30 |
/// block id. |
| 31 |
id: Vec<u8>, |
| 32 |
/// items to be inserted. |
| 33 |
items: Vec<T>, |
| 34 |
/// filter for pruning insertions. |
| 35 |
filter: Option<&'a PartitionedRibbonFilter<W, T, Approximate>>, |
| 36 |
/// size of the universe that contains self.items |
| 37 |
universe_size: usize, |
| 38 |
/// Whether queries against this ribbon indicate membership in R (inverted = false) or |
| 39 |
/// membership in U \ R (inverted = true). |
| 40 |
inverted: bool, |
| 41 |
} |
| 42 |
|
| 43 |
impl<'a, const W: usize, T: Filterable<W>> RibbonBuilder<'a, W, T> { |
| 44 |
fn new( |
| 45 |
id: &[u8], |
| 46 |
filter: Option<&'a PartitionedRibbonFilter<W, T, Approximate>>, |
| 47 |
) -> RibbonBuilder<'a, W, T> { |
| 48 |
RibbonBuilder { |
| 49 |
id: AsRef::<[u8]>::as_ref(id).to_vec(), |
| 50 |
items: vec![], |
| 51 |
filter, |
| 52 |
universe_size: 0, |
| 53 |
inverted: false, |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
/// Queue `item` for insertion into the ribbon (if it is contained in the provided filter). |
| 58 |
pub fn insert(&mut self, item: T) { |
| 59 |
if let Some(filter) = self.filter { |
| 60 |
if filter.contains(&item) { |
| 61 |
self.items.push(item); |
| 62 |
} |
| 63 |
} else { |
| 64 |
self.items.push(item); |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
/// Set the size of the universe. This only needs to be called if you |
| 69 |
/// are constructing an ApproximateRibbon. |
| 70 |
pub fn set_universe_size(&mut self, universe_size: usize) { |
| 71 |
self.universe_size = universe_size; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
impl<'a, const W: usize, T: Filterable<W>> From<RibbonBuilder<'a, W, T>> |
| 76 |
for ApproximateRibbon<W, T> |
| 77 |
{ |
| 78 |
/// Denote the inserted set by R and the universe by U. |
| 79 |
/// The ribbon returned by ApproximateRibbon::from encodes a function f : U -> {0, 1} where |
| 80 |
/// f(x) = 0 if and only if x is in R union S where S is a (random) subset of U \ R of size |
| 81 |
/// ~|R|. In other words, the ribbon solves the approximate membership query problem with a |
| 82 |
/// false positive rate roughly 2^-r = |R| / (|U| - |R|). |
| 83 |
/// The size of this ribbon is proportional to r|R|. |
| 84 |
fn from(mut builder: RibbonBuilder<'a, W, T>) -> ApproximateRibbon<W, T> { |
| 85 |
assert!(builder.items.len() <= builder.universe_size); |
| 86 |
if builder.items.len() == builder.universe_size { |
| 87 |
ApproximateRibbon::new(&builder.id, 0, builder.universe_size, !builder.inverted) |
| 88 |
} else { |
| 89 |
let mut out = ApproximateRibbon::new( |
| 90 |
&builder.id, |
| 91 |
builder.items.len(), |
| 92 |
builder.universe_size, |
| 93 |
builder.inverted, |
| 94 |
); |
| 95 |
for item in builder.items.drain(..) { |
| 96 |
out.insert(item); |
| 97 |
} |
| 98 |
// Insertions should not fail for a homogeneous system. |
| 99 |
assert!(out.exceptions.is_empty()); |
| 100 |
out |
| 101 |
} |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
impl<'a, const W: usize, T: Filterable<W>> From<RibbonBuilder<'a, W, T>> for ExactRibbon<W, T> { |
| 106 |
/// Denote the inserted set by R and the universe by U. |
| 107 |
/// The ribbon returned by ExactRibbon::from encodes the function "f(x) = 0 iff x in R". The |
| 108 |
/// size of this ribbon is proportional to |U|. In the typical use case, the set U is the |
| 109 |
/// result of filtering a larger universe with a false positive rate of 2^-r. This allows for |
| 110 |
/// exact encoding of R-membership using a pair of filters of total size ~(r+2)|R|. |
| 111 |
fn from(mut builder: RibbonBuilder<'a, W, T>) -> ExactRibbon<W, T> { |
| 112 |
assert!(builder.universe_size == 0 || builder.universe_size == builder.items.len()); |
| 113 |
if let Some(filter) = builder.filter { |
| 114 |
if filter.block_is_empty(&builder.id) { |
| 115 |
// The approximate filter is empty, so it gives a definitive result on every |
| 116 |
// item and there's nothing to encode in the exact filter. |
| 117 |
return ExactRibbon::new(&builder.id, 0, filter.block_is_inverted(&builder.id)); |
| 118 |
} |
| 119 |
} |
| 120 |
let mut out = ExactRibbon::new(&builder.id, builder.items.len(), builder.inverted); |
| 121 |
// By inserting the included items first, we ensure that any exceptions that occur during |
| 122 |
// insertion are for excluded items. |
| 123 |
let mut excluded = vec![]; |
| 124 |
for item in builder.items.drain(..) { |
| 125 |
if item.included() { |
| 126 |
out.insert(item); |
| 127 |
} else { |
| 128 |
excluded.push(item); |
| 129 |
} |
| 130 |
} |
| 131 |
for item in excluded.drain(..) { |
| 132 |
out.insert(item); |
| 133 |
} |
| 134 |
out |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
/// A compact representation of a linear system AX = B |
| 139 |
pub struct Ribbon<const W: usize, T: Filterable<W>, ApproxOrExact> { |
| 140 |
/// A block identifier. Used to build an index for partitioned filters. |
| 141 |
id: Vec<u8>, |
| 142 |
/// The overhead. |
| 143 |
epsilon: f64, |
| 144 |
/// Equal to (1+epsilon) * |R| |
| 145 |
m: usize, |
| 146 |
/// The rank is round(-log2(subset_size / (universe_size - subset_size))) |
| 147 |
rank: usize, |
| 148 |
/// A linear system in which each equation has s in {0, ..., m-1} |
| 149 |
rows: Vec<Equation<W>>, |
| 150 |
/// A (typically short) list of items that failed insertion |
| 151 |
exceptions: Vec<T>, |
| 152 |
/// Whether queries against this ribbon indicate membership in R (inverted = false) or |
| 153 |
/// membership in U \ R (inverted = true). |
| 154 |
inverted: bool, |
| 155 |
/// Marker for whether this is an Approximate or an Exact filter. |
| 156 |
phantom: std::marker::PhantomData<ApproxOrExact>, |
| 157 |
} |
| 158 |
|
| 159 |
impl<const W: usize, T: Filterable<W>, ApproxOrExact> fmt::Display for Ribbon<W, T, ApproxOrExact> { |
| 160 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 161 |
write!( |
| 162 |
f, |
| 163 |
"ribbon({:?}): m: {}, rows: {}, rank: {}, exceptions: {}, epsilon: {}, overhead {}", |
| 164 |
self.id, |
| 165 |
self.m, |
| 166 |
self.rows.len(), |
| 167 |
self.rank, |
| 168 |
self.exceptions.len(), |
| 169 |
self.epsilon, |
| 170 |
(self.rows.iter().filter(|eq| eq.is_zero()).count() as f64 / (self.rows.len() as f64)) |
| 171 |
) |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
impl<const W: usize, T: Filterable<W>> ApproximateRibbon<W, T> { |
| 176 |
/// Construct an empty ribbon to encode a set R of size `subset_size` in a universe U of size |
| 177 |
/// `universe_size`. |
| 178 |
fn new(id: &[u8], subset_size: usize, universe_size: usize, inverted: bool) -> Self { |
| 179 |
assert!(subset_size <= universe_size); |
| 180 |
|
| 181 |
// TODO: Tune epsilon as a function of the inputs. Numerical experiments? |
| 182 |
let epsilon = 0.02; |
| 183 |
let m = ((1.0 + epsilon) * (subset_size as f64)).floor() as usize; |
| 184 |
|
| 185 |
let rank = if subset_size == 0 || 2 * subset_size >= universe_size { |
| 186 |
0 |
| 187 |
} else { |
| 188 |
(((universe_size - subset_size) as f64) / (subset_size as f64)) |
| 189 |
.log2() |
| 190 |
.floor() as usize |
| 191 |
}; |
| 192 |
|
| 193 |
Ribbon { |
| 194 |
id: AsRef::<[u8]>::as_ref(id).to_vec(), |
| 195 |
rows: vec![Equation::zero(); m], |
| 196 |
m, |
| 197 |
epsilon, |
| 198 |
rank, |
| 199 |
exceptions: vec![], |
| 200 |
inverted, |
| 201 |
phantom: std::marker::PhantomData, |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
impl<const W: usize, T: Filterable<W>> ExactRibbon<W, T> { |
| 207 |
/// Construct an empty ribbon to encode a set R of size `subset_size` in a universe U of size |
| 208 |
/// `universe_size`. |
| 209 |
fn new(id: &impl AsRef<[u8]>, size: usize, inverted: bool) -> Self { |
| 210 |
// TODO: Tune epsilon as a function of the inputs. Numerical experiments? |
| 211 |
let epsilon = 0.02; |
| 212 |
let m = ((1.0 + epsilon) * (size as f64)).floor() as usize; |
| 213 |
|
| 214 |
Ribbon { |
| 215 |
id: AsRef::<[u8]>::as_ref(id).to_vec(), |
| 216 |
rows: vec![Equation::zero(); m], |
| 217 |
m, |
| 218 |
epsilon, |
| 219 |
rank: 1, |
| 220 |
exceptions: vec![], |
| 221 |
inverted, |
| 222 |
phantom: std::marker::PhantomData, |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
impl<const W: usize, T: Filterable<W>, ApproxOrExact> Ribbon<W, T, ApproxOrExact> { |
| 228 |
/// Hash the item to an Equation and insert it into the system. |
| 229 |
fn insert(&mut self, item: T) -> bool { |
| 230 |
let mut eq = item.as_query(self.m); |
| 231 |
eq.b = if item.included() { 0 } else { 1 }; |
| 232 |
assert!(eq.is_zero() || eq.a[0] & 1 == 1); |
| 233 |
let rv = self.insert_equation(eq); |
| 234 |
if !rv { |
| 235 |
self.exceptions.push(item) |
| 236 |
} |
| 237 |
rv |
| 238 |
} |
| 239 |
|
| 240 |
/// Insert an equation into the system using Algorithm 1 from <https://arxiv.org/pdf/2103.02515> |
| 241 |
fn insert_equation(&mut self, mut eq: Equation<W>) -> bool { |
| 242 |
loop { |
| 243 |
if eq.is_zero() { |
| 244 |
return eq.b == 0; /* redundant (b=0) or inconsistent (b!=0) */ |
| 245 |
} |
| 246 |
if eq.s >= self.rows.len() { |
| 247 |
// TODO: could be smarter here |
| 248 |
self.rows.resize_with(eq.s + 1, Equation::zero); |
| 249 |
} |
| 250 |
let cur = &mut self.rows[eq.s]; |
| 251 |
if cur.is_zero() { |
| 252 |
*cur = eq; |
| 253 |
return true; /* inserted */ |
| 254 |
} |
| 255 |
eq.add(cur); |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
/// Solve the system using back-substitution. If this is a block in a larger system, the `tail` |
| 260 |
/// argument should be set to the the solution vector for the block to the right of this one. |
| 261 |
fn solve(&self, tail: &[u64]) -> Vec<u64> { |
| 262 |
let mut z = vec![0u64; ((self.rows.len() + 63) / 64) + tail.len()]; |
| 263 |
// insert tail into z starting at bit self.rows.len() |
| 264 |
let k = self.rows.len() / 64; |
| 265 |
let p = self.rows.len() % 64; |
| 266 |
if p == 0 { |
| 267 |
z[k..(tail.len() + k)].copy_from_slice(tail); |
| 268 |
} else { |
| 269 |
for i in 0..tail.len() { |
| 270 |
z[k + i] |= tail[i] << p; |
| 271 |
z[k + i + 1] = tail[i] >> (64 - p) |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
// Solve by back substitution |
| 276 |
for i in (0..self.rows.len()).rev() { |
| 277 |
let limb = i / 64; |
| 278 |
let pos = i % 64; |
| 279 |
let z_i = if self.rows[i].is_zero() { |
| 280 |
// Row i has a zero in column i, so we're free to choose. |
| 281 |
// TODO: We want multiple calls to solve() to give a different |
| 282 |
// solutions (when the system is suitably under-determined), |
| 283 |
// but it might be nice if this was deterministic. |
| 284 |
thread_rng().gen::<u8>() |
| 285 |
} else { |
| 286 |
// Let z' be the vector we get by setting bit i of z to z'_i. |
| 287 |
// Since z_i is zero, and row i has a one in column i, we have |
| 288 |
// row_i(z') = z'_i ^ row_i(z). |
| 289 |
// We want row_i(z') = b, so we must choose |
| 290 |
// z'_i = row_i(z) ^ b. |
| 291 |
self.rows[i].eval(&z) ^ self.rows[i].b |
| 292 |
}; |
| 293 |
z[limb] |= ((z_i & 1) as u64) << pos; |
| 294 |
} |
| 295 |
z |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
#[derive(Debug)] |
| 300 |
struct PartitionedRibbonFilterIndexEntry { |
| 301 |
offset: usize, |
| 302 |
m: usize, |
| 303 |
rank: usize, |
| 304 |
exceptions: Vec<Vec<u8>>, |
| 305 |
inverted: bool, |
| 306 |
} |
| 307 |
|
| 308 |
type PartitionedRibbonFilterIndex = |
| 309 |
BTreeMap</* block id */ Vec<u8>, PartitionedRibbonFilterIndexEntry>; |
| 310 |
|
| 311 |
/// A solution to a ribbon system, along with metadata necessary for querying it. |
| 312 |
struct PartitionedRibbonFilter<const W: usize, T: Filterable<W>, ApproxOrExact> { |
| 313 |
index: PartitionedRibbonFilterIndex, |
| 314 |
solution: Vec<Vec<u64>>, |
| 315 |
phantom: std::marker::PhantomData<T>, |
| 316 |
phantom2: std::marker::PhantomData<ApproxOrExact>, |
| 317 |
} |
| 318 |
|
| 319 |
impl<const W: usize, T: Filterable<W>, ApproxOrExact> fmt::Display |
| 320 |
for PartitionedRibbonFilter<W, T, ApproxOrExact> |
| 321 |
{ |
| 322 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 323 |
write!(f, "PartitionedRibbonFilter({:?})", self.index) |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
impl<const W: usize, T: Filterable<W>, Approximate> PartitionedRibbonFilter<W, T, Approximate> { |
| 328 |
fn block_is_empty(&self, block: &[u8]) -> bool { |
| 329 |
let Some(entry) = self.index.get(block) else { |
| 330 |
return false; |
| 331 |
}; |
| 332 |
entry.m == 0 |
| 333 |
} |
| 334 |
|
| 335 |
fn block_is_inverted(&self, block: &[u8]) -> bool { |
| 336 |
let Some(entry) = self.index.get(block) else { |
| 337 |
return false; |
| 338 |
}; |
| 339 |
entry.inverted |
| 340 |
} |
| 341 |
|
| 342 |
/// Check if this filter contains the given item in the given block. |
| 343 |
fn contains(&self, item: &T) -> bool { |
| 344 |
let Some(entry) = self.index.get(item.block()) else { |
| 345 |
return false; |
| 346 |
}; |
| 347 |
let result = (|| { |
| 348 |
// Empty blocks do not contain anything, |
| 349 |
// despite having inner product 0 with everything. |
| 350 |
if entry.m == 0 { |
| 351 |
return false; |
| 352 |
} |
| 353 |
let mut eq = item.as_query(entry.m); |
| 354 |
eq.s += entry.offset; |
| 355 |
for i in 0..entry.rank { |
| 356 |
if eq.eval(&self.solution[i]) != 0 { |
| 357 |
return false; |
| 358 |
} |
| 359 |
} |
| 360 |
for exception in &entry.exceptions { |
| 361 |
if exception == item.discriminant() { |
| 362 |
return false; |
| 363 |
} |
| 364 |
} |
| 365 |
true |
| 366 |
})(); |
| 367 |
result ^ entry.inverted |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
impl<const W: usize, T: Filterable<W>, ApproxOrExact> From<Vec<Ribbon<W, T, ApproxOrExact>>> |
| 372 |
for PartitionedRibbonFilter<W, T, ApproxOrExact> |
| 373 |
{ |
| 374 |
fn from( |
| 375 |
mut blocks: Vec<Ribbon<W, T, ApproxOrExact>>, |
| 376 |
) -> PartitionedRibbonFilter<W, T, ApproxOrExact> { |
| 377 |
// Sort ribbons by descending rank (descending simplifies indexing). |
| 378 |
blocks.sort_unstable_by(|a, b| b.rank.cmp(&a.rank)); |
| 379 |
|
| 380 |
// Solve the (block) system. |
| 381 |
// The blocks are sorted by descending rank. We need at least one solution (i.e. column |
| 382 |
// vector) per block, but we need no more than i solutions for a block of rank i. |
| 383 |
// Concretely, suppose the ranks are [4, 2, 1, 0]. Then our solution can look like |
| 384 |
// block 0: | | | | |
| 385 |
// block 1: | | 0 0 |
| 386 |
// block 2: | 0 0 0 |
| 387 |
// block 3: | 0 0 0 |
| 388 |
// Since we serialize the block identifiers, offsets, and ranks in the final filter, we |
| 389 |
// don't need to encode the zeros. |
| 390 |
let mut solution = vec![]; |
| 391 |
let max_rank = blocks.first().map_or(0, |first| first.rank); |
| 392 |
for i in 0..max_rank { |
| 393 |
// Back substitution across blocks. |
| 394 |
let mut tail = vec![]; |
| 395 |
if max_rank > 1 { |
| 396 |
// randomizing the tail increases the odds that the solutions will be distinct |
| 397 |
tail.push(thread_rng().gen::<u64>()); |
| 398 |
} |
| 399 |
for j in (0..blocks.len()).rev() { |
| 400 |
if blocks[j].rank > i { |
| 401 |
tail = blocks[j].solve(&tail); |
| 402 |
} |
| 403 |
} |
| 404 |
while let Some(0) = tail.last() { |
| 405 |
tail.pop(); |
| 406 |
} |
| 407 |
solution.push(tail); |
| 408 |
} |
| 409 |
|
| 410 |
// construct the index---a map from a block identifier to that |
| 411 |
// block's offset in the solution vector. |
| 412 |
let mut index = PartitionedRibbonFilterIndex::new(); |
| 413 |
let mut offset = 0; |
| 414 |
for block in &blocks { |
| 415 |
let exceptions = block |
| 416 |
.exceptions |
| 417 |
.iter() |
| 418 |
.map(|x| x.discriminant().to_vec()) |
| 419 |
.collect(); |
| 420 |
index.insert( |
| 421 |
block.id.clone(), |
| 422 |
PartitionedRibbonFilterIndexEntry { |
| 423 |
offset, |
| 424 |
m: block.m, |
| 425 |
rank: block.rank, |
| 426 |
exceptions, |
| 427 |
inverted: block.inverted, |
| 428 |
}, |
| 429 |
); |
| 430 |
offset += block.rows.len(); |
| 431 |
} |
| 432 |
|
| 433 |
PartitionedRibbonFilter { |
| 434 |
index, |
| 435 |
solution, |
| 436 |
phantom: std::marker::PhantomData, |
| 437 |
phantom2: std::marker::PhantomData, |
| 438 |
} |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
/// A pair of ribbon filters that, together, solve the exact membership query problem. |
| 443 |
pub struct ClubcardBuilder<const W: usize, T: Filterable<W>> { |
| 444 |
/// An approximate membership query filter to whittle down the universe |
| 445 |
/// to a managable size. |
| 446 |
approx_filter: Option<PartitionedRibbonFilter<W, T, Approximate>>, |
| 447 |
/// An exact membership query filter to confirm membership in R for items that |
| 448 |
/// pass through the approximate filter. |
| 449 |
exact_filter: Option<PartitionedRibbonFilter<W, T, Exact>>, |
| 450 |
} |
| 451 |
|
| 452 |
impl<const W: usize, T: Filterable<W>> Default for ClubcardBuilder<W, T> { |
| 453 |
fn default() -> Self { |
| 454 |
ClubcardBuilder { |
| 455 |
approx_filter: None, |
| 456 |
exact_filter: None, |
| 457 |
} |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
impl<const W: usize, T: Filterable<W>> ClubcardBuilder<W, T> { |
| 462 |
pub fn new() -> Self { |
| 463 |
ClubcardBuilder::default() |
| 464 |
} |
| 465 |
|
| 466 |
pub fn new_approx_builder(&self, block: &[u8]) -> RibbonBuilder<'static, W, T> { |
| 467 |
assert!(self.approx_filter.is_none()); |
| 468 |
RibbonBuilder::new(block, None) |
| 469 |
} |
| 470 |
|
| 471 |
pub fn new_exact_builder<'a>(&'a self, block: &[u8]) -> RibbonBuilder<'a, W, T> { |
| 472 |
RibbonBuilder::new(block, self.approx_filter.as_ref()) |
| 473 |
} |
| 474 |
|
| 475 |
pub fn collect_approx_ribbons(&mut self, ribbons: Vec<ApproximateRibbon<W, T>>) { |
| 476 |
self.approx_filter = Some(PartitionedRibbonFilter::from(ribbons)); |
| 477 |
} |
| 478 |
|
| 479 |
pub fn collect_exact_ribbons(&mut self, ribbons: Vec<Ribbon<W, T, Exact>>) { |
| 480 |
self.exact_filter = Some(PartitionedRibbonFilter::from(ribbons)); |
| 481 |
} |
| 482 |
|
| 483 |
pub fn build<U: Queryable<W>>( |
| 484 |
self, |
| 485 |
universe: U::UniverseMetadata, |
| 486 |
partition: U::PartitionMetadata, |
| 487 |
) -> Clubcard<W, U::UniverseMetadata, U::PartitionMetadata> { |
| 488 |
let mut index: ClubcardIndex = BTreeMap::new(); |
| 489 |
|
| 490 |
assert!(self.approx_filter.is_some()); |
| 491 |
let approx_filter = self.approx_filter.unwrap(); |
| 492 |
for (block, entry) in approx_filter.index { |
| 493 |
let meta = ClubcardIndexEntry { |
| 494 |
approx_filter_offset: entry.offset, |
| 495 |
approx_filter_m: entry.m, |
| 496 |
approx_filter_rank: entry.rank, |
| 497 |
exact_filter_offset: 0, |
| 498 |
exact_filter_m: 0, |
| 499 |
inverted: entry.inverted, |
| 500 |
exceptions: entry.exceptions, |
| 501 |
}; |
| 502 |
index.insert(block, meta); |
| 503 |
} |
| 504 |
|
| 505 |
assert!(self.exact_filter.is_some()); |
| 506 |
let mut exact_filter = self.exact_filter.unwrap(); |
| 507 |
for (block, entry) in exact_filter.index { |
| 508 |
assert!(entry.rank == 1); |
| 509 |
let meta = index.get_mut(&block).unwrap(); |
| 510 |
meta.exact_filter_offset = entry.offset; |
| 511 |
meta.exact_filter_m = entry.m; |
| 512 |
assert!(meta.inverted == entry.inverted); |
| 513 |
meta.exceptions.extend(entry.exceptions); |
| 514 |
} |
| 515 |
|
| 516 |
assert!(exact_filter.solution.len() == 1); |
| 517 |
let exact_filter = exact_filter.solution.pop().unwrap(); |
| 518 |
|
| 519 |
Clubcard { |
| 520 |
universe, |
| 521 |
partition, |
| 522 |
index, |
| 523 |
approx_filter: approx_filter.solution, |
| 524 |
exact_filter, |
| 525 |
} |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
#[cfg(test)] |
| 530 |
mod tests { |
| 531 |
use crate::builder::*; |
| 532 |
use crate::*; |
| 533 |
use rand::distributions::{Distribution, Uniform}; |
| 534 |
use rand::Rng; |
| 535 |
|
| 536 |
// Construct the equation a(x) = x_i |
| 537 |
fn std_eq<const W: usize>(i: usize) -> Equation<W> { |
| 538 |
let mut a = [0u64; W]; |
| 539 |
a[0] = 1; |
| 540 |
Equation::homogeneous(i, a) |
| 541 |
} |
| 542 |
|
| 543 |
// Construct an random aligned equation using the given distribution for s. |
| 544 |
fn rand<const W: usize>(s_dist: &impl Distribution<usize>) -> Equation<W> { |
| 545 |
let mut rng = rand::thread_rng(); |
| 546 |
let s = s_dist.sample(&mut rng); |
| 547 |
let mut a = [0u64; W]; |
| 548 |
for a_i in a.iter_mut() { |
| 549 |
*a_i = rng.gen(); |
| 550 |
} |
| 551 |
a[0] |= 1; |
| 552 |
Equation::inhomogeneous(s, a, rng.gen::<u8>() & 1) |
| 553 |
} |
| 554 |
|
| 555 |
impl<const W: usize> AsQuery<W> for Equation<W> { |
| 556 |
fn as_query(&self, _m: usize) -> Equation<W> { |
| 557 |
self.clone() |
| 558 |
} |
| 559 |
|
| 560 |
fn block(&self) -> &[u8] { |
| 561 |
&[] |
| 562 |
} |
| 563 |
|
| 564 |
fn discriminant(&self) -> &[u8] { |
| 565 |
unsafe { std::mem::transmute(&self.a[..]) } |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
impl<const W: usize> Filterable<W> for Equation<W> { |
| 570 |
fn included(&self) -> bool { |
| 571 |
self.b == 0 |
| 572 |
} |
| 573 |
} |
| 574 |
|
| 575 |
impl<const W: usize> Queryable<W> for Equation<W> { |
| 576 |
type UniverseMetadata = (); |
| 577 |
type PartitionMetadata = (); |
| 578 |
|
| 579 |
fn in_universe(&self, _meta: &Self::UniverseMetadata) -> bool { |
| 580 |
true |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
#[test] |
| 585 |
fn test_solve_identity() { |
| 586 |
let n = 1024; |
| 587 |
let mut builder = RibbonBuilder::new(&[], None); |
| 588 |
for i in 0usize..n { |
| 589 |
let eq: Equation<1> = std_eq(i); |
| 590 |
builder.insert(eq); |
| 591 |
} |
| 592 |
let ribbon = ExactRibbon::from(builder); |
| 593 |
let filter = PartitionedRibbonFilter::from(vec![ribbon]); |
| 594 |
for i in 0usize..n { |
| 595 |
let eq: Equation<1> = std_eq(i); |
| 596 |
assert!(eq.eval(&filter.solution[0]) == 0); |
| 597 |
} |
| 598 |
} |
| 599 |
|
| 600 |
#[test] |
| 601 |
fn test_solve_empty() { |
| 602 |
let builder = RibbonBuilder::<4, Equation<4>>::new(&[0], None); |
| 603 |
let ribbon = ApproximateRibbon::from(builder); |
| 604 |
let filter = PartitionedRibbonFilter::from(vec![ribbon]); |
| 605 |
assert!(!filter.contains(&std_eq(0))); |
| 606 |
} |
| 607 |
|
| 608 |
#[test] |
| 609 |
fn test_solve_random() { |
| 610 |
let n = 1024; |
| 611 |
const W: usize = 2; |
| 612 |
let mut r = Ribbon::<W, Equation<W>, Exact>::new(&[0], n, false); |
| 613 |
let mut s_dist = Uniform::new(0, r.m); |
| 614 |
let mut eqs = Vec::with_capacity(n); |
| 615 |
for _ in 0..n { |
| 616 |
let eq = rand(&mut s_dist); |
| 617 |
eqs.push(eq.clone()); |
| 618 |
r.insert(eq); |
| 619 |
} |
| 620 |
let x = r.solve(&[]); |
| 621 |
for eq in &eqs { |
| 622 |
assert!(eq.eval(&x) == eq.b); |
| 623 |
} |
| 624 |
} |
| 625 |
|
| 626 |
#[test] |
| 627 |
fn test_total_approx_filter() { |
| 628 |
// test that approximate filters that encode R=U are encoded |
| 629 |
// as a zero-length solution vector with m=0 and inverted=true |
| 630 |
// in the metadata. |
| 631 |
let n = 1024; |
| 632 |
let mut approx_builder = RibbonBuilder::new(&[], None); |
| 633 |
approx_builder.set_universe_size(n); |
| 634 |
for i in 0usize..n { |
| 635 |
let eq: Equation<1> = std_eq(i); |
| 636 |
approx_builder.insert(eq); |
| 637 |
} |
| 638 |
|
| 639 |
let approx_ribbon = ApproximateRibbon::from(approx_builder); |
| 640 |
let approx_filter = PartitionedRibbonFilter::from(vec![approx_ribbon]); |
| 641 |
let approx_index_entry = approx_filter |
| 642 |
.index |
| 643 |
.get(&vec![]) |
| 644 |
.expect("should have metadata"); |
| 645 |
assert!(approx_index_entry.m == 0); |
| 646 |
assert!(approx_index_entry.rank == 0); |
| 647 |
assert!(approx_index_entry.exceptions.is_empty()); |
| 648 |
assert!(approx_index_entry.inverted); |
| 649 |
for i in 0usize..n { |
| 650 |
let eq = std_eq(i); |
| 651 |
assert!(approx_filter.contains(&eq)); |
| 652 |
} |
| 653 |
assert!(approx_filter.solution.len() == 0); |
| 654 |
|
| 655 |
let mut exact_builder = RibbonBuilder::new(&[], Some(&approx_filter)); |
| 656 |
for i in 0usize..n { |
| 657 |
let mut eq = std_eq(i); |
| 658 |
eq.b = 0; |
| 659 |
exact_builder.insert(eq); |
| 660 |
} |
| 661 |
let exact_ribbon = ExactRibbon::from(exact_builder); |
| 662 |
let exact_filter = PartitionedRibbonFilter::from(vec![exact_ribbon]); |
| 663 |
let exact_index_entry = exact_filter |
| 664 |
.index |
| 665 |
.get(&vec![]) |
| 666 |
.expect("should have metadata"); |
| 667 |
assert!(exact_index_entry.m == 0); |
| 668 |
assert!(exact_index_entry.rank == 1); |
| 669 |
assert!(exact_index_entry.exceptions.is_empty()); |
| 670 |
assert!(exact_index_entry.inverted); |
| 671 |
for i in 0usize..n { |
| 672 |
let eq = std_eq(i); |
| 673 |
assert!(exact_filter.contains(&eq)); |
| 674 |
} |
| 675 |
assert!(exact_filter.solution.len() == 1); |
| 676 |
assert!(exact_filter.solution[0].len() == 0); |
| 677 |
} |
| 678 |
|
| 679 |
#[test] |
| 680 |
fn test_rank_0_approx_filter() { |
| 681 |
let n = 1024; |
| 682 |
let mut builder = RibbonBuilder::new(&[], None); |
| 683 |
builder.set_universe_size(n); |
| 684 |
for i in 0usize..768 { |
| 685 |
let eq: Equation<1> = std_eq(i); |
| 686 |
builder.insert(eq); |
| 687 |
} |
| 688 |
|
| 689 |
let ribbon = ApproximateRibbon::from(builder); |
| 690 |
let filter = PartitionedRibbonFilter::from(vec![ribbon]); |
| 691 |
let entry = filter.index.get(&vec![]).expect("should have metadata"); |
| 692 |
assert!(entry.rank == 0); |
| 693 |
assert!(!entry.inverted); |
| 694 |
assert!(filter.solution.len() == 0); |
| 695 |
for i in 0usize..n { |
| 696 |
let eq = std_eq(i); |
| 697 |
assert!(filter.contains(&eq)); |
| 698 |
} |
| 699 |
} |
| 700 |
} |