Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / anon.rs
anon.rs202 lines · 7.6 KiBRaw
| 1 | //! Anonymous pagefile-backed scratch: virtual memory with no file behind it. |
| 2 | //! |
| 3 | //! The spill backends ([`crate::spill::NormalizedWriter`], `ChunkSpill`) stage |
| 4 | //! hundreds of gigabytes through temp files — `tiles.features.tmp` alone hits |
| 5 | //! ~300GB on a world build. Every one of those files is write-once then read |
| 6 | //! positionally (offsets, never paths), which is exactly what an anonymous |
| 7 | //! mapping serves: `memmap2::MmapMut::map_anon` reserves address space backed |
| 8 | //! by the pagefile, no directory entry, no cleanup on kill. |
| 9 | //! |
| 10 | //! On Windows this is `MapViewOfFile(INVALID_HANDLE_VALUE)`: commit charge |
| 11 | //! against RAM + pagefile, paged by the OS like any other memory. It does NOT |
| 12 | //! reduce the bytes — a 300GB spill still needs 300GB of commit — it removes |
| 13 | //! the *file*: no 6x-free-disk preflight, no stranded `.tmp` on kill, no |
| 14 | //! delete pass. The pagefile cap is the bound (check `Win32_PageFileSetting`; |
| 15 | //! system-managed is what a world build wants). |
| 16 | //! |
| 17 | //! Growth: mappings don't grow, so this reserves in 1GB segments and chains |
| 18 | //! them. Readers see one contiguous `&[u8]` via segment lookup — offsets stay |
| 19 | //! plain `u64`, identical to file offsets, so every call site keeps working. |
| 20 | |
| 21 | use crate::proto::{err, Error, Result}; |
| 22 | |
| 23 | /// One mapping segment. 256MB: large enough that a 300GB spill is ~1200 segments |
| 24 | /// (a small table), small enough that the tail wastes at most 256MB of commit. |
| 25 | /// Was 1GB; the tail waste is per store and there are two large ones (ways + |
| 26 | /// features), so planet builds paid up to 2GB of commit for partial tails. |
| 27 | const SEGMENT_BYTES: usize = 1 << 28; |
| 28 | |
| 29 | /// A growable anonymous byte store with file-like offsets. |
| 30 | /// |
| 31 | /// Write-once, then positional reads: `push` appends, `finish` seals, and |
| 32 | /// `read_at` serves any range. Offsets are `u64` from zero, exactly like the |
| 33 | /// file offsets the spill index already records — swapping the backend changes |
| 34 | /// no index, no record format, no byte of output. |
| 35 | pub struct AnonStore { |
| 36 | segments: Vec<memmap2::MmapMut>, |
| 37 | /// Committed (written) length. Reads past this are corruption, same as a |
| 38 | /// short read off the file. |
| 39 | len: u64, |
| 40 | sealed: bool, |
| 41 | } |
| 42 | |
| 43 | impl AnonStore { |
| 44 | pub fn new() -> AnonStore { |
| 45 | AnonStore { segments: Vec::new(), len: 0, sealed: false } |
| 46 | } |
| 47 | |
| 48 | /// Append `bytes`, returning the offset they start at. |
| 49 | pub fn push(&mut self, bytes: &[u8]) -> Result<u64> { |
| 50 | if self.sealed { |
| 51 | return err("an anon store is sealed: no more writes".to_string()); |
| 52 | } |
| 53 | let at = self.len; |
| 54 | self.write_at(at, bytes)?; |
| 55 | Ok(at) |
| 56 | } |
| 57 | |
| 58 | /// Write `bytes` at `offset`, growing the store as needed. Workers reserve |
| 59 | /// ranges concurrently and flush out of order, so `offset` may lie past |
| 60 | /// the current length — the reservation cursor guarantees the ranges are |
| 61 | /// back-to-back and `check_books` verifies reserved == written at the end. |
| 62 | /// Bytes past the current length read as zero until written (same as a |
| 63 | /// sparse file), but every reserved byte is written before the merge |
| 64 | /// reads, so no reader ever sees the gap. |
| 65 | pub fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result<()> { |
| 66 | if self.sealed { |
| 67 | return err("an anon store is sealed: no more writes".to_string()); |
| 68 | } |
| 69 | let end = offset.checked_add(bytes.len() as u64).ok_or_else(|| { |
| 70 | Error("an anon store write overflows".to_string()) |
| 71 | })?; |
| 72 | let mut at = offset; |
| 73 | let mut rest = bytes; |
| 74 | while !rest.is_empty() { |
| 75 | let seg_idx = (at as usize) / SEGMENT_BYTES; |
| 76 | let seg_off = (at as usize) % SEGMENT_BYTES; |
| 77 | while seg_idx >= self.segments.len() { |
| 78 | let map = memmap2::MmapMut::map_anon(SEGMENT_BYTES) |
| 79 | .map_err(|e| Error(format!("cannot commit anon segment: {e}")))?; |
| 80 | self.segments.push(map); |
| 81 | } |
| 82 | let room = SEGMENT_BYTES - seg_off; |
| 83 | let take = room.min(rest.len()); |
| 84 | self.segments[seg_idx][seg_off..seg_off + take].copy_from_slice(&rest[..take]); |
| 85 | at += take as u64; |
| 86 | rest = &rest[take..]; |
| 87 | } |
| 88 | self.len = self.len.max(end); |
| 89 | Ok(()) |
| 90 | } |
| 91 | |
| 92 | /// Seal: no more writes. Reads are valid from here on. |
| 93 | pub fn finish(&mut self) { |
| 94 | self.sealed = true; |
| 95 | } |
| 96 | |
| 97 | pub fn len(&self) -> u64 { |
| 98 | self.len |
| 99 | } |
| 100 | |
| 101 | pub fn is_empty(&self) -> bool { |
| 102 | self.len == 0 |
| 103 | } |
| 104 | |
| 105 | /// Copy `out.len()` bytes from `offset` into `out`. Bounds-checked like a |
| 106 | /// file read: past-`len` is an error, not a zero fill. |
| 107 | pub fn read_at(&self, mut offset: u64, mut out: &mut [u8]) -> Result<()> { |
| 108 | let end = offset.checked_add(out.len() as u64).ok_or_else(|| { |
| 109 | Error("an anon store read overflows".to_string()) |
| 110 | })?; |
| 111 | if end > self.len { |
| 112 | return err(format!( |
| 113 | "an anon store read of {} byte(s) at {offset} runs past its {len}", |
| 114 | out.len(), |
| 115 | len = self.len, |
| 116 | )); |
| 117 | } |
| 118 | while !out.is_empty() { |
| 119 | let seg_idx = (offset as usize) / SEGMENT_BYTES; |
| 120 | let seg_off = (offset as usize) % SEGMENT_BYTES; |
| 121 | let take = (SEGMENT_BYTES - seg_off).min(out.len()); |
| 122 | out[..take].copy_from_slice(&self.segments[seg_idx][seg_off..seg_off + take]); |
| 123 | offset += take as u64; |
| 124 | out = &mut out[take..]; |
| 125 | } |
| 126 | Ok(()) |
| 127 | } |
| 128 | |
| 129 | /// A borrowed slice for `len` bytes at `offset`, when the range sits in |
| 130 | /// one segment. Avoids the copy for hot paths; falls back to `read_at` |
| 131 | /// into a scratch buffer when it straddles. |
| 132 | pub fn slice_at(&self, offset: u64, len: usize) -> Result<&[u8]> { |
| 133 | let end = (offset as usize).checked_add(len).ok_or_else(|| { |
| 134 | Error("an anon store slice overflows".to_string()) |
| 135 | })?; |
| 136 | if end as u64 > self.len { |
| 137 | return err(format!( |
| 138 | "an anon store slice of {len} byte(s) at {offset} runs past its {l}", |
| 139 | l = self.len, |
| 140 | )); |
| 141 | } |
| 142 | let seg_idx = (offset as usize) / SEGMENT_BYTES; |
| 143 | let seg_off = (offset as usize) % SEGMENT_BYTES; |
| 144 | if seg_off + len <= SEGMENT_BYTES { |
| 145 | Ok(&self.segments[seg_idx][seg_off..seg_off + len]) |
| 146 | } else { |
| 147 | err("an anon store slice straddles segments: use read_at".to_string()) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl Default for AnonStore { |
| 153 | fn default() -> Self { |
| 154 | Self::new() |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[cfg(test)] |
| 159 | mod tests { |
| 160 | use super::*; |
| 161 | |
| 162 | #[test] |
| 163 | fn a_push_reads_back_at_its_own_offset() { |
| 164 | let mut s = AnonStore::new(); |
| 165 | let a = s.push(b"hello").expect("push"); |
| 166 | let b = s.push(b"world!").expect("push"); |
| 167 | assert_eq!(a, 0); |
| 168 | assert_eq!(b, 5); |
| 169 | s.finish(); |
| 170 | let mut out = [0u8; 5]; |
| 171 | s.read_at(0, &mut out).expect("read"); |
| 172 | assert_eq!(&out, b"hello"); |
| 173 | let mut out2 = [0u8; 6]; |
| 174 | s.read_at(5, &mut out2).expect("read"); |
| 175 | assert_eq!(&out2, b"world!"); |
| 176 | } |
| 177 | |
| 178 | #[test] |
| 179 | fn a_read_past_the_end_is_an_error_not_a_zero_fill() { |
| 180 | let mut s = AnonStore::new(); |
| 181 | s.push(b"hi").expect("push"); |
| 182 | s.finish(); |
| 183 | let mut out = [0u8; 3]; |
| 184 | assert!(s.read_at(0, &mut out).is_err()); |
| 185 | assert!(s.read_at(2, &mut out[..1]).is_err()); |
| 186 | } |
| 187 | |
| 188 | #[test] |
| 189 | fn a_sealed_store_refuses_writes() { |
| 190 | let mut s = AnonStore::new(); |
| 191 | s.finish(); |
| 192 | assert!(s.push(b"x").is_err()); |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn a_slice_within_one_segment_borrows() { |
| 197 | let mut s = AnonStore::new(); |
| 198 | s.push(b"abcdef").expect("push"); |
| 199 | s.finish(); |
| 200 | assert_eq!(s.slice_at(1, 3).expect("slice"), b"bcd"); |
| 201 | } |
| 202 | } |