type EncodedBatch = (Vec, usize, u64, u64); /// Tile every feature and write the archive. /// Tile every feature in `store` into a `.mamaps` archive. /// /// The store is read **once per zoom**, in order, rather than held in memory for all of them. Fifteen /// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of /// a measured 10.03 GB California peak. #[cfg(test)] pub fn build(store: &Store, settings: &Settings) -> Result<(Vec, Vec)> { adopt_thread_budget(); let mut writer = writer_for(store, settings)?; // Tests share the zoom loop but report no phase: the timer is dropped without `finish`, // so no `TIMING` line ever reaches test output. let mut timer = crate::timing::PhaseTimer::start("tiles"); let per_zoom = tile_zooms(store, settings, &mut writer, &mut timer)?; let bytes = writer.finish()?; Ok((bytes, per_zoom)) } /// Tile every feature in `store` straight into the archive at `out`, without ever holding the /// archive in memory. /// /// `build` above returns the whole archive as a `Vec` -- fine for tests, fatal for a planet: /// the data section alone is tens of GB, and holding it beside the merge's own peak is what OOMs /// a box with ~50 GB of commit headroom right after z14 merges. This runs the identical zoom loop /// ([`tile_zooms`]) and finishes through [`StreamWriter::finish_to_path`], so the only thing ever /// held is the prefix (the index, small next to the bodies). Same tiles, same order, same bytes: /// the writer appends identically either way, and `finish_to_path` assembles the same /// header/dictionary/root/leaves/data layout as `finish`. pub fn build_to_path( store: &Store, settings: &Settings, out: &std::path::Path, timer: &mut crate::timing::PhaseTimer, ) -> Result> { adopt_thread_budget(); let mut writer = writer_for(store, settings)?; let per_zoom = tile_zooms(store, settings, &mut writer, timer)?; writer.finish_to_path(out)?; Ok(per_zoom) } /// The [`StreamWriter`] for a build: zoom range, build id, compression, and the body scratch /// beside the output. /// /// The scratch placement matters: the writer spills the data section (tens of GB on a planet) /// through a temp file, and the default is the system temp dir -- routinely a small system /// volume. Beside the output it shares the volume the operator already sized for the build /// (feature spill, tile chunks, archive), and it is removed on drop like every other scratch /// file. Path only, never bytes: the archive is identical wherever the scratch lives. fn writer_for(store: &Store, settings: &Settings) -> Result { let bbox = store.bbox(); StreamWriter::new(Options { min_zoom: 0, max_zoom: crate::DEFAULT_MAX_ZOOM, build_id: settings.build_id, // The header carries the seed folded with the digest of every tile written: identical // tiles from identical inputs give an identical id anywhere (see `derive_build_id`). build_id_from_content: true, compress: true, // Stage C runs on every tile below, so the claim is true. It is what lets the renderer // skip its repair pass — and the renderer still keeps that pass, gated, because a claim is // only as good as the generator making it. rings_validated: true, min_lon_e7: bbox.0, min_lat_e7: bbox.1, max_lon_e7: bbox.2, max_lat_e7: bbox.3, spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf), // Leaf compression at finish runs on the build's own thread budget. threads: par::threads(), // The body scratch holds already-DEFLATEd bodies (~53 GB on a planet): keep btrfs // `compress-force` from zstd'ing them again at writeback. spill_file_hook: Some(osm_ingest::mem::mark_scratch_uncompressed), // `--body-zstd`: the header says zstd; the encode worker compresses with it. zstd: size_opts().zstd_level > 0, ..Options::default() }) } /// The zoom loop both builders share: map, merge, encode and append z0..=z14 through `writer`. /// /// Extracted whole from `build` so the two finishes cannot diverge: the per-zoom stats, the /// progress bars, the `check_books` gate and the append order are identical, and only the final /// assembly differs (in-memory vs streaming). fn tile_zooms( store: &Store, settings: &Settings, writer: &mut StreamWriter, timer: &mut crate::timing::PhaseTimer, ) -> Result> { let mut per_zoom = Vec::new(); // The tile-chunk spill's backend, decided once from the feature count: z14 holds the most // clipped copies at once (the 53 GB north-america case that motivated the spill), so sizing // for the whole store is the safe side. Per-zoom files share one scratch path -- each zoom's // spill truncates it on create and removes it on drop, so peak disk is still the largest // single zoom. let chunk_plan = plan_chunk_spill(store, &settings.scratch); // The operator's override wins over the gate: `force_chunk_spill_file` (from // `MAPS_ANON_SPILL`, unset or non-`1`) stages through the scratch file even when the gate // picks anon. Same chunks, same bytes, no commit charge for the merge to trip over. let chunk_plan = if settings.force_chunk_spill_file && chunk_plan == osm_ingest::mem::SpillPlan::Anon { eprintln!( " [tiler] chunk spill -> {} (file backend: MAPS_ANON_SPILL)", settings.scratch.display(), ); osm_ingest::mem::SpillPlan::File } else { chunk_plan }; for z in 0..=crate::DEFAULT_MAX_ZOOM { let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() }; let tolerance = simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, DEFAULT_SIMPLIFICATION) * size_opts().simplify_scale; let buffer = geom::buffer_for(EXTENT); // Per zoom, so peak scratch is the largest single zoom rather than the sum, and so a build // that dies at z14 leaves one zoom behind rather than fifteen. Anonymous // pagefile-backed memory (no file) when commit allows, else the scratch file; the merge // reads through the same ChunkReader either way. let spill = ChunkSpill::create_planned(&settings.scratch, chunk_plan)?; // Per-zoom `map`: repeat visits merge into one total at `finish`. timer.switch("map"); let mapped = std::time::Instant::now(); let (chunks, tally) = map_zoom(store, settings, z, tolerance, buffer, &spill)?; stats.map_ms = mapped.elapsed().as_millis() as u64; stats.features = tally.features; stats.points = tally.points; stats.dropped = tally.dropped; // Ascending by tile id because the merge makes it so, not because a sort step was // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the // single-threaded `BTreeMap` gave; the maps now live on disk and the guarantee does not // change, because a chunk's bytes are written in its key order and read back in file order. // // Range-parallel merge when the zoom repays planning: one worker k-way merges each // cost-balanced tile range (see `tiler_part3::merge_parallel`), drained in order by the // same consume loop below — sequence-identical to serial, so batches, prune and append // are untouched. Small zooms stay serial: planning costs more than it saves there. So do // z0–z3, whose tile spans (1–64) don't divide by the 256 cost buckets — the bucket table // can't invert those edges exactly (see `parallel_merge_supported`). // // The choice is `merge_gate` below, hardcoded: no environment override. // Operator control arrives through `--threads`/`MAPS_THREADS` (which sizes the // worker count) exactly like every other parallel stage in this tree. let merge_parallel = merge_gate(&chunks, z); if merge_parallel { let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS); // One worker owns the whole tile space on a one-thread box, which is // the serial sequence by construction — correctness never depends on // the count, only speed does. let merge_workers = merge_workers.max(1); // Timed as its own subphase: the planning scan is a serial // skip-walk over every chunk, and at z14 it is large enough to // matter against the merge it parallelises. timer.switch("merge-plan"); let planning = std::time::Instant::now(); // Many more ranges than workers (see `plan_ranges_auto`): workers claim ranges in // order and the coordinator drains them in order, so `merge_workers` consecutive // ranges merge at once instead of one range at a time behind a full run-ahead budget. let plan = crate::tiler::plan_ranges_auto(&chunks, &spill, z, merge_workers)?; let ranges = plan.bounds.len() - 1; stats.merge_ms += planning.elapsed().as_millis() as u64; // One line per zoom on the parallel path: the spread of per-range cost estimates. // `hot` is the costliest single tile: ranges assign whole tiles, so no range can go // below it however they split. let (lo, hi) = plan .range_cost .iter() .fold((u64::MAX, 0u64), |(lo, hi), &c| (lo.min(c), hi.max(c))); eprintln!( " [merge] z{z}: {ranges} range(s) on {merge_workers} worker(s), cost {lo}..{hi} per range, hot tile {} at {}, entries {}, planned in {:.1}s", plan.hot_tile, plan.hot_cost, plan.remaining .iter() .map(|row| row.iter().sum::()) .sum::(), planning.elapsed().as_secs_f64(), ); let queues = crate::tiler::RangeQueues::new(ranges); let claim = AtomicUsize::new(0); std::thread::scope(|s| -> Result<()> { // Shared refs are `Copy`: each spawned closure gets its own // copy rather than moving `chunks`/`spill` on first use. let chunks_ref = &chunks; let spill_ref = &spill; let range_plan = &plan; for _ in 0..merge_workers.min(ranges) { let (queues, claim) = (&queues, &claim); s.spawn(move || loop { let r = claim.fetch_add(1, Ordering::Relaxed); if r >= ranges || queues.abandoned() { return; } crate::tiler::merge_range_into( chunks_ref, spill_ref, range_plan, r, queues.sender(r), ); }); } let mut stream = crate::tiler::MergeStream::Parallel(crate::tiler::ParallelMerge::new( std::sync::Arc::clone(&queues), )); consume_merged( &mut stream, &mut stats, z, timer, &settings.dem, store.conventions(), &settings.region_links, writer, )?; Ok(()) })?; } else { let mut stream = crate::tiler::MergeStream::Serial(merge(&chunks, &spill)); consume_merged( &mut stream, &mut stats, z, timer, &settings.dem, store.conventions(), &settings.region_links, writer, )?; } // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries // would produce an archive with holes in it and nothing downstream could tell. spill.check_books()?; per_zoom.push(stats); } Ok(per_zoom) } /// The entry gate for the range-parallel merge: big supported zoom on a /// multi-thread box. /// /// Split out so the call site reads as intent rather than inline conditions. /// z0–z3 stay serial however threaded: they can't invert their bucket edges /// exactly, so they have one path and no divergence to compare. fn merge_gate(chunks: &[ChunkRef], z: u8) -> bool { let total_entries: u64 = chunks.iter().map(|c| c.entries).sum(); let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS); total_entries >= crate::tiler::PARALLEL_MERGE_MIN_ENTRIES && merge_workers > 1 && crate::tiler::parallel_merge_supported(z) } include!("tiler_part1_s1.rs"); include!("tiler_part1_s2.rs");