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

Modern-Apps.git / scripts / maps / osm_ingest / src / pbf_s1.rs

pbf_s1.rs301 lines · 12.5 KiBRaw
1pub fn run_pass_sink<S, F, G, H>(
2 path: &Path,
3 blobs: &[BlobLoc],
4 spec: PassSpec<'_>,
5 make: F,
6 body: G,
7 sink: H,
8) -> Result<Vec<u8>>
9where
10 S: Send,
11 F: Fn() -> S + Sync,
12 G: Fn(&mut S, &PrimitiveBlock) -> Result<u8> + Sync,
13 H: FnMut(S) -> Result<()> + Send,
14{
15 let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS).max(1);
16 let shared: Mutex<Shared<S>> = Mutex::new(Shared {
17 slots: (0..n_chunks).map(|_| None).collect(),
18 next: 0,
19 waiters: Vec::new(),
20 failed: false,
21 });
22 let kinds: Vec<AtomicU8> = (0..blobs.len()).map(|_| AtomicU8::new(0)).collect();
23
24 let next_chunk = AtomicUsize::new(0);
25 let done_blobs = AtomicUsize::new(0);
26 let last_pct = AtomicUsize::new(usize::MAX);
27 // Owns the meter's clock: `report` draws the progress.rs standard shape
28 // (`label [pct%] done/total elapsed, ETA`) from it on every redraw.
29 let pass_start = std::time::Instant::now();
30 let n_threads = crate::par::threads().min(n_chunks);
31 let mut first_err: Option<Error> = None;
32 let mut sink_err: Option<Error> = None;
33 let mut sink = sink;
34 // How far ahead of the sink the workers may run.
35 //
36 // Without this the reorder buffer is unbounded: a worker deposits and immediately
37 // claims another chunk, so one slow chunk 0 can park every other chunk's
38 // accumulator in `slots` at once. On a planet pass those accumulators are the
39 // largest things in the build, and raising the thread count widens the window,
40 // which is exactly the failure this plan is shaped to avoid. Two chunks per thread
41 // leaves slack for an uneven chunk without letting the buffer grow with the file.
42 //
43 // Note what this does NOT bound. It is a count of chunks, so the bytes it admits are
44 // `window * CHUNK_BLOBS` blobs' worth of accumulator — and on a 64-core box the window
45 // is 128 chunks, which exceeds the chunk count of anything smaller than a continent.
46 // For those the window binds on nothing and the bound is really [`CHUNK_BLOBS`]; see
47 // its doc for the 2.19 GB that cost. Bounding this in bytes would mean measuring `S`,
48 // which is opaque here by design.
49 let window = n_threads.saturating_mul(2).max(2);
50 // Workers still running; the drain stops waiting once it reaches zero, so a
51 // worker that failed (or unwound, in tests) cannot strand it.
52 let alive = AtomicUsize::new(n_threads);
53
54 // The sink runs HERE, on the calling thread, and never under the lock.
55 //
56 // It used to run inside `deposit`, under the one mutex every worker takes
57 // to deposit and to check the window, and each deposit `notify_all`-ed
58 // every worker parked on the window. At 192 threads with a sink that is the
59 // bottleneck that was a thundering herd: California spent ~400 s of system
60 // time (vs ~110 s user) in futex hash-bucket spinlocks. Now a deposit is a
61 // slot store plus an unpark of the drain thread, the sink overlaps with the
62 // deposits, and a window waiter is woken only when ITS chunk enters the
63 // window. Order is unchanged: the sink still sees chunks strictly in index
64 // order, one at a time, on one thread.
65 let drain_thread = std::thread::current();
66 std::thread::scope(|scope| {
67 let mut handles = Vec::with_capacity(n_threads);
68 for _ in 0..n_threads {
69 handles.push(scope.spawn(|| -> Result<()> {
70 struct Alive<'a>(&'a AtomicUsize, std::thread::Thread);
71 impl Drop for Alive<'_> {
72 fn drop(&mut self) {
73 self.0.fetch_sub(1, Ordering::AcqRel);
74 self.1.unpark();
75 }
76 }
77 let _alive = Alive(&alive, drain_thread.clone());
78 let fail = |e: Error| -> Error {
79 shared.lock().expect("chunk slot mutex").failed = true;
80 e
81 };
82 let mut file = File::open(path)
83 .map_err(|e| fail(Error(format!("cannot open {}: {e}", path.display()))))?;
84 let mut compressed = Vec::new();
85 let mut inflated = Vec::new();
86 loop {
87 let chunk = next_chunk.fetch_add(1, Ordering::Relaxed);
88 if chunk >= n_chunks {
89 return Ok(());
90 }
91 // Hold off until this chunk is inside the window. The worker that
92 // owns the lowest outstanding chunk always passes this test, so it
93 // always makes progress and the wait cannot deadlock.
94 loop {
95 let mut st = shared.lock().expect("chunk slot mutex");
96 if chunk < st.next + window || st.failed {
97 st.waiters.retain(|(c, _)| *c != chunk);
98 break;
99 }
100 if !st.waiters.iter().any(|(c, _)| *c == chunk) {
101 st.waiters.push((chunk, std::thread::current()));
102 }
103 drop(st);
104 std::thread::park();
105 }
106 let start = chunk * CHUNK_BLOBS;
107 let end = ((chunk + 1) * CHUNK_BLOBS).min(blobs.len());
108 let mut state = make();
109 for (i, loc) in blobs[start..end].iter().enumerate() {
110 let idx = start + i;
111 match spec.blob_kinds.filter(|k| k[idx] & spec.want == 0) {
112 Some(k) => kinds[idx].store(k[idx], Ordering::Relaxed),
113 None => {
114 read_exact_at(&mut file, loc, &mut compressed).map_err(fail)?;
115 inflate_blob(&compressed, &mut inflated).map_err(fail)?;
116 let block = PrimitiveBlock::decode(&inflated).map_err(fail)?;
117 let seen = body(&mut state, &block).map_err(fail)?;
118 kinds[idx].store(seen, Ordering::Relaxed);
119 }
120 }
121 report(spec.label, &done_blobs, &last_pct, blobs.len(), &pass_start);
122 }
123 shared.lock().expect("chunk slot mutex").slots[chunk] = Some(state);
124 drain_thread.unpark();
125 }
126 }));
127 }
128
129 // The in-order drain.
130 let mut next = 0usize;
131 while next < n_chunks {
132 let (ready, failed) = {
133 let mut st = shared.lock().expect("chunk slot mutex");
134 match st.slots[next].take() {
135 Some(s) => {
136 st.next = next + 1;
137 // Admit exactly the waiters whose chunk just entered the window.
138 let limit = st.next + window;
139 let mut i = 0;
140 while i < st.waiters.len() {
141 if st.waiters[i].0 < limit {
142 st.waiters.swap_remove(i).1.unpark();
143 } else {
144 i += 1;
145 }
146 }
147 (Some(s), st.failed)
148 }
149 None => (None, st.failed),
150 }
151 };
152 match ready {
153 Some(s) => {
154 next += 1;
155 // Keep draining after a failure: the pass reports the first error
156 // at the end, and stopping here would strand the remaining chunks.
157 if let Err(e) = sink(s) {
158 if sink_err.is_none() {
159 sink_err = Some(e);
160 }
161 }
162 }
163 None => {
164 if failed || alive.load(Ordering::Acquire) == 0 {
165 // A worker failed (its chunk will never arrive), or every
166 // worker is gone: release anyone parked on the window and
167 // stop; the join below reports the error.
168 let mut st = shared.lock().expect("chunk slot mutex");
169 st.failed = true;
170 for (_, t) in st.waiters.drain(..) {
171 t.unpark();
172 }
173 if alive.load(Ordering::Acquire) == 0 {
174 break;
175 }
176 }
177 std::thread::park_timeout(std::time::Duration::from_millis(50));
178 }
179 }
180 }
181
182 for h in handles {
183 match h.join() {
184 Ok(Ok(())) => {}
185 Ok(Err(e)) => {
186 if first_err.is_none() {
187 first_err = Some(e);
188 }
189 }
190 Err(_) => {
191 if first_err.is_none() {
192 first_err = Some(Error("a reader thread panicked".into()));
193 }
194 }
195 }
196 }
197 if first_err.is_none() && next < n_chunks {
198 first_err = Some(Error(format!(
199 "pass {}: chunks {next}..{n_chunks} were never produced",
200 spec.label
201 )));
202 }
203 });
204
205 if let Some(e) = first_err {
206 return Err(e);
207 }
208 if let Some(e) = sink_err {
209 return Err(e);
210 }
211 // Snap to 100% in the same standard shape, then a fresh line so the next
212 // stage starts clean instead of on top of the meter.
213 {
214 let n = blobs.len();
215 eprintln!(
216 "\r{:<28} [100%] {n}/{n} {} elapsed, ETA 0s ",
217 spec.label,
218 crate::progress::hms(pass_start.elapsed().as_secs_f64()),
219 );
220 }
221 Ok(kinds.iter().map(|k| k.load(Ordering::Relaxed)).collect())
222}
223
224/// Finished chunks waiting for their turn, plus the window bookkeeping. The
225/// sink itself lives on the draining thread, outside this lock.
226struct Shared<S> {
227 slots: Vec<Option<S>>,
228 /// The next chunk the drain will hand to the sink.
229 next: usize,
230 /// Workers parked until their chunk enters the window: `(chunk, thread)`.
231 waiters: Vec<(usize, std::thread::Thread)>,
232 /// A worker failed, so a chunk will never arrive: stop waiting.
233 failed: bool,
234}
235
236/// Run one pass over the file in parallel, returning every chunk's accumulator.
237///
238/// Convenience over [`run_pass_sink`] for passes whose accumulators are small
239/// enough that holding them all costs nothing. Accumulators come back in chunk
240/// order, so merging them is deterministic.
241pub fn run_pass<S, F, G>(
242 path: &Path,
243 blobs: &[BlobLoc],
244 blob_kinds: Option<&[u8]>,
245 want: u8,
246 label: &str,
247 make: F,
248 body: G,
249) -> Result<(Vec<S>, Vec<u8>)>
250where
251 S: Send,
252 F: Fn() -> S + Sync,
253 G: Fn(&mut S, &PrimitiveBlock) -> Result<u8> + Sync,
254{
255 let mut out: Vec<S> = Vec::new();
256 let kinds =
257 run_pass_sink(path, blobs, PassSpec { blob_kinds, want, label }, make, body, |s| {
258 out.push(s);
259 Ok(())
260 })?;
261 Ok((out, kinds))
262}
263
264pub(crate) fn read_exact_at(file: &mut File, loc: &BlobLoc, out: &mut Vec<u8>) -> Result<()> {
265 file.seek(SeekFrom::Start(loc.offset))
266 .map_err(|e| Error(format!("seek to {} failed: {e}", loc.offset)))?;
267 out.clear();
268 out.resize(loc.datasize as usize, 0);
269 file.read_exact(out).map_err(|e| Error(format!("short read at {}: {e}", loc.offset)))
270}
271
272/// One redraw of the pass meter, in the single standard shape (`progress.rs`):
273/// `label [pct%] done/total elapsed, ETA` on one stderr line.
274fn report(
275 label: &str,
276 done: &AtomicUsize,
277 last_pct: &AtomicUsize,
278 total: usize,
279 start: &std::time::Instant,
280) {
281 let n = done.fetch_add(1, Ordering::Relaxed) + 1;
282 if total == 0 {
283 return;
284 }
285 let pct = n * 100 / total;
286 let prev = last_pct.load(Ordering::Relaxed);
287 if pct != prev
288 && last_pct.compare_exchange(prev, pct, Ordering::Relaxed, Ordering::Relaxed).is_ok()
289 {
290 let elapsed = start.elapsed().as_secs_f64();
291 // ETA extrapolates the average rate so far; meaningless until something is
292 // done, so hold it at zero for the opening frame.
293 let eta = if n == 0 { 0.0 } else { elapsed * (total - n) as f64 / n as f64 };
294 eprint!(
295 "\r{label:<28} [{pct:>3}%] {n}/{total} {} elapsed, ETA {} ",
296 crate::progress::hms(elapsed),
297 crate::progress::hms(eta),
298 );
299 let _ = std::io::stderr().flush();
300 }
301}