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