Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / store.rs

store.rs449 lines · 16.2 KiBRaw
1//! Writer for the `WPSDB2` store format read by
2//! `networklocation/src/main/rust/src/wpsdb.rs`.
3//!
4//! The layout is documented there and duplicated here only as far as the constants; the two
5//! must stay in step. `wpsdb.rs`'s own fixture tests build a store with a transcription of
6//! this writer, so a divergence shows up as a failure on the reader side too.
7//!
8//! ```text
9//! 0 magic "WPSDB2\0\0" 8 B
10//! 8 key_kind:u8, universe_bits:u8, payload_kind:u8, l:u8
11//! 12 select_sample_log2:u8, reserved:u8 * 3
12//! 16 n:u64
13//! 24 high_len_bits:u64
14//! 32 high_len:u64
15//! 40 high[high_len]
16//! zeros_len:u64, zeros[zeros_len]
17//! low_len:u64, low[low_len]
18//! payload_len:u64, payload[payload_len]
19//! ```
20//!
21//! Nothing is held in memory proportional to the record count except the `select0` sample
22//! table (a few MB at a billion records): `high`, `low` and `payload` are streamed to scratch
23//! files as the sorted records arrive and concatenated at the end.
24
25use std::fs::File;
26use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
27use std::path::{Path, PathBuf};
28
29use crate::record::{ALT_UNKNOWN, Record, LAT_E8_MIN, LON_E8_MIN};
30
31const MAGIC: &[u8; 8] = b"WPSDB2\x00\x00";
32
33const LAT_BITS: u32 = 35;
34const LON_BITS: u32 = 36;
35const ACC_BITS: u32 = 16;
36const ALT_BITS: u32 = 16;
37
38/// Payload: lat(35) | lon(36) | accuracy(16) | altitude(16), LSB-first — 103 bits.
39/// Altitude is metres biased by 32768 (two's complement in 16 bits), 0 meaning "unknown".
40/// Kind-1 stores (87 bits, no altitude) remain readable; new builds always write kind 2.
41const PAYLOAD_LATLON_E8_ACC16_ALT16: u8 = 2;
42
43/// Cap on the Elias-Fano low width, so a low value always fits the reader's `u64`. Exceeding
44/// it would only ever lengthen `high`, so the cap costs nothing at real record counts.
45pub(crate) const MAX_L: u8 = 64;
46
47/// Default `select0` sampling stride, as a power of two. 4096 bounds the in-block scan of a
48/// `select0` to 4096 bit tests while keeping the table small.
49pub const DEFAULT_SAMPLE_LOG2: u8 = 12;
50
51/// Which keyspace a store indexes. Recorded in the header for diagnostics; the reader keys
52/// its behaviour off `universe_bits`.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum KeyKind {
55 /// 48-bit BSSID.
56 Wifi = 1,
57 /// 84-bit packed cell identity.
58 Cell = 2,
59}
60
61/// Elias-Fano low-part width for `n` keys drawn from a `universe_bits`-wide universe.
62///
63/// The bucket space is `2^(universe_bits - l)` bits of `high`, so a small `l` over a wide
64/// universe is catastrophic rather than merely wasteful: at `n = 0` the unguarded formula
65/// gives `l = 0` and asks for `2^48` bits of padding. An empty or tiny set therefore pins `l`
66/// as wide as it is allowed to go, which makes the bucket space as small as possible.
67pub fn choose_l(universe_bits: u8, n: u64) -> u8 {
68 if n == 0 {
69 return universe_bits.min(MAX_L);
70 }
71 let u = 1u128 << universe_bits;
72 let mut l = 0u8;
73 while l < MAX_L && (u >> (l as u32 + 1)) >= n as u128 {
74 l += 1;
75 }
76 l
77}
78
79// --------------------------------------------------------------------------- bit writer
80struct BitWriter<W: Write> {
81 inner: W,
82 cur: u8,
83 used: u32,
84 bits: u64,
85}
86
87impl<W: Write> BitWriter<W> {
88 fn new(inner: W) -> BitWriter<W> {
89 BitWriter { inner, cur: 0, used: 0, bits: 0 }
90 }
91
92 fn push(&mut self, v: u64, nbits: u32) -> io::Result<()> {
93 for k in 0..nbits {
94 self.push_bit((v >> k) & 1 == 1)?;
95 }
96 Ok(())
97 }
98
99 fn push_bit(&mut self, set: bool) -> io::Result<()> {
100 if set {
101 self.cur |= 1 << self.used;
102 }
103 self.used += 1;
104 self.bits += 1;
105 if self.used == 8 {
106 self.inner.write_all(&[self.cur])?;
107 self.cur = 0;
108 self.used = 0;
109 }
110 Ok(())
111 }
112
113 /// Flush the partial final byte and return `(bits written, bytes written)`.
114 fn finish(mut self) -> io::Result<(u64, u64)> {
115 let mut bytes = self.bits / 8;
116 if self.used > 0 {
117 self.inner.write_all(&[self.cur])?;
118 bytes += 1;
119 }
120 self.inner.flush()?;
121 Ok((self.bits, bytes))
122 }
123}
124
125// --------------------------------------------------------------------------- scratch
126/// A scratch file that deletes itself.
127struct Scratch {
128 path: PathBuf,
129}
130
131impl Scratch {
132 fn create(dir: &Path, name: &str) -> io::Result<(Scratch, File)> {
133 std::fs::create_dir_all(dir)?;
134 let path = dir.join(name);
135 let file = File::create(&path)?;
136 Ok((Scratch { path }, file))
137 }
138}
139
140impl Drop for Scratch {
141 fn drop(&mut self) {
142 let _ = std::fs::remove_file(&self.path);
143 }
144}
145
146fn append_file(out: &mut impl Write, path: &Path) -> io::Result<u64> {
147 let mut f = BufReader::new(File::open(path)?);
148 io::copy(&mut f, out)
149}
150
151// --------------------------------------------------------------------------- writer
152/// Write a `WPSDB2` store.
153///
154/// `records` must be **sorted by key and free of duplicate keys**, and must yield exactly `n`
155/// items. Both are invariants of the Elias-Fano index rather than preferences: an out-of-order
156/// key produces a bitvector that decodes to a different key, and a duplicate produces two
157/// records the reader can only ever reach one of. They are checked, not assumed.
158///
159/// Records are consumed as a stream of results so the caller can read them straight off disk;
160/// nothing proportional to `n` is held in memory. `scratch_dir` holds three intermediate files
161/// whose combined size is roughly that of the finished store; they are removed on both success
162/// and failure.
163pub fn write_store<I>(
164 out_path: &Path,
165 scratch_dir: &Path,
166 kind: KeyKind,
167 universe_bits: u8,
168 n: u64,
169 sample_log2: u8,
170 records: I,
171) -> io::Result<u64>
172where
173 I: IntoIterator<Item = io::Result<Record>>,
174{
175 if universe_bits == 0 || universe_bits > 127 {
176 return Err(invalid(format!("universe_bits {universe_bits} out of range")));
177 }
178 if !(6..=20).contains(&sample_log2) {
179 return Err(invalid(format!("select sample stride 2^{sample_log2} out of range")));
180 }
181 let l = choose_l(universe_bits, n);
182 if (universe_bits as u32).saturating_sub(l as u32) > 64 {
183 return Err(invalid("bucket space wider than 64 bits".to_string()));
184 }
185 let buckets = 1u64 << (universe_bits as u32 - l as u32);
186
187 let (high_s, high_f) = Scratch::create(scratch_dir, "wpsdb.high")?;
188 let (low_s, low_f) = Scratch::create(scratch_dir, "wpsdb.low")?;
189 let (pay_s, pay_f) = Scratch::create(scratch_dir, "wpsdb.payload")?;
190
191 let mut high = BitWriter::new(BufWriter::new(high_f));
192 let mut low = BitWriter::new(BufWriter::new(low_f));
193 let mut payload = BitWriter::new(BufWriter::new(pay_f));
194
195 // `zeros[b]` = number of zero bits in high[0 .. b << sample_log2). Accumulated while the
196 // bitvector streams past, so `high` never has to be resident to build the index.
197 let sample_mask = (1u64 << sample_log2) - 1;
198 let mut zeros: Vec<u64> = vec![0];
199 let mut zero_count = 0u64;
200 let mut high_bits = 0u64;
201
202 let emit_high = |bit: bool,
203 high: &mut BitWriter<BufWriter<File>>,
204 zeros: &mut Vec<u64>,
205 zero_count: &mut u64,
206 high_bits: &mut u64|
207 -> io::Result<()> {
208 high.push_bit(bit)?;
209 if !bit {
210 *zero_count += 1;
211 }
212 *high_bits += 1;
213 if (*high_bits & sample_mask) == 0 {
214 zeros.push(*zero_count);
215 }
216 Ok(())
217 };
218
219 let mut written = 0u64;
220 let mut prev_bucket = 0u64;
221 let mut prev_key: Option<u128> = None;
222
223 for r in records {
224 let r = r?;
225 if written == n {
226 return Err(invalid(format!("more than the declared {n} records")));
227 }
228 if r.key >= (1u128 << universe_bits) {
229 return Err(invalid(format!("key {:#x} outside the {universe_bits}-bit universe", r.key)));
230 }
231 if let Some(p) = prev_key {
232 if r.key <= p {
233 return Err(invalid(format!(
234 "records must be strictly ascending by key; {:#x} follows {:#x}",
235 r.key, p
236 )));
237 }
238 }
239 if !r.in_range() {
240 return Err(invalid(format!("record {:#x} has out-of-range coordinates", r.key)));
241 }
242 prev_key = Some(r.key);
243
244 let bucket = (r.key >> l) as u64;
245 for _ in prev_bucket..bucket {
246 emit_high(false, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
247 }
248 emit_high(true, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
249 prev_bucket = bucket;
250
251 let lo = if l == 0 { 0 } else { (r.key & ((1u128 << l) - 1)) as u64 };
252 low.push(lo, l as u32)?;
253
254 payload.push((r.lat_e8 - LAT_E8_MIN) as u64, LAT_BITS)?;
255 payload.push((r.lon_e8 - LON_E8_MIN) as u64, LON_BITS)?;
256 payload.push(u64::from(r.accuracy_m), ACC_BITS)?;
257 // Altitude biased so "unknown" (i16::MIN) lands on 0 and real metres on 1..=65535.
258 payload.push((i64::from(r.altitude_m) - i64::from(ALT_UNKNOWN)) as u64, ALT_BITS)?;
259
260 written += 1;
261 }
262 if written != n {
263 return Err(invalid(format!("declared {n} records but got {written}")));
264 }
265
266 // Pad the bucket space out so `select0(bucket - 1)` resolves for every reachable bucket,
267 // including ones past the last key.
268 for _ in prev_bucket..buckets {
269 emit_high(false, &mut high, &mut zeros, &mut zero_count, &mut high_bits)?;
270 }
271
272 let (high_len_bits, high_len) = high.finish()?;
273 let (_, low_len) = low.finish()?;
274 let (_, payload_len) = payload.finish()?;
275
276 debug_assert_eq!(high_len_bits, n + buckets);
277 if zeros.len() as u64 != (high_len_bits >> sample_log2) + 1 {
278 return Err(invalid("select0 sample table has the wrong length".to_string()));
279 }
280
281 let mut out = BufWriter::new(File::create(out_path)?);
282 out.write_all(MAGIC)?;
283 out.write_all(&[kind as u8, universe_bits, PAYLOAD_LATLON_E8_ACC16_ALT16, l])?;
284 out.write_all(&[sample_log2, 0, 0, 0])?;
285 out.write_all(&n.to_le_bytes())?;
286 out.write_all(&high_len_bits.to_le_bytes())?;
287 out.write_all(&high_len.to_le_bytes())?;
288 let copied = append_file(&mut out, &high_s.path)?;
289 debug_assert_eq!(copied, high_len);
290 out.write_all(&((zeros.len() * 8) as u64).to_le_bytes())?;
291 for z in &zeros {
292 out.write_all(&z.to_le_bytes())?;
293 }
294 out.write_all(&low_len.to_le_bytes())?;
295 let _ = append_file(&mut out, &low_s.path)?;
296 out.write_all(&payload_len.to_le_bytes())?;
297 let _ = append_file(&mut out, &pay_s.path)?;
298 out.flush()?;
299
300 let mut f = out.into_inner().map_err(|e| e.into_error())?;
301 let size = f.seek(SeekFrom::End(0))?;
302 Ok(size)
303}
304
305fn invalid(msg: String) -> io::Error {
306 io::Error::new(io::ErrorKind::InvalidData, msg)
307}
308
309// --------------------------------------------------------------------------- self-test
310/// Sequential LSB-first bit reader over one section of the store.
311struct BitStream<R: Read> {
312 inner: R,
313 acc: u64,
314 have: u32,
315}
316
317impl<R: Read> BitStream<R> {
318 fn new(inner: R) -> BitStream<R> {
319 BitStream { inner, acc: 0, have: 0 }
320 }
321
322 fn take_small(&mut self, n: u32) -> io::Result<u64> {
323 while self.have < n {
324 let mut b = [0u8; 1];
325 self.inner.read_exact(&mut b)?;
326 self.acc |= (b[0] as u64) << self.have;
327 self.have += 8;
328 }
329 let v = if n == 64 { self.acc } else { self.acc & ((1u64 << n) - 1) };
330 self.acc >>= n;
331 self.have -= n;
332 Ok(v)
333 }
334
335 /// Next `n` bits (`n <= 64`). Taken in 32-bit chunks so the accumulator cannot overflow.
336 fn take(&mut self, n: u32) -> io::Result<u64> {
337 let mut out = 0u64;
338 let mut taken = 0u32;
339 while taken < n {
340 let chunk = (n - taken).min(32);
341 out |= self.take_small(chunk)? << taken;
342 taken += chunk;
343 }
344 Ok(out)
345 }
346
347 fn take_bit(&mut self) -> io::Result<bool> {
348 Ok(self.take_small(1)? == 1)
349 }
350}
351
352fn section_reader(path: &Path, offset: u64) -> io::Result<BufReader<File>> {
353 let mut f = File::open(path)?;
354 let _ = f.seek(SeekFrom::Start(offset))?;
355 Ok(BufReader::with_capacity(1 << 16, f))
356}
357
358/// Read a finished store back and check every record resolves to what was written.
359///
360/// The store's own writer is not reused: this walks the Elias-Fano bitvector directly instead
361/// of using `select0`, so a shared misunderstanding between two `index()` implementations
362/// cannot hide here. It is also the only check that the bytes on disk are what the writer
363/// believed it wrote.
364///
365/// `expected` must yield the same records, in the same order, that were written. All four
366/// sections are streamed in parallel — `idx` only ever increases, so `low` and `payload` are
367/// consumed strictly in order — which keeps this O(1) in memory over a store of any size.
368pub fn verify_store<I>(path: &Path, expected: I) -> io::Result<u64>
369where
370 I: IntoIterator<Item = io::Result<Record>>,
371{
372 let mut head = [0u8; 40];
373 File::open(path)?.read_exact(&mut head)?;
374 if &head[0..8] != MAGIC {
375 return Err(invalid("bad magic".to_string()));
376 }
377 let universe_bits = head[9];
378 let l = head[11] as u32;
379 let n = u64::from_le_bytes(head[16..24].try_into().map_err(|_| invalid("short header".into()))?);
380 let high_len_bits =
381 u64::from_le_bytes(head[24..32].try_into().map_err(|_| invalid("short header".into()))?);
382 let high_len =
383 u64::from_le_bytes(head[32..40].try_into().map_err(|_| invalid("short header".into()))?);
384
385 // Section offsets follow from the lengths; the file has no offset table.
386 let mut len_buf = [0u8; 8];
387 let read_u64_at = |off: u64, buf: &mut [u8; 8]| -> io::Result<u64> {
388 let mut f = File::open(path)?;
389 let _ = f.seek(SeekFrom::Start(off))?;
390 f.read_exact(buf)?;
391 Ok(u64::from_le_bytes(*buf))
392 };
393 let zeros_len_off = 40 + high_len;
394 let zeros_len = read_u64_at(zeros_len_off, &mut len_buf)?;
395 let low_len_off = zeros_len_off + 8 + zeros_len;
396 let low_len = read_u64_at(low_len_off, &mut len_buf)?;
397 let payload_len_off = low_len_off + 8 + low_len;
398 let _payload_len = read_u64_at(payload_len_off, &mut len_buf)?;
399
400 let mut high = BitStream::new(section_reader(path, 40)?);
401 let mut low = BitStream::new(section_reader(path, low_len_off + 8)?);
402 let mut payload = BitStream::new(section_reader(path, payload_len_off + 8)?);
403
404 let mut want = expected.into_iter();
405 let mut idx = 0u64;
406 let mut p = 0u64;
407 while p < high_len_bits && idx < n {
408 if high.take_bit()? {
409 let upper = (p - idx) as u128;
410 let lo = if l == 0 { 0 } else { low.take(l)? as u128 };
411 let key = (upper << l) | lo;
412
413 let lat = payload.take(LAT_BITS)? as i64 + LAT_E8_MIN;
414 let lon = payload.take(LON_BITS)? as i64 + LON_E8_MIN;
415 let acc = payload.take(ACC_BITS)? as u16;
416 let alt = payload.take(ALT_BITS)? as i64 + i64::from(ALT_UNKNOWN);
417
418 let w = want
419 .next()
420 .transpose()?
421 .ok_or_else(|| invalid(format!("store holds more than the {idx} expected")))?;
422 if key != w.key || lat != w.lat_e8 || lon != w.lon_e8 || acc != w.accuracy_m {
423 return Err(invalid(format!(
424 "record {idx} mismatch: got ({key:#x}, {lat}, {lon}, {acc}), \
425 want ({:#x}, {}, {}, {})",
426 w.key, w.lat_e8, w.lon_e8, w.accuracy_m
427 )));
428 }
429 if alt != i64::from(w.altitude_m) {
430 return Err(invalid(format!(
431 "record {idx} altitude mismatch: got {alt}, want {}",
432 w.altitude_m
433 )));
434 }
435 if key >= (1u128 << universe_bits) {
436 return Err(invalid(format!("record {idx} key escapes the universe")));
437 }
438 idx += 1;
439 }
440 p += 1;
441 }
442 if idx != n {
443 return Err(invalid(format!("recovered {idx} of {n} records from the bitvector")));
444 }
445 if want.next().transpose()?.is_some() {
446 return Err(invalid(format!("expected more records than the {n} the store holds")));
447 }
448 Ok(n)
449}