Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / networklocation / wps_harvest / src / sort.rs
sort.rs276 lines · 8.4 KiBRaw
| 1 | //! External sort over record shards. |
| 2 | //! |
| 3 | //! The record sets are far larger than memory — a planet WiFi store is order a billion |
| 4 | //! observations — so records are buffered into fixed-size runs, each sorted in memory and |
| 5 | //! spilled, then merged with a heap. `wps_build` consumes the merged stream directly, so the |
| 6 | //! sorted whole is never materialized. |
| 7 | //! |
| 8 | //! Sorting is by key first and then by a total order over the rest of the record, so equal |
| 9 | //! keys arrive adjacent (which is what lets the merge see every observation of a beacon at |
| 10 | //! once) and the output is deterministic regardless of input order or run boundaries. |
| 11 | |
| 12 | use std::cmp::Ordering; |
| 13 | use std::collections::BinaryHeap; |
| 14 | use std::fs::File; |
| 15 | use std::io::{self, BufReader, BufWriter}; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | |
| 18 | use crate::record::{Record, RecordReader, RecordWriter}; |
| 19 | |
| 20 | /// Total order: key, then accuracy (best first), then the rest, for determinism. |
| 21 | pub fn record_order(a: &Record, b: &Record) -> Ordering { |
| 22 | a.key |
| 23 | .cmp(&b.key) |
| 24 | .then(a.accuracy_m.cmp(&b.accuracy_m)) |
| 25 | .then(a.lat_e8.cmp(&b.lat_e8)) |
| 26 | .then(a.lon_e8.cmp(&b.lon_e8)) |
| 27 | .then(a.source.cmp(&b.source)) |
| 28 | } |
| 29 | |
| 30 | /// Buffers records into sorted runs on disk, then merges them. |
| 31 | pub struct ExternalSort { |
| 32 | dir: PathBuf, |
| 33 | run_capacity: usize, |
| 34 | buf: Vec<Record>, |
| 35 | runs: Vec<PathBuf>, |
| 36 | total: u64, |
| 37 | } |
| 38 | |
| 39 | impl ExternalSort { |
| 40 | /// `run_capacity` records are held in memory at a time; each full buffer becomes one run |
| 41 | /// file in `dir`. At the default 4 M that is about 160 MB of buffer. |
| 42 | pub fn new(dir: &Path, run_capacity: usize) -> io::Result<ExternalSort> { |
| 43 | std::fs::create_dir_all(dir)?; |
| 44 | Ok(ExternalSort { |
| 45 | dir: dir.to_path_buf(), |
| 46 | run_capacity: run_capacity.max(1), |
| 47 | buf: Vec::with_capacity(run_capacity.min(1 << 20)), |
| 48 | runs: Vec::new(), |
| 49 | total: 0, |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | /// Add one record. |
| 54 | pub fn push(&mut self, r: Record) -> io::Result<()> { |
| 55 | self.buf.push(r); |
| 56 | self.total += 1; |
| 57 | if self.buf.len() >= self.run_capacity { |
| 58 | self.spill()?; |
| 59 | } |
| 60 | Ok(()) |
| 61 | } |
| 62 | |
| 63 | /// Records accepted so far. |
| 64 | pub fn len(&self) -> u64 { |
| 65 | self.total |
| 66 | } |
| 67 | |
| 68 | /// Whether nothing has been pushed. |
| 69 | pub fn is_empty(&self) -> bool { |
| 70 | self.total == 0 |
| 71 | } |
| 72 | |
| 73 | fn spill(&mut self) -> io::Result<()> { |
| 74 | if self.buf.is_empty() { |
| 75 | return Ok(()); |
| 76 | } |
| 77 | self.buf.sort_unstable_by(record_order); |
| 78 | let path = self.dir.join(format!("run-{:05}.shard", self.runs.len())); |
| 79 | let mut w = RecordWriter::new(BufWriter::new(File::create(&path)?)); |
| 80 | for r in &self.buf { |
| 81 | w.push(r)?; |
| 82 | } |
| 83 | let _ = w.finish()?; |
| 84 | self.buf.clear(); |
| 85 | self.runs.push(path); |
| 86 | Ok(()) |
| 87 | } |
| 88 | |
| 89 | /// Spill the tail and return a merged, globally sorted stream. |
| 90 | pub fn finish(mut self) -> io::Result<Merge> { |
| 91 | self.spill()?; |
| 92 | Merge::open(self.runs, self.total) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | struct Head { |
| 97 | record: Record, |
| 98 | which: usize, |
| 99 | } |
| 100 | |
| 101 | impl PartialEq for Head { |
| 102 | fn eq(&self, other: &Self) -> bool { |
| 103 | record_order(&self.record, &other.record) == Ordering::Equal && self.which == other.which |
| 104 | } |
| 105 | } |
| 106 | impl Eq for Head {} |
| 107 | impl Ord for Head { |
| 108 | fn cmp(&self, other: &Self) -> Ordering { |
| 109 | // BinaryHeap is a max-heap; invert so the smallest record comes out first. `which` |
| 110 | // breaks ties so the merge is stable across runs. |
| 111 | record_order(&other.record, &self.record).then(other.which.cmp(&self.which)) |
| 112 | } |
| 113 | } |
| 114 | impl PartialOrd for Head { |
| 115 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 116 | Some(self.cmp(other)) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// A k-way merge over sorted run files. Deletes the runs when dropped. |
| 121 | pub struct Merge { |
| 122 | readers: Vec<RecordReader<BufReader<File>>>, |
| 123 | heap: BinaryHeap<Head>, |
| 124 | paths: Vec<PathBuf>, |
| 125 | remaining: u64, |
| 126 | } |
| 127 | |
| 128 | impl Merge { |
| 129 | fn open(paths: Vec<PathBuf>, total: u64) -> io::Result<Merge> { |
| 130 | let mut readers = Vec::with_capacity(paths.len()); |
| 131 | let mut heap = BinaryHeap::with_capacity(paths.len()); |
| 132 | for (which, p) in paths.iter().enumerate() { |
| 133 | let mut rd = RecordReader::new(BufReader::new(File::open(p)?)); |
| 134 | if let Some(record) = rd.next()? { |
| 135 | heap.push(Head { record, which }); |
| 136 | } |
| 137 | readers.push(rd); |
| 138 | } |
| 139 | Ok(Merge { readers, heap, paths, remaining: total }) |
| 140 | } |
| 141 | |
| 142 | /// Total records the merge will yield. |
| 143 | pub fn len(&self) -> u64 { |
| 144 | self.remaining |
| 145 | } |
| 146 | |
| 147 | /// Whether the merge is empty. |
| 148 | pub fn is_empty(&self) -> bool { |
| 149 | self.remaining == 0 |
| 150 | } |
| 151 | |
| 152 | /// Next record in sorted order. |
| 153 | pub fn next(&mut self) -> io::Result<Option<Record>> { |
| 154 | let Some(Head { record, which }) = self.heap.pop() else { |
| 155 | return Ok(None); |
| 156 | }; |
| 157 | let reader = self |
| 158 | .readers |
| 159 | .get_mut(which) |
| 160 | .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "merge run index out of range"))?; |
| 161 | if let Some(next) = reader.next()? { |
| 162 | self.heap.push(Head { record: next, which }); |
| 163 | } |
| 164 | self.remaining = self.remaining.saturating_sub(1); |
| 165 | Ok(Some(record)) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | impl Drop for Merge { |
| 170 | fn drop(&mut self) { |
| 171 | for p in &self.paths { |
| 172 | let _ = std::fs::remove_file(p); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | #[cfg(test)] |
| 178 | mod tests { |
| 179 | use super::*; |
| 180 | use crate::record::{ALT_UNKNOWN, Source}; |
| 181 | |
| 182 | struct TempDir(PathBuf); |
| 183 | impl TempDir { |
| 184 | fn new(tag: &str) -> TempDir { |
| 185 | let p = std::env::temp_dir().join(format!("wpssort-{tag}-{}", std::process::id())); |
| 186 | let _ = std::fs::remove_dir_all(&p); |
| 187 | std::fs::create_dir_all(&p).unwrap(); |
| 188 | TempDir(p) |
| 189 | } |
| 190 | } |
| 191 | impl Drop for TempDir { |
| 192 | fn drop(&mut self) { |
| 193 | let _ = std::fs::remove_dir_all(&self.0); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn rec(key: u128, acc: u16) -> Record { |
| 198 | Record { |
| 199 | key, |
| 200 | lat_e8: 37_00000000, |
| 201 | lon_e8: -122_00000000, |
| 202 | accuracy_m: acc, |
| 203 | altitude_m: ALT_UNKNOWN, |
| 204 | source: Source::Gsloc, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | fn drain(mut m: Merge) -> Vec<Record> { |
| 209 | let mut out = Vec::new(); |
| 210 | while let Some(r) = m.next().unwrap() { |
| 211 | out.push(r); |
| 212 | } |
| 213 | out |
| 214 | } |
| 215 | |
| 216 | #[test] |
| 217 | fn sorts_across_many_runs() { |
| 218 | let d = TempDir::new("runs"); |
| 219 | // A tiny run capacity forces plenty of spills, which is the case worth testing. |
| 220 | let mut s = ExternalSort::new(&d.0, 7).unwrap(); |
| 221 | let mut state = 99u64; |
| 222 | let mut expect = Vec::new(); |
| 223 | for _ in 0..500 { |
| 224 | state = state.wrapping_mul(6364136223846793005).wrapping_add(1); |
| 225 | let r = rec((state >> 20) as u128, (state & 0xFF) as u16); |
| 226 | expect.push(r); |
| 227 | s.push(r).unwrap(); |
| 228 | } |
| 229 | assert_eq!(s.len(), 500); |
| 230 | let got = drain(s.finish().unwrap()); |
| 231 | expect.sort_unstable_by(record_order); |
| 232 | assert_eq!(got, expect); |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn equal_keys_come_out_adjacent_and_best_accuracy_first() { |
| 237 | let d = TempDir::new("dupes"); |
| 238 | let mut s = ExternalSort::new(&d.0, 3).unwrap(); |
| 239 | for acc in [400u16, 12, 90, 12] { |
| 240 | s.push(rec(42, acc)).unwrap(); |
| 241 | } |
| 242 | s.push(rec(7, 5)).unwrap(); |
| 243 | s.push(rec(99, 5)).unwrap(); |
| 244 | let got = drain(s.finish().unwrap()); |
| 245 | assert_eq!(got.iter().map(|r| r.key).collect::<Vec<_>>(), vec![7, 42, 42, 42, 42, 99]); |
| 246 | assert_eq!( |
| 247 | got[1..5].iter().map(|r| r.accuracy_m).collect::<Vec<_>>(), |
| 248 | vec![12, 12, 90, 400] |
| 249 | ); |
| 250 | } |
| 251 | |
| 252 | #[test] |
| 253 | fn run_files_are_cleaned_up() { |
| 254 | let d = TempDir::new("cleanup"); |
| 255 | let mut s = ExternalSort::new(&d.0, 2).unwrap(); |
| 256 | for i in 0..10 { |
| 257 | s.push(rec(i, 1)).unwrap(); |
| 258 | } |
| 259 | let m = s.finish().unwrap(); |
| 260 | drop(drain(m)); |
| 261 | let leftover: Vec<_> = std::fs::read_dir(&d.0) |
| 262 | .unwrap() |
| 263 | .filter_map(|e| e.ok()) |
| 264 | .filter(|e| e.file_name().to_string_lossy().starts_with("run-")) |
| 265 | .collect(); |
| 266 | assert!(leftover.is_empty(), "run files were left behind: {leftover:?}"); |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn an_empty_sort_merges_to_nothing() { |
| 271 | let d = TempDir::new("empty"); |
| 272 | let s = ExternalSort::new(&d.0, 16).unwrap(); |
| 273 | assert!(s.is_empty()); |
| 274 | assert!(drain(s.finish().unwrap()).is_empty()); |
| 275 | } |
| 276 | } |