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

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

sort.rs284 lines · 8.6 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
12use std::cmp::Ordering;
13use std::collections::BinaryHeap;
14use std::fs::File;
15use std::io::{self, BufReader, BufWriter};
16use std::path::{Path, PathBuf};
17
18use crate::record::{Record, RecordReader, RecordWriter};
19
20/// Total order: key, then accuracy (best first), then the rest, for determinism.
21pub 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.
31pub struct ExternalSort {
32 dir: PathBuf,
33 run_capacity: usize,
34 buf: Vec<Record>,
35 runs: Vec<PathBuf>,
36 total: u64,
37}
38
39impl 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
96struct Head {
97 record: Record,
98 which: usize,
99}
100
101impl 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}
106impl Eq for Head {}
107impl 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}
114impl 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.
121pub struct Merge {
122 readers: Vec<RecordReader<BufReader<File>>>,
123 heap: BinaryHeap<Head>,
124 paths: Vec<PathBuf>,
125 remaining: u64,
126}
127
128impl 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().transpose()? {
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, or `Ok(None)` when the merge is drained.
153 fn next_record(&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::other("merge run index out of range"))?;
161 if let Some(next) = reader.next().transpose()? {
162 self.heap.push(Head { record: next, which });
163 }
164 self.remaining = self.remaining.saturating_sub(1);
165 Ok(Some(record))
166 }
167}
168
169impl Iterator for Merge {
170 type Item = io::Result<Record>;
171
172 fn next(&mut self) -> Option<Self::Item> {
173 self.next_record().transpose()
174 }
175}
176
177impl Drop for Merge {
178 fn drop(&mut self) {
179 for p in &self.paths {
180 let _ = std::fs::remove_file(p);
181 }
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188 use crate::record::{Source, ALT_UNKNOWN};
189
190 struct TempDir(PathBuf);
191 impl TempDir {
192 fn new(tag: &str) -> TempDir {
193 let p = std::env::temp_dir().join(format!("wpssort-{tag}-{}", std::process::id()));
194 let _ = std::fs::remove_dir_all(&p);
195 std::fs::create_dir_all(&p).unwrap();
196 TempDir(p)
197 }
198 }
199 impl Drop for TempDir {
200 fn drop(&mut self) {
201 let _ = std::fs::remove_dir_all(&self.0);
202 }
203 }
204
205 fn rec(key: u128, acc: u16) -> Record {
206 Record {
207 key,
208 lat_e8: 37_00000000,
209 lon_e8: -122_00000000,
210 accuracy_m: acc,
211 altitude_m: ALT_UNKNOWN,
212 source: Source::Gsloc,
213 }
214 }
215
216 fn drain(m: Merge) -> Vec<Record> {
217 let mut out = Vec::new();
218 for r in m {
219 out.push(r.unwrap());
220 }
221 out
222 }
223
224 #[test]
225 fn sorts_across_many_runs() {
226 let d = TempDir::new("runs");
227 // A tiny run capacity forces plenty of spills, which is the case worth testing.
228 let mut s = ExternalSort::new(&d.0, 7).unwrap();
229 let mut state = 99u64;
230 let mut expect = Vec::new();
231 for _ in 0..500 {
232 state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
233 let r = rec((state >> 20) as u128, (state & 0xFF) as u16);
234 expect.push(r);
235 s.push(r).unwrap();
236 }
237 assert_eq!(s.len(), 500);
238 let got = drain(s.finish().unwrap());
239 expect.sort_unstable_by(record_order);
240 assert_eq!(got, expect);
241 }
242
243 #[test]
244 fn equal_keys_come_out_adjacent_and_best_accuracy_first() {
245 let d = TempDir::new("dupes");
246 let mut s = ExternalSort::new(&d.0, 3).unwrap();
247 for acc in [400u16, 12, 90, 12] {
248 s.push(rec(42, acc)).unwrap();
249 }
250 s.push(rec(7, 5)).unwrap();
251 s.push(rec(99, 5)).unwrap();
252 let got = drain(s.finish().unwrap());
253 assert_eq!(got.iter().map(|r| r.key).collect::<Vec<_>>(), vec![7, 42, 42, 42, 42, 99]);
254 assert_eq!(
255 got[1..5].iter().map(|r| r.accuracy_m).collect::<Vec<_>>(),
256 vec![12, 12, 90, 400]
257 );
258 }
259
260 #[test]
261 fn run_files_are_cleaned_up() {
262 let d = TempDir::new("cleanup");
263 let mut s = ExternalSort::new(&d.0, 2).unwrap();
264 for i in 0..10 {
265 s.push(rec(i, 1)).unwrap();
266 }
267 let m = s.finish().unwrap();
268 drop(drain(m));
269 let leftover: Vec<_> = std::fs::read_dir(&d.0)
270 .unwrap()
271 .filter_map(|e| e.ok())
272 .filter(|e| e.file_name().to_string_lossy().starts_with("run-"))
273 .collect();
274 assert!(leftover.is_empty(), "run files were left behind: {leftover:?}");
275 }
276
277 #[test]
278 fn an_empty_sort_merges_to_nothing() {
279 let d = TempDir::new("empty");
280 let s = ExternalSort::new(&d.0, 16).unwrap();
281 assert!(s.is_empty());
282 assert!(drain(s.finish().unwrap()).is_empty());
283 }
284}