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

Modern-Apps.git / scripts / maps / mamaps_build / src / tiler_part1.rs

tiler_part1.rs263 lines · 13.0 KiBRaw
1type EncodedBatch = (Vec<Encoded>, usize, u64, u64);
2
3/// Tile every feature and write the archive.
4/// Tile every feature in `store` into a `.mamaps` archive.
5///
6/// The store is read **once per zoom**, in order, rather than held in memory for all of them. Fifteen
7/// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of
8/// a measured 10.03 GB California peak.
9#[cfg(test)]
10pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> {
11 adopt_thread_budget();
12 let mut writer = writer_for(store, settings)?;
13 // Tests share the zoom loop but report no phase: the timer is dropped without `finish`,
14 // so no `TIMING` line ever reaches test output.
15 let mut timer = crate::timing::PhaseTimer::start("tiles");
16 let per_zoom = tile_zooms(store, settings, &mut writer, &mut timer)?;
17 let bytes = writer.finish()?;
18 Ok((bytes, per_zoom))
19}
20
21/// Tile every feature in `store` straight into the archive at `out`, without ever holding the
22/// archive in memory.
23///
24/// `build` above returns the whole archive as a `Vec<u8>` -- fine for tests, fatal for a planet:
25/// the data section alone is tens of GB, and holding it beside the merge's own peak is what OOMs
26/// a box with ~50 GB of commit headroom right after z14 merges. This runs the identical zoom loop
27/// ([`tile_zooms`]) and finishes through [`StreamWriter::finish_to_path`], so the only thing ever
28/// held is the prefix (the index, small next to the bodies). Same tiles, same order, same bytes:
29/// the writer appends identically either way, and `finish_to_path` assembles the same
30/// header/dictionary/root/leaves/data layout as `finish`.
31pub fn build_to_path(
32 store: &Store,
33 settings: &Settings,
34 out: &std::path::Path,
35 timer: &mut crate::timing::PhaseTimer,
36) -> Result<Vec<ZoomStats>> {
37 adopt_thread_budget();
38 let mut writer = writer_for(store, settings)?;
39 let per_zoom = tile_zooms(store, settings, &mut writer, timer)?;
40 writer.finish_to_path(out)?;
41 Ok(per_zoom)
42}
43
44/// The [`StreamWriter`] for a build: zoom range, build id, compression, and the body scratch
45/// beside the output.
46///
47/// The scratch placement matters: the writer spills the data section (tens of GB on a planet)
48/// through a temp file, and the default is the system temp dir -- routinely a small system
49/// volume. Beside the output it shares the volume the operator already sized for the build
50/// (feature spill, tile chunks, archive), and it is removed on drop like every other scratch
51/// file. Path only, never bytes: the archive is identical wherever the scratch lives.
52fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> {
53 let bbox = store.bbox();
54 StreamWriter::new(Options {
55 min_zoom: 0,
56 max_zoom: crate::DEFAULT_MAX_ZOOM,
57 build_id: settings.build_id,
58 // The header carries the seed folded with the digest of every tile written: identical
59 // tiles from identical inputs give an identical id anywhere (see `derive_build_id`).
60 build_id_from_content: true,
61 compress: true,
62 // Stage C runs on every tile below, so the claim is true. It is what lets the renderer
63 // skip its repair pass — and the renderer still keeps that pass, gated, because a claim is
64 // only as good as the generator making it.
65 rings_validated: true,
66 min_lon_e7: bbox.0,
67 min_lat_e7: bbox.1,
68 max_lon_e7: bbox.2,
69 max_lat_e7: bbox.3,
70 spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf),
71 // Leaf compression at finish runs on the build's own thread budget.
72 threads: par::threads(),
73 // The body scratch holds already-DEFLATEd bodies (~53 GB on a planet): keep btrfs
74 // `compress-force` from zstd'ing them again at writeback.
75 spill_file_hook: Some(osm_ingest::mem::mark_scratch_uncompressed),
76 // `--body-zstd`: the header says zstd; the encode worker compresses with it.
77 zstd: size_opts().zstd_level > 0,
78 ..Options::default()
79 })
80}
81
82/// The zoom loop both builders share: map, merge, encode and append z0..=z14 through `writer`.
83///
84/// Extracted whole from `build` so the two finishes cannot diverge: the per-zoom stats, the
85/// progress bars, the `check_books` gate and the append order are identical, and only the final
86/// assembly differs (in-memory vs streaming).
87fn tile_zooms(
88 store: &Store,
89 settings: &Settings,
90 writer: &mut StreamWriter,
91 timer: &mut crate::timing::PhaseTimer,
92) -> Result<Vec<ZoomStats>> {
93
94 let mut per_zoom = Vec::new();
95 // The tile-chunk spill's backend, decided once from the feature count: z14 holds the most
96 // clipped copies at once (the 53 GB north-america case that motivated the spill), so sizing
97 // for the whole store is the safe side. Per-zoom files share one scratch path -- each zoom's
98 // spill truncates it on create and removes it on drop, so peak disk is still the largest
99 // single zoom.
100 let chunk_plan = plan_chunk_spill(store, &settings.scratch);
101 // The operator's override wins over the gate: `force_chunk_spill_file` (from
102 // `MAPS_ANON_SPILL`, unset or non-`1`) stages through the scratch file even when the gate
103 // picks anon. Same chunks, same bytes, no commit charge for the merge to trip over.
104 let chunk_plan = if settings.force_chunk_spill_file
105 && chunk_plan == osm_ingest::mem::SpillPlan::Anon
106 {
107 eprintln!(
108 " [tiler] chunk spill -> {} (file backend: MAPS_ANON_SPILL)",
109 settings.scratch.display(),
110 );
111 osm_ingest::mem::SpillPlan::File
112 } else {
113 chunk_plan
114 };
115 for z in 0..=crate::DEFAULT_MAX_ZOOM {
116 let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() };
117 let tolerance =
118 simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, DEFAULT_SIMPLIFICATION)
119 * size_opts().simplify_scale;
120 let buffer = geom::buffer_for(EXTENT);
121
122 // Per zoom, so peak scratch is the largest single zoom rather than the sum, and so a build
123 // that dies at z14 leaves one zoom behind rather than fifteen. Anonymous
124 // pagefile-backed memory (no file) when commit allows, else the scratch file; the merge
125 // reads through the same ChunkReader either way.
126 let spill = ChunkSpill::create_planned(&settings.scratch, chunk_plan)?;
127 // Per-zoom `map`: repeat visits merge into one total at `finish`.
128 timer.switch("map");
129 let mapped = std::time::Instant::now();
130 let (chunks, tally) = map_zoom(store, settings, z, tolerance, buffer, &spill)?;
131 stats.map_ms = mapped.elapsed().as_millis() as u64;
132 stats.features = tally.features;
133 stats.points = tally.points;
134 stats.dropped = tally.dropped;
135
136 // Ascending by tile id because the merge makes it so, not because a sort step was
137 // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the
138 // single-threaded `BTreeMap` gave; the maps now live on disk and the guarantee does not
139 // change, because a chunk's bytes are written in its key order and read back in file order.
140 //
141 // Range-parallel merge when the zoom repays planning: one worker k-way merges each
142 // cost-balanced tile range (see `tiler_part3::merge_parallel`), drained in order by the
143 // same consume loop below — sequence-identical to serial, so batches, prune and append
144 // are untouched. Small zooms stay serial: planning costs more than it saves there. So do
145 // z0–z3, whose tile spans (1–64) don't divide by the 256 cost buckets — the bucket table
146 // can't invert those edges exactly (see `parallel_merge_supported`).
147 //
148 // The choice is `merge_gate` below, hardcoded: no environment override.
149 // Operator control arrives through `--threads`/`MAPS_THREADS` (which sizes the
150 // worker count) exactly like every other parallel stage in this tree.
151 let merge_parallel = merge_gate(&chunks, z);
152 if merge_parallel {
153 let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS);
154 // One worker owns the whole tile space on a one-thread box, which is
155 // the serial sequence by construction — correctness never depends on
156 // the count, only speed does.
157 let merge_workers = merge_workers.max(1);
158 // Timed as its own subphase: the planning scan is a serial
159 // skip-walk over every chunk, and at z14 it is large enough to
160 // matter against the merge it parallelises.
161 timer.switch("merge-plan");
162 let planning = std::time::Instant::now();
163 // Many more ranges than workers (see `plan_ranges_auto`): workers claim ranges in
164 // order and the coordinator drains them in order, so `merge_workers` consecutive
165 // ranges merge at once instead of one range at a time behind a full run-ahead budget.
166 let plan = crate::tiler::plan_ranges_auto(&chunks, &spill, z, merge_workers)?;
167 let ranges = plan.bounds.len() - 1;
168 stats.merge_ms += planning.elapsed().as_millis() as u64;
169 // One line per zoom on the parallel path: the spread of per-range cost estimates.
170 // `hot` is the costliest single tile: ranges assign whole tiles, so no range can go
171 // below it however they split.
172 let (lo, hi) = plan
173 .range_cost
174 .iter()
175 .fold((u64::MAX, 0u64), |(lo, hi), &c| (lo.min(c), hi.max(c)));
176 eprintln!(
177 " [merge] z{z}: {ranges} range(s) on {merge_workers} worker(s), cost {lo}..{hi} per range, hot tile {} at {}, entries {}, planned in {:.1}s",
178 plan.hot_tile,
179 plan.hot_cost,
180 plan.remaining
181 .iter()
182 .map(|row| row.iter().sum::<u64>())
183 .sum::<u64>(),
184 planning.elapsed().as_secs_f64(),
185 );
186 let queues = crate::tiler::RangeQueues::new(ranges);
187 let claim = AtomicUsize::new(0);
188 std::thread::scope(|s| -> Result<()> {
189 // Shared refs are `Copy`: each spawned closure gets its own
190 // copy rather than moving `chunks`/`spill` on first use.
191 let chunks_ref = &chunks;
192 let spill_ref = &spill;
193 let range_plan = &plan;
194 for _ in 0..merge_workers.min(ranges) {
195 let (queues, claim) = (&queues, &claim);
196 s.spawn(move || loop {
197 let r = claim.fetch_add(1, Ordering::Relaxed);
198 if r >= ranges || queues.abandoned() {
199 return;
200 }
201 crate::tiler::merge_range_into(
202 chunks_ref,
203 spill_ref,
204 range_plan,
205 r,
206 queues.sender(r),
207 );
208 });
209 }
210 let mut stream =
211 crate::tiler::MergeStream::Parallel(crate::tiler::ParallelMerge::new(
212 std::sync::Arc::clone(&queues),
213 ));
214 consume_merged(
215 &mut stream,
216 &mut stats,
217 z,
218 timer,
219 &settings.dem,
220 store.conventions(),
221 &settings.region_links,
222 writer,
223 )?;
224 Ok(())
225 })?;
226 } else {
227 let mut stream = crate::tiler::MergeStream::Serial(merge(&chunks, &spill));
228 consume_merged(
229 &mut stream,
230 &mut stats,
231 z,
232 timer,
233 &settings.dem,
234 store.conventions(),
235 &settings.region_links,
236 writer,
237 )?;
238 }
239 // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries
240 // would produce an archive with holes in it and nothing downstream could tell.
241 spill.check_books()?;
242 per_zoom.push(stats);
243 }
244
245 Ok(per_zoom)
246}
247
248/// The entry gate for the range-parallel merge: big supported zoom on a
249/// multi-thread box.
250///
251/// Split out so the call site reads as intent rather than inline conditions.
252/// z0–z3 stay serial however threaded: they can't invert their bucket edges
253/// exactly, so they have one path and no divergence to compare.
254fn merge_gate(chunks: &[ChunkRef], z: u8) -> bool {
255 let total_entries: u64 = chunks.iter().map(|c| c.entries).sum();
256 let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS);
257 total_entries >= crate::tiler::PARALLEL_MERGE_MIN_ENTRIES
258 && merge_workers > 1
259 && crate::tiler::parallel_merge_supported(z)
260}
261
262include!("tiler_part1_s1.rs");
263include!("tiler_part1_s2.rs");