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

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

mem.rs428 lines · 17.4 KiBRaw
1//! Peak resident set size, so a build reports its own memory ceiling.
2//!
3//! The planet-scale gates for `road_graph` are memory gates: the question is
4//! never "did it finish" but "how close did it come to the box". Having the tool
5//! print its own `VmHWM` means every run is a measurement, including the ones
6//! nobody thought to instrument, and it removes the step where a gate is judged
7//! from a `top` reading somebody happened to catch.
8//!
9//! `VmHWM` is a high-water *mark*, so it survives the frees that a `top` sample
10//! between two phases would miss. It does not include the page cache or dirty
11//! pages, which is the one thing it cannot answer and the reason the graph
12//! writer prefers sequential writes to computed-offset ones.
13
14/// Peak RSS in bytes, or `None` where the platform does not expose it.
15///
16/// Only Linux is implemented: that is where the scale gates run, and the
17/// alternative on other platforms is a raw FFI declaration to carry a number
18/// nothing reads.
19pub fn peak_rss_bytes() -> Option<u64> {
20 #[cfg(target_os = "linux")]
21 {
22 let status = std::fs::read_to_string("/proc/self/status").ok()?;
23 parse_vm_hwm(&status)
24 }
25 #[cfg(not(target_os = "linux"))]
26 {
27 None
28 }
29}
30
31/// `VmHWM:\t 123456 kB` -> bytes.
32#[cfg(any(target_os = "linux", test))]
33fn parse_vm_hwm(status: &str) -> Option<u64> {
34 let line = status.lines().find(|l| l.starts_with("VmHWM:"))?;
35 let kb: u64 = line.split_whitespace().nth(1).and_then(|v| v.parse().ok())?;
36 Some(kb * 1024)
37}
38
39/// `"4.97 GB"`, or a note that the platform does not report it. Callers put this
40/// straight into a log line.
41pub fn peak_rss_report() -> String {
42 match peak_rss_bytes() {
43 Some(b) => format!("{:.2} GB", b as f64 / (1u64 << 30) as f64),
44 None => "not reported on this platform".to_string(),
45 }
46}
47
48/// A file mapped read-only, dereferencing to its bytes.
49///
50/// The same bytes `std::fs::read` would hand back, but paged by the OS instead of copied onto the
51/// heap: no commit charge up front (which is what `mmap(MAP_ANON)` spills pay but file mappings do
52/// not), and the resident cost is the working set rather than the file. Junction walks
53/// `nodes.bin` in order and probes `edges.bin`/`intermediate.bin` positionally, so this is strictly
54/// cheaper than the `Vec<u8>` it replaces.
55///
56/// The mapping owns its `File` so the handle outlives every read; an empty file maps to an empty
57/// slice rather than erroring, so callers keep their own length checks and their own messages.
58pub struct Mapped {
59 // Held so the mapping's file description outlives the reads. Never read through directly.
60 _file: std::fs::File,
61 map: Option<memmap2::Mmap>,
62}
63
64impl Mapped {
65 pub fn open(path: &std::path::Path) -> Result<Mapped, String> {
66 let file = std::fs::File::open(path)
67 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
68 let len =
69 file.metadata().map_err(|e| format!("cannot stat {}: {e}", path.display()))?.len();
70 // `memmap2` refuses an empty file; an empty graph file is a length error the caller
71 // reports, not a mapping error here.
72 let map = if len == 0 {
73 None
74 } else {
75 // SAFETY: read-only, and the file is never truncated while mapped -- every writer in
76 // this tree creates with `truncate` and closes before any reader opens.
77 Some(
78 unsafe { memmap2::Mmap::map(&file) }
79 .map_err(|e| format!("cannot map {}: {e}", path.display()))?,
80 )
81 };
82 Ok(Mapped { _file: file, map })
83 }
84}
85
86impl std::ops::Deref for Mapped {
87 type Target = [u8];
88
89 fn deref(&self) -> &[u8] {
90 self.map.as_deref().unwrap_or(&[])
91 }
92}
93
94// --- budgets: how much commit and disk a phase may ask for -------------------------------
95//
96// The planet build died at the junction tail with `cannot commit anon segment` (OS error 1455):
97// anonymous spills charge RAM+pagefile ("commit"), and nothing checked the charge against the
98// limit before asking. These queries let each phase size its request from counts it already has
99// (node/way/relation counts, graph metadata) and either pick a file backend or fail fast with
100// numbers, instead of paging 1767 s into stage A.
101//
102// All `Option`: a platform that cannot answer (or a sandboxed `/proc`) warns and proceeds with
103// the historical behaviour rather than refusing to build.
104
105/// Bytes of commit (RAM + pagefile) the OS will still grant, or `None` if unknown.
106///
107/// Windows: `ullAvailPageFile` -- the number 1455 is charged against. Linux: `CommitLimit - Committed_AS`.
108pub fn commit_avail_bytes() -> Option<u64> {
109 #[cfg(windows)]
110 {
111 let st = memory_status()?;
112 Some(st.ull_avail_page_file)
113 }
114 #[cfg(target_os = "linux")]
115 {
116 let info = proc_meminfo()?;
117 Some(info.commit_limit?.saturating_sub(info.committed_as?))
118 }
119 #[cfg(not(any(windows, target_os = "linux")))]
120 {
121 None
122 }
123}
124
125/// The commit ceiling itself, for messages (`need X of Y`).
126pub fn commit_limit_bytes() -> Option<u64> {
127 #[cfg(windows)]
128 {
129 Some(memory_status()?.ull_total_page_file)
130 }
131 #[cfg(target_os = "linux")]
132 {
133 proc_meminfo()?.commit_limit
134 }
135 #[cfg(not(any(windows, target_os = "linux")))]
136 {
137 None
138 }
139}
140
141/// Bytes free for the caller on the volume holding `path`, or `None` if unknown.
142pub fn disk_free_bytes(path: &std::path::Path) -> Option<u64> {
143 #[cfg(windows)]
144 {
145 use std::os::windows::ffi::OsStrExt;
146 let dir = path.parent().unwrap_or(path);
147 let mut wide: Vec<u16> = dir.as_os_str().encode_wide().collect();
148 wide.push(0);
149 let mut avail: u64 = 0;
150 // SAFETY: `wide` is null-terminated and outlives the call; the three trailing
151 // pointers are valid `*mut u64` or null, and null is accepted for the totals.
152 let ok = unsafe {
153 platform::GetDiskFreeSpaceExW(
154 wide.as_ptr(),
155 &mut avail,
156 std::ptr::null_mut(),
157 std::ptr::null_mut(),
158 )
159 };
160 (ok != 0).then_some(avail)
161 }
162 #[cfg(target_os = "linux")]
163 {
164 let dir = path.parent().unwrap_or(path);
165 let cstr = std::ffi::CString::new(dir.as_os_str().as_encoded_bytes()).ok()?;
166 // SAFETY: `cstr` is a valid null-terminated path; `statvfs` only reads through it.
167 let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
168 if unsafe { libc::statvfs(cstr.as_ptr(), &mut st) } != 0 {
169 return None;
170 }
171 (st.f_bavail as u64).checked_mul(st.f_bsize as u64)
172 }
173 #[cfg(not(any(windows, target_os = "linux")))]
174 {
175 let _ = path;
176 None
177 }
178}
179
180#[cfg(target_os = "linux")]
181struct Meminfo {
182 commit_limit: Option<u64>,
183 committed_as: Option<u64>,
184}
185
186#[cfg(target_os = "linux")]
187fn proc_meminfo() -> Option<Meminfo> {
188 let text = std::fs::read_to_string("/proc/meminfo").ok()?;
189 let mut out = Meminfo { commit_limit: None, committed_as: None };
190 for line in text.lines() {
191 // `CommitLimit: 123456 kB` -- the field width varies, the unit does not.
192 let mut parts = line.split_whitespace();
193 let (key, value) = (parts.next()?, parts.next()?);
194 let kb: u64 = value.parse().ok()?;
195 match key {
196 "CommitLimit:" => out.commit_limit = Some(kb.saturating_mul(1024)),
197 "Committed_AS:" => out.committed_as = Some(kb.saturating_mul(1024)),
198 _ => {}
199 }
200 }
201 Some(out)
202}
203
204/// What stage A expects to hold at once, sized from counts pass 1 already measured.
205///
206/// Everything here is known before the bytes are asked for: `way_refs`/`way_max_ref` come from
207/// [`WaySink::finish`](crate::store::WaySink) (every ref walked to encode it), `distinct` from
208/// the collector, the ways-spill length from the sealed store, the feature estimate from the
209/// feature count times a calibrated bytes-per-feature, and the graph from `metadata.bin`'s 40-byte
210/// header. The gate compares the sum against the commit limit and the spill volume's disk free
211/// and either picks the file backend or fails fast naming the numbers -- instead of paging 1767 s
212/// in with `cannot commit anon segment`.
213///
214/// Relations move the needle less (8.4 M vs 1.1 B ways on planet) and are counted approximately:
215/// member refs are already inside `distinct`; the `Relation` structs themselves are `members *
216/// overhead`, estimated, not measured.
217#[derive(Debug, Default, Clone)]
218pub struct StageBudget {
219 /// Distinct node ids the coordinate table must hold.
220 pub distinct_nodes: u64,
221 /// Largest node id the bitset/rank index is sized over.
222 pub max_node_id: u64,
223 /// Sealed ways-spill bytes (the delta-coded classified ways).
224 pub ways_spill_bytes: u64,
225 /// Features already spilled (labels so far); times `bytes_per_feature` for the spill so far.
226 pub features_spilled: u64,
227 /// Features still to come (ways + relations + externals, estimated from classified counts).
228 pub features_expected: u64,
229 /// Calibrated spill bytes per feature (measure one small build, reuse everywhere).
230 pub bytes_per_feature: u64,
231 /// Routing-graph bytes that must be addressable at once (nodes+edges+intermediate+lanes files
232 /// plus the `InEdges` reverse index), from `metadata.bin` before anything is mapped.
233 pub graph_bytes: u64,
234 /// Resident relation-member table entries (relation count), estimated overhead each.
235 pub relations: u64,
236}
237
238impl StageBudget {
239 /// Rank bitset + directory over `0..=max_node_id`: `max/8` words plus one prefix-sum u64 per
240 /// 8 words. The collector's own bitset is already folded in (see `from_bitset`): this is the
241 /// one surviving copy.
242 pub fn rank_bytes(&self) -> u64 {
243 let words = (self.max_node_id.saturating_add(1)).div_ceil(64);
244 words.saturating_mul(8).saturating_add(words.div_ceil(8).saturating_mul(8))
245 }
246
247 /// Per-node resolved bit (`distinct/8`) plus the mapped coordinate file (`distinct*8`).
248 /// The file is disk-backed, not commit, but it still has to fit the volume -- counted in
249 /// `disk_bytes` rather than here.
250 pub fn resolved_bytes(&self) -> u64 {
251 self.distinct_nodes.div_ceil(8)
252 }
253
254 /// Coordinate file bytes on the temp volume.
255 pub fn locs_file_bytes(&self) -> u64 {
256 self.distinct_nodes.saturating_mul(8)
257 }
258
259 /// Relation structs kept resident between passes (members table + `Relation` vec).
260 pub fn relations_bytes(&self) -> u64 {
261 // ~64 B per relation entry (HashMap node + Vec header + struct) plus ~16 B per member id.
262 // Approximate: the members' refs are already inside `distinct_nodes`; this is the structs.
263 self.relations.saturating_mul(96)
264 }
265
266 /// Feature spill so far plus what is still to come.
267 pub fn feature_spill_bytes(&self) -> u64 {
268 self.features_spilled
269 .saturating_add(self.features_expected)
270 .saturating_mul(self.bytes_per_feature.max(1))
271 }
272
273 /// Commit charged if everything stages anonymously: rank + resolved + ways spill +
274 /// the feature spill (the graph is the caller's choice -- see `plan`).
275 ///
276 /// The feature spill used to be missing here, so a planet gate compared ~43 GB
277 /// (rank + resolved + ways) against the allowance while the anon feature spill
278 /// itself needed hundreds of GB more. The build then paid for it 1767 s in with
279 /// `cannot commit anon segment` -- or, when it survived stage A, left the tiling
280 /// phase with no commit headroom and OOM'd merging z14. Counting it pushes
281 /// planet-scale builds to files (same records, removed on success), which is the
282 /// safe side.
283 pub fn anon_commit_bytes(&self) -> u64 {
284 self.rank_bytes()
285 .saturating_add(self.resolved_bytes())
286 .saturating_add(self.ways_spill_bytes)
287 .saturating_add(self.feature_spill_bytes())
288 }
289
290 /// Disk needed on the spill volume if the spills go to files: ways spill + feature spill +
291 /// locs file.
292 pub fn disk_bytes(&self) -> u64 {
293 self.ways_spill_bytes
294 .saturating_add(self.feature_spill_bytes())
295 .saturating_add(self.locs_file_bytes())
296 }
297}
298
299/// Which backend a spill stages in, and why.
300///
301/// Anonymous memory charges commit (RAM+pagefile) and needs no directory entry; files charge the
302/// spill volume's free space and survive nothing on kill (existing `Drop` impls remove them).
303/// Same records, same offsets, same output bytes either way -- the backend never changes a hash.
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum SpillPlan {
306 /// Commit headroom covers the anon charge with margin: keep the historical behaviour.
307 Anon,
308 /// Commit is tight or the estimate exceeds it: stage in files on the spill volume instead.
309 /// No retained storage growth -- the files are removed on success like every other `.tmp`.
310 File,
311}
312
313impl SpillPlan {
314 /// Decide from a budget, the spill path (for its volume's free space) and a safety margin.
315 ///
316 /// Fails fast with the numbers when *neither* backend fits: that build cannot succeed on this
317 /// machine, and saying so in seconds beats `cannot commit anon segment` after 1767 s. `context`
318 /// names the phase (`"stage A ways spill"`) so the message says where the bytes go.
319 pub fn decide(
320 budget: &StageBudget,
321 spill_path: &std::path::Path,
322 context: &str,
323 ) -> Result<SpillPlan, String> {
324 // Half the commit limit is the most anon staging may claim: the other half is the heap
325 // (relations, members, rayon buffers), the mapped graph, and the OS itself. A build that
326 // needs more anon than that is one bad estimate from 1455.
327 const ANON_SHARE_NUM: u64 = 1;
328 const ANON_SHARE_DEN: u64 = 2;
329 let need_anon = budget.anon_commit_bytes();
330 let need_disk = budget.disk_bytes();
331 // Test knob: take the file backend whatever the budget says, so a regional extract runs
332 // the planet's code path (file-staged spills) for profiling. Same records either way.
333 if std::env::var_os("MAPS_FORCE_FILE_SPILL").is_some() {
334 return Ok(SpillPlan::File);
335 }
336
337 match (commit_avail_bytes(), commit_limit_bytes(), disk_free_bytes(spill_path)) {
338 (Some(avail), Some(limit), disk) => {
339 let allowance = limit / ANON_SHARE_DEN * ANON_SHARE_NUM;
340 if need_anon <= allowance.min(avail) {
341 return Ok(SpillPlan::Anon);
342 }
343 // Anon does not fit: files do if the volume holds them.
344 match disk {
345 Some(free) if need_disk <= free => Ok(SpillPlan::File),
346 Some(free) => Err(format!(
347 "{context}: needs {} commit for anon staging ({} avail of {}) and {} on \
348 {} for file staging ({} free) -- neither fits; free pagefile or point \
349 the spill at a larger volume",
350 fmt_gb(need_anon),
351 fmt_gb(avail),
352 fmt_gb(limit),
353 fmt_gb(need_disk),
354 spill_path.display(),
355 fmt_gb(free),
356 )),
357 None => Err(format!(
358 "{context}: needs {} commit for anon staging ({} avail of {}), and the \
359 spill volume's free space is unknown -- refusing anon rather than \
360 risking OS error 1455",
361 fmt_gb(need_anon),
362 fmt_gb(avail),
363 fmt_gb(limit),
364 )),
365 }
366 }
367 // Unknown limits (non-Windows/Linux, sandbox): historical behaviour, no gate.
368 _ => Ok(SpillPlan::Anon),
369 }
370 }
371}
372
373/// `"12.34 GB"` for budget messages.
374pub fn fmt_gb(bytes: u64) -> String {
375 format!("{:.2} GB", bytes as f64 / (1u64 << 30) as f64)
376}
377
378#[cfg(windows)]
379struct MemoryStatus {
380 ull_total_page_file: u64,
381 ull_avail_page_file: u64,
382}
383
384#[cfg(windows)]
385fn memory_status() -> Option<MemoryStatus> {
386 // SAFETY: `st` is a valid `MEMORYSTATUSEX`-layout struct with `dw_length` set, which is the
387 // one precondition `GlobalMemoryStatusEx` documents.
388 unsafe {
389 let mut st: platform::MemoryStatusEx = std::mem::zeroed();
390 st.dw_length = std::mem::size_of::<platform::MemoryStatusEx>() as u32;
391 if platform::GlobalMemoryStatusEx(&mut st) == 0 {
392 return None;
393 }
394 Some(MemoryStatus {
395 ull_total_page_file: st.ull_total_page_file,
396 ull_avail_page_file: st.ull_avail_page_file,
397 })
398 }
399}
400
401#[cfg(windows)]
402mod platform {
403 #[repr(C)]
404 pub struct MemoryStatusEx {
405 pub dw_length: u32,
406 pub dw_memory_load: u32,
407 pub ull_total_phys: u64,
408 pub ull_avail_phys: u64,
409 pub ull_total_page_file: u64,
410 pub ull_avail_page_file: u64,
411 pub ull_total_virtual: u64,
412 pub ull_avail_virtual: u64,
413 pub ull_avail_extended_virtual: u64,
414 }
415
416 #[link(name = "kernel32")]
417 extern "system" {
418 pub fn GlobalMemoryStatusEx(lpBuffer: *mut MemoryStatusEx) -> i32;
419 pub fn GetDiskFreeSpaceExW(
420 lpDirectoryName: *const u16,
421 lpFreeBytesAvailable: *mut u64,
422 lpTotalNumberOfBytes: *mut u64,
423 lpTotalNumberOfFreeBytes: *mut u64,
424 ) -> i32;
425 }
426}
427
428include!("mem_s1.rs");