Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / store_part3.rs
store_part3.rs300 lines · 15.2 KiBRaw
| 1 | /// Consecutive chunks one lane claims at a time. |
| 2 | /// |
| 3 | /// **One, because dealing longer runs was tried and measured as nothing.** The reasoning for runs is |
| 4 | /// good and the measurement does not support it: single-chunk round-robin means each of sixteen |
| 5 | /// lanes walks the file in ~9 KB hops sixteen chunks apart, which is the pattern readahead exists to |
| 6 | /// defeat, and the spill was moving at 643 MB/s on hardware that does several gigabytes. Dealing |
| 7 | /// runs of 64 consecutive chunks — ~600 KB, a streaming read — changed north-america tiling from |
| 8 | /// 807.0 s to 813.1 s and the reader from 292.6 s to 298.4 s. Noise, and slightly the wrong way. |
| 9 | /// |
| 10 | /// So the reads were never the problem, and the throughput figure was measuring something else: the |
| 11 | /// reader was not waiting on disk, it was busy discarding features (see [`ZoomReader::spawn`]). Kept |
| 12 | /// as a named constant of 1 rather than deleted, because the shape of the partition is worth being |
| 13 | /// explicit about and because the next person to look at a 643 MB/s number will have the same idea. |
| 14 | #[cfg_attr(not(test), allow(dead_code))] |
| 15 | const PREFETCH_RUN: usize = 1; |
| 16 | |
| 17 | /// Chunks one lane may run ahead by. |
| 18 | /// |
| 19 | /// Bounds the prefetch at `prefetch_lanes() * (PREFETCH_DEPTH + 1) * 64` features — about 34 K at |
| 20 | /// constants above, which is small against the 512 Ki *vertices* the tiler batches immediately |
| 21 | /// downstream. Depth is here to absorb a slow chunk, not to buffer. |
| 22 | #[cfg_attr(not(test), allow(dead_code))] |
| 23 | const PREFETCH_DEPTH: usize = 32; |
| 24 | |
| 25 | /// Reads the chunks one zoom needs and seeks past the rest. |
| 26 | #[cfg_attr(not(test), allow(dead_code))] |
| 27 | pub struct ZoomReader { |
| 28 | /// One receiver per lane. Wanted-chunk `k` is decoded by lane `(k / PREFETCH_RUN) % lanes.len()`, |
| 29 | /// so walking the lanes a run at a time reproduces file order exactly. Empty when there is |
| 30 | /// nothing to read. |
| 31 | lanes: Vec<std::sync::mpsc::Receiver<Decoded>>, |
| 32 | /// Joined on drop, after the receivers are dropped: a lane blocked on a full channel exits when |
| 33 | /// its receiver goes, so the order of those two steps is what makes the join finite. |
| 34 | lanes_running: Vec<std::thread::JoinHandle<()>>, |
| 35 | /// Chunks taken so far, which is also what decides the lane to take the next one from. |
| 36 | at: usize, |
| 37 | total: usize, |
| 38 | records: Vec<Feature>, |
| 39 | } |
| 40 | |
| 41 | impl Drop for ZoomReader { |
| 42 | fn drop(&mut self) { |
| 43 | // Receivers first. A lane parked on `send` to a full channel wakes with an error the moment |
| 44 | // its receiver is gone, and only then is the join below guaranteed to finish -- which |
| 45 | // matters on the error path, where the tiler abandons a zoom with every lane backed up. |
| 46 | self.lanes.clear(); |
| 47 | for lane in self.lanes_running.drain(..) { |
| 48 | let _ = lane.join(); |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[cfg_attr(not(test), allow(dead_code))] |
| 54 | impl ZoomReader { |
| 55 | /// Start a lane per [`prefetch_lanes`] over `wanted`, dealt round-robin. |
| 56 | /// |
| 57 | /// # Why dedicated threads and not the pool |
| 58 | /// |
| 59 | /// This decode is 62.6 s of a 175 s us-west build, all of it on one thread, and |
| 60 | /// [`NormalizedChunks::read_into`] is an obvious candidate for the pool: it takes `&self`, reads |
| 61 | /// its own byte range positionally, and is pure. Decoding 512 chunks at a time across the pool |
| 62 | /// was tried and made the map phase **62% slower** — 102.4 s to 165.5 s — for byte-identical |
| 63 | /// output. |
| 64 | /// |
| 65 | /// The reason is what this reader is: it feeds the clipping workers through a channel. Handing |
| 66 | /// the refill to the same pool queues it *behind* the clipping tasks it exists to supply, so the |
| 67 | /// reader blocks waiting on a pool that is busy with work only the reader can extend. The |
| 68 | /// overlap between reading and clipping — the entire point of the arrangement — disappears, and |
| 69 | /// both halves get slower. |
| 70 | /// |
| 71 | /// So: threads of their own, outside the pool, which is what [`crate::tiler`] does for the |
| 72 | /// reader itself and for the same reason. |
| 73 | /// |
| 74 | /// # Why the lanes drop features rather than hand them over |
| 75 | /// |
| 76 | /// A feature below `z`'s own floor is dropped **here**, and that is not tidiness — it is most of |
| 77 | /// what this reader costs. The chunk index skips a chunk only when *every* feature in it is too |
| 78 | /// deep, and a chunk is 64 features in file order with no relationship between their |
| 79 | /// `min_zoom`s, so at a shallow zoom nearly every chunk survives the index while holding almost |
| 80 | /// nothing that zoom draws. z5 of north-america reads 590,002 chunks — 37.8 M features — to |
| 81 | /// produce 156 tiles. |
| 82 | /// |
| 83 | /// Left to the consumer, as it was, that is roughly **1.06 billion features across the build** |
| 84 | /// pulled one `next()` at a time and then discarded. No lane count fixes it, because it is not |
| 85 | /// the lanes' work: raising lanes from 4 to 16 took the reader 496.8 s to 292.6 s and then |
| 86 | /// stopped, and dealing sequential runs instead of strided chunks changed nothing at all. The |
| 87 | /// filter is per-feature and order-preserving, so moving it up here removes exactly the features |
| 88 | /// the tiler removed, in a place where sixteen threads share the cost. |
| 89 | /// |
| 90 | /// # Why the order cannot move |
| 91 | /// |
| 92 | /// Lane `j` takes wanted-chunks `j`, `j + n`, `j + 2n`, ... and a lane's own channel is FIFO, so |
| 93 | /// the `k`th chunk out of lane `k % n` is wanted-chunk `k`. Reading the lanes round-robin is |
| 94 | /// therefore the wanted list in order, which is the file in order, which is what the archive's |
| 95 | /// feature ordering rests on. Nothing here depends on which lane finishes first; a lane that |
| 96 | /// races ahead fills its channel and parks. |
| 97 | fn spawn(inner: NormalizedChunks, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> { |
| 98 | let total = wanted.len(); |
| 99 | if total == 0 { |
| 100 | return Ok(ZoomReader { |
| 101 | lanes: Vec::new(), |
| 102 | lanes_running: Vec::new(), |
| 103 | at: 0, |
| 104 | total: 0, |
| 105 | records: Vec::new(), |
| 106 | }); |
| 107 | } |
| 108 | // One handle shared rather than one file open per lane: `read_into` is positional and |
| 109 | // documented to serve every thread from one handle. |
| 110 | let inner = std::sync::Arc::new(inner); |
| 111 | // No more lanes than there are runs to deal, or the tail lanes are threads started to do |
| 112 | // nothing. |
| 113 | let count = prefetch_lanes().min(total.div_ceil(PREFETCH_RUN)); |
| 114 | let mut lanes = Vec::with_capacity(count); |
| 115 | let mut lanes_running = Vec::with_capacity(count); |
| 116 | for lane in 0..count { |
| 117 | let (send, receive) = std::sync::mpsc::sync_channel::<Decoded>(PREFETCH_DEPTH); |
| 118 | let inner = std::sync::Arc::clone(&inner); |
| 119 | // This lane's runs, flattened back into the chunks it will read: sequential within a |
| 120 | // run, which is the whole point of dealing runs rather than chunks. |
| 121 | let mine: Vec<usize> = wanted |
| 122 | .chunks(PREFETCH_RUN) |
| 123 | .skip(lane) |
| 124 | .step_by(count) |
| 125 | .flatten() |
| 126 | .copied() |
| 127 | .collect(); |
| 128 | let running = std::thread::Builder::new() |
| 129 | .name(format!("mamaps-spill-{lane}")) |
| 130 | .spawn(move || { |
| 131 | // One byte buffer and one record buffer for the lane, reused across its |
| 132 | // chunks. What is sent is a third `Vec`, allocated per chunk -- one allocation |
| 133 | // per 64 features, against the per-feature geometry the decode allocates |
| 134 | // anyway. |
| 135 | let mut scratch = Vec::new(); |
| 136 | let mut records = Vec::new(); |
| 137 | for chunk in mine { |
| 138 | let decoded = inner |
| 139 | .read_into(chunk, &mut scratch, &mut records) |
| 140 | .map_err(|e| osm_ingest::proto::Error(e.to_string())) |
| 141 | // Reversed here rather than by the consumer, which takes from the |
| 142 | // back: same reason as everything else in this closure, it is work and |
| 143 | // it does not have to be the reader's. |
| 144 | .and_then(|()| { |
| 145 | let mut out = Vec::with_capacity(records.len()); |
| 146 | for record in records.drain(..).rev() { |
| 147 | let feature = feature_of(record)?; |
| 148 | // The zoom window, applied where the work is spread. See this |
| 149 | // function's docs: at a shallow zoom this is nearly the whole |
| 150 | // Floor is the feature's own `min_zoom`; ceiling is the |
| 151 | // layer cap (`MAX_ZOOM_PER_LAYER`) — boundaries stop at |
| 152 | // z13, everything else tiles to the archive max. |
| 153 | if z >= feature.class.min_zoom |
| 154 | && z <= crate::schema::max_zoom_for_layer(feature.class.layer) |
| 155 | { |
| 156 | out.push(feature); |
| 157 | } |
| 158 | } |
| 159 | Ok(out) |
| 160 | }); |
| 161 | // Stop on the first error: the consumer surfaces it and abandons the zoom, |
| 162 | // and carrying on would only queue work behind a build that is already |
| 163 | // failing. |
| 164 | let stop = decoded.is_err(); |
| 165 | if send.send(decoded).is_err() || stop { |
| 166 | return; |
| 167 | } |
| 168 | } |
| 169 | }) |
| 170 | .map_err(|e| { |
| 171 | osm_ingest::proto::Error(format!("cannot start spill prefetch lane {lane}: {e}")) |
| 172 | })?; |
| 173 | lanes.push(receive); |
| 174 | lanes_running.push(running); |
| 175 | } |
| 176 | Ok(ZoomReader { lanes, lanes_running, at: 0, total, records: Vec::new() }) |
| 177 | } |
| 178 | |
| 179 | /// How many spill chunks this zoom will read, and how many it has. |
| 180 | /// |
| 181 | /// Exposed so the tiler can show progress: the map phase is the longest in the build and was |
| 182 | /// silent for all of it, which on a continent is forty minutes of no output at all. |
| 183 | #[allow(dead_code)] |
| 184 | pub fn chunks(&self) -> (usize, usize) { |
| 185 | (self.at.min(self.total), self.total) |
| 186 | } |
| 187 | |
| 188 | /// The next feature, or `None` once this zoom's chunks are exhausted. |
| 189 | pub fn next(&mut self) -> Result<Option<Feature>> { |
| 190 | loop { |
| 191 | // From the back, which is why the lane reversed the chunk before sending it. |
| 192 | if let Some(feature) = self.records.pop() { |
| 193 | return Ok(Some(feature)); |
| 194 | } |
| 195 | if self.at >= self.total { |
| 196 | return Ok(None); |
| 197 | } |
| 198 | let lane = self.at % self.lanes.len(); |
| 199 | self.at += 1; |
| 200 | // A lane that hung up before delivering all of its chunks panicked: it returns only |
| 201 | // after sending every one of them or after sending an error, and an error arrives as a |
| 202 | // value rather than a hangup. |
| 203 | let decoded = self.lanes[lane].recv().map_err(|_| { |
| 204 | osm_ingest::proto::Error(format!("spill prefetch lane {lane} stopped early")) |
| 205 | })?; |
| 206 | self.records = decoded?; |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | #[cfg_attr(not(test), allow(dead_code))] |
| 212 | pub struct Reader { |
| 213 | inner: NormalizedReader, |
| 214 | } |
| 215 | |
| 216 | impl Reader { |
| 217 | /// The next feature, or `None` at the end of the file. |
| 218 | /// |
| 219 | /// A record whose class property is missing or is not an integer is a corrupt file rather than a |
| 220 | /// feature to skip: everything in here was written by [`Sink::push`] one run ago, so anything |
| 221 | /// else means the file is not the one we wrote. |
| 222 | #[cfg_attr(not(test), allow(dead_code))] |
| 223 | pub fn next(&mut self) -> Result<Option<Feature>> { |
| 224 | let Some(record) = |
| 225 | self.inner.next().map_err(|e| osm_ingest::proto::Error(e.to_string()))? |
| 226 | else { |
| 227 | return Ok(None); |
| 228 | }; |
| 229 | Ok(Some(feature_of(record)?)) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /// Classified ways on disk: the second row of the table above, and the second thing stage A no |
| 234 | /// longer holds. |
| 235 | /// |
| 236 | /// # Why a file rather than the `HashMap<i64, Way>` this replaces |
| 237 | /// |
| 238 | /// The map cost ~2.7 GB on California, nearly all of it node refs, and every read of it was |
| 239 | /// sequential in ascending id order — [`crate::extract`] sorted the keys precisely so the archive |
| 240 | /// would not depend on hash order. It was a map only because a relation reaches its member ways by |
| 241 | /// id, in whatever order it lists them, and that one random access is served far more cheaply by |
| 242 | /// keeping *only* the relation members resident: California has 63 156 relations against several |
| 243 | /// million classified ways. |
| 244 | /// |
| 245 | /// # Why nothing has to be sorted on the way back |
| 246 | /// |
| 247 | /// A `.osm.pbf` stores ways sorted by id, and [`osm_ingest::pbf::run_pass_sink`] hands finished |
| 248 | /// chunks to its sink in file order. Appending as pass 1 goes therefore produces a file already in |
| 249 | /// the order materialisation wants, and the sort disappears along with the map. |
| 250 | /// |
| 251 | /// [`push`] **enforces** that ordering rather than trusting it. An id that does not advance would |
| 252 | /// silently reorder the archive, and a byte-identical rebuild is the only evidence this pipeline has |
| 253 | /// that a change to stage A preserved its meaning — so a file that is not sorted is an error here, |
| 254 | /// where it is one line of output, rather than a diff in a 655 MB archive. |
| 255 | /// |
| 256 | /// # The encoding |
| 257 | /// |
| 258 | /// One record per way, every field a varint, nothing aligned: |
| 259 | /// |
| 260 | /// | field | encoding | |
| 261 | /// |---|---| |
| 262 | /// | id | zigzag varint of the gap from the previous record's id | |
| 263 | /// | class | unsigned varint of [`pack`]'s integer | |
| 264 | /// | ref count | unsigned varint | |
| 265 | /// | refs | zigzag varint of each ref's gap from the one before it, the first from zero | |
| 266 | /// | name | unsigned varint byte length, then that many UTF-8 bytes (zero when nameless) | |
| 267 | /// | lane count | unsigned varint | |
| 268 | /// | turn masks | a count then each `u16`, forward then backward | |
| 269 | /// | carriageway | unsigned varint of the packed forward/backward/divider word | |
| 270 | /// | building | a presence byte, then three packed varints when set | |
| 271 | /// |
| 272 | /// Delta coding earns its keep rather than being a flourish. The refs are ~150 M ids on California |
| 273 | /// and the file is read twice — once to collect the node ids pass 3 must resolve, once to build |
| 274 | /// geometry — so a flat 8 bytes each would be 1.2 GB read twice. Consecutive nodes of a way were |
| 275 | /// almost always created in one editing session and so have near-consecutive ids, which is exactly |
| 276 | /// what a delta collapses to one or two bytes. |
| 277 | /// |
| 278 | /// [`push`]: WaySink::push |
| 279 | pub struct WaySink { |
| 280 | out: WayOut, |
| 281 | /// One record's bytes, reused. Several million records, so a `Vec` per record would be several |
| 282 | /// million allocations for a buffer that is dead a line later. |
| 283 | record: Vec<u8>, |
| 284 | last_id: i64, |
| 285 | count: u64, |
| 286 | refs: u64, |
| 287 | max_ref: i64, |
| 288 | /// Bytes staged so far: the next record's offset, for the block index. |
| 289 | at: u64, |
| 290 | /// The block index over the stream. See [`WayBlockLoc`]. |
| 291 | blocks: Vec<WayBlockLoc>, |
| 292 | } |
| 293 | |
| 294 | /// Where a [`WaySink`] stages its bytes: a file, or anonymous memory. |
| 295 | enum WayOut { |
| 296 | File(BufWriter<File>), |
| 297 | Anon(tile_build::anon::AnonStore), |
| 298 | } |
| 299 | |
| 300 | include!("store_part3_s1.rs"); |