memopro 0.1.2

Budgeted memory runtime: keep, losslessly compress, re-read from verified source files or recompute large buffers so work runs within a guaranteed memory ceiling (alpha).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Spill engine (0027 RS1–RS5, 0032 H1–H4, P5, 0038): move tensor bytes between memory and files.
//!
//! Main path (H1): re-read an unchanged tensor from its original file (e.g. safetensors) straight
//! into the destination buffer and verify it with a digest; no SSD write. Last resort: write a
//! spill file, only when the caller's policy allows it (the policy itself lives in Python).
//!
//! - RS1: each call does the whole transfer; no intermediate copies (reads land in `dst`, writes
//!   come from `src`).
//! - RS2: buffers are borrowed (the Python bindings take the buffer protocol, never `bytes`).
//! - RS3: reads and digests run on one process-wide read pool of [`readers`] threads; writes on
//!   one process-wide, low-I/O-priority pool (H4).
//! - RS4: no transfer buffers at all, so extra memory does not grow with the transfer size.
//! - RS5: digests are computed chunk by chunk while other chunks are being read or written.
//! - P5: spill files are created `0600` with `create_new` and hold raw bytes only; metadata and
//!   the digest stay with the caller (never pickle).
//!
//! Digest: xxh3-128 of every [`DIGEST_CHUNK`], combined with the length (0038). It detects
//! corruption and changed files; it is not a cryptographic hash. The value does not depend on
//! the number of threads.

use crate::error::{Error, Result};
use rayon::prelude::*;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use xxhash_rust::xxh3::xxh3_128;

/// Chunk size for digests and parallel I/O.
pub const DIGEST_CHUNK: usize = 4 << 20;

/// 128-bit digest of a buffer (16 bytes, little-endian).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Digest(pub Vec<u8>);

/// A byte range in an existing file that holds the original data of a tensor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceRef {
    pub path: PathBuf,
    pub offset: u64,
    pub len: u64,
}

/// A spill file written by the engine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpillFile {
    pub path: PathBuf,
    pub len: u64,
    pub digest: Digest,
}

fn combine(len: usize, parts: &[u128]) -> Digest {
    let mut buf = Vec::with_capacity(8 + 16 * parts.len());
    buf.extend_from_slice(&(len as u64).to_le_bytes());
    for p in parts {
        buf.extend_from_slice(&p.to_le_bytes());
    }
    Digest(xxh3_128(&buf).to_le_bytes().to_vec())
}

/// Digest of `data`, computed in parallel.
pub fn digest(data: &[u8]) -> Digest {
    combine(data.len(), &digest_parts(data))
}

/// Per-[`DIGEST_CHUNK`] hashes of `data`. Hashing consecutive pieces whose lengths are multiples
/// of `DIGEST_CHUNK` and combining all parts with [`digest_combine`] gives [`digest`] of the whole,
/// so callers can verify large data piece by piece with bounded buffers (0061 F1).
pub fn digest_parts(data: &[u8]) -> Vec<u128> {
    data.par_chunks(DIGEST_CHUNK).map(xxh3_128).collect()
}

/// The digest of data of length `len` whose chunk hashes are `parts` (see [`digest_parts`]).
pub fn digest_combine(len: usize, parts: &[u128]) -> Digest {
    combine(len, parts)
}

#[cfg(target_os = "macos")]
fn lower_io_priority() {
    unsafe extern "C" {
        fn setiopolicy_np(
            iotype: libc::c_int,
            scope: libc::c_int,
            policy: libc::c_int,
        ) -> libc::c_int;
    }
    const IOPOL_TYPE_DISK: libc::c_int = 0;
    const IOPOL_SCOPE_THREAD: libc::c_int = 1;
    const IOPOL_UTILITY: libc::c_int = 4;
    // SAFETY: plain syscall wrapper with constant arguments; failure only keeps the default.
    unsafe {
        setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD, IOPOL_UTILITY);
    }
}

#[cfg(target_os = "linux")]
fn lower_io_priority() {
    const IOPRIO_WHO_PROCESS: libc::c_long = 1; // with id 0: the calling thread
    const IOPRIO_CLASS_BE: libc::c_long = 2;
    const LOWEST_BE_LEVEL: libc::c_long = 7;
    // SAFETY: ioprio_set with constant arguments; failure only keeps the default priority.
    unsafe {
        libc::syscall(
            libc::SYS_ioprio_set,
            IOPRIO_WHO_PROCESS,
            0,
            (IOPRIO_CLASS_BE << 13) | LOWEST_BE_LEVEL,
        );
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn lower_io_priority() {}

/// Reads in flight at once: `MEMOPRO_READ_THREADS` when set (a calibration knob for other
/// devices), else 4: more did not read faster on an M1 (E050, 0247) and each reader keeps one
/// [`DIGEST_CHUNK`]-sized scratch buffer for unaligned reads.
pub fn readers() -> usize {
    std::env::var("MEMOPRO_READ_THREADS")
        .ok()
        .and_then(|v| v.parse().ok())
        .filter(|&n| n > 0)
        .unwrap_or(4)
}

/// Process-wide pool for reads (RS3).
fn read_pool() -> Option<&'static rayon::ThreadPool> {
    static POOL: OnceLock<Option<rayon::ThreadPool>> = OnceLock::new();
    POOL.get_or_init(|| {
        rayon::ThreadPoolBuilder::new()
            .num_threads(readers())
            .thread_name(|i| format!("memopro-read-{i}"))
            .build()
            .ok()
    })
    .as_ref()
}

/// Process-wide pool for spill writes, with lowered I/O priority (H4, RS3).
fn write_pool() -> Option<&'static rayon::ThreadPool> {
    static POOL: OnceLock<Option<rayon::ThreadPool>> = OnceLock::new();
    POOL.get_or_init(|| {
        rayon::ThreadPoolBuilder::new()
            .num_threads(std::thread::available_parallelism().map_or(2, |n| n.get().min(4)))
            .thread_name(|i| format!("memopro-spill-{i}"))
            .start_handler(|_| lower_io_priority())
            .build()
            .ok()
    })
    .as_ref()
}

#[cfg(unix)]
fn read_at(file: &File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
    use std::os::unix::fs::FileExt;
    file.read_exact_at(buf, offset)
}

#[cfg(windows)]
fn read_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {
    use std::os::windows::fs::FileExt;
    while !buf.is_empty() {
        match file.seek_read(buf, offset)? {
            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
            n => {
                buf = &mut buf[n..];
                offset += n as u64;
            }
        }
    }
    Ok(())
}

/// File offsets of uncached reads are aligned to this. macOS reads an `F_NOCACHE` file at an
/// unaligned offset through its cache: slower (1.4 vs 2.0 GiB/s) and the pages stay cached
/// (E050 follow-up, 0248). Safetensors data starts at any byte (0115).
const ALIGN: u64 = 16 << 10;

std::thread_local! {
    static SCRATCH: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// Fill `dst` from `offset`: directly when the offset is aligned, else through an aligned
/// per-thread scratch buffer covering the aligned pages around it (same bytes, one copy).
fn read_aligned(file: &File, file_len: u64, dst: &mut [u8], offset: u64) -> std::io::Result<()> {
    let skew = offset % ALIGN;
    if skew == 0 {
        return read_at(file, dst, offset);
    }
    let start = offset - skew;
    let end = (offset + dst.len() as u64)
        .next_multiple_of(ALIGN)
        .min(file_len);
    let len = (end - start) as usize;
    SCRATCH.with(|s| {
        let mut s = s.borrow_mut();
        if s.len() < len + ALIGN as usize {
            *s = vec![0; len + ALIGN as usize];
        }
        let at = s.as_ptr().align_offset(ALIGN as usize);
        let buf = &mut s[at..at + len];
        read_at(file, buf, start)?;
        let from = skew as usize;
        dst.copy_from_slice(&buf[from..from + dst.len()]);
        Ok(())
    })
}

/// Create a new spill file readable only by this user. Unix: mode 0600. Windows: the file
/// inherits the per-user cache folder's ACL (only the user and administrators).
#[cfg(unix)]
fn create_private(path: &Path) -> std::io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
}

#[cfg(windows)]
fn create_private(path: &Path) -> std::io::Result<File> {
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
}

#[cfg(unix)]
fn write_at(file: &File, buf: &[u8], offset: u64) -> std::io::Result<()> {
    use std::os::unix::fs::FileExt;
    file.write_all_at(buf, offset)
}

#[cfg(windows)]
fn write_at(file: &File, mut buf: &[u8], mut offset: u64) -> std::io::Result<()> {
    use std::os::windows::fs::FileExt;
    while !buf.is_empty() {
        match file.seek_write(buf, offset)? {
            0 => return Err(std::io::ErrorKind::WriteZero.into()),
            n => {
                buf = &buf[n..];
                offset += n as u64;
            }
        }
    }
    Ok(())
}

pub(crate) fn read_region(
    file: &File,
    offset: u64,
    dst: &mut [u8],
    expected: Option<&Digest>,
) -> Result<Digest> {
    let len = dst.len();
    let file_len = file.metadata()?.len();
    let mut job = move || -> std::io::Result<Vec<u128>> {
        dst.par_chunks_mut(DIGEST_CHUNK)
            .enumerate()
            .map(|(i, chunk)| {
                read_aligned(file, file_len, chunk, offset + (i * DIGEST_CHUNK) as u64)?;
                Ok(xxh3_128(chunk))
            })
            .collect()
    };
    let parts = match read_pool() {
        Some(pool) => pool.install(job),
        None => job(),
    };
    let got = combine(len, &parts?);
    match expected {
        Some(want) if *want != got => Err(Error::Integrity(
            "data read back does not match its digest".into(),
        )),
        _ => Ok(got),
    }
}

static COUNTER: AtomicU64 = AtomicU64::new(0);

/// The spill engine. Stateless apart from the process-wide pools.
#[derive(Debug, Default, Clone, Copy)]
pub struct Engine;

impl Engine {
    pub fn new() -> Self {
        Engine
    }

    /// Digest `data` in parallel.
    pub fn digest(&self, data: &[u8]) -> Digest {
        digest(data)
    }

    /// Fill `dst` from an original file region (write-free restore, H1) and return its digest.
    /// With `expected`, fail with [`Error::Integrity`] if the data differs.
    pub fn read_source_into(
        &self,
        source: &SourceRef,
        dst: &mut [u8],
        expected: Option<&Digest>,
    ) -> Result<Digest> {
        if dst.len() as u64 != source.len {
            return Err(Error::InvalidArgument(format!(
                "destination holds {} bytes, source region {}",
                dst.len(),
                source.len
            )));
        }
        let file = File::open(&source.path)?;
        let size = file.metadata()?.len();
        if source.offset.saturating_add(source.len) > size {
            return Err(Error::Integrity(format!(
                "{} is {size} bytes, shorter than the recorded region",
                source.path.display()
            )));
        }
        read_region(&file, source.offset, dst, expected)
    }

    /// Write `src` to a new spill file in `dir` (last resort; the caller checked the policy).
    pub fn write(&self, src: &[u8], dir: &Path) -> Result<SpillFile> {
        let name = format!(
            "{}-{}-{}.mpspill",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos()),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        let path = dir.join(name);
        let file = create_private(&path)?;
        let job = || -> std::io::Result<Vec<u128>> {
            file.set_len(src.len() as u64)?;
            src.par_chunks(DIGEST_CHUNK)
                .enumerate()
                .map(|(i, chunk)| {
                    write_at(&file, chunk, (i * DIGEST_CHUNK) as u64)?;
                    Ok(xxh3_128(chunk))
                })
                .collect()
        };
        let parts = match write_pool() {
            Some(pool) => pool.install(job),
            None => job(),
        };
        match parts {
            Ok(parts) => Ok(SpillFile {
                path,
                len: src.len() as u64,
                digest: combine(src.len(), &parts),
            }),
            Err(e) => {
                drop(file);
                let _ = std::fs::remove_file(&path);
                Err(e.into())
            }
        }
    }

    /// Restore a spill file into `dst`, verifying its digest.
    pub fn read_into(&self, file: &SpillFile, dst: &mut [u8]) -> Result<()> {
        let source = SourceRef {
            path: file.path.clone(),
            offset: 0,
            len: file.len,
        };
        self.read_source_into(&source, dst, Some(&file.digest))
            .map(|_| ())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn data(n: usize) -> Vec<u8> {
        (0..n).map(|i| (i * 31 + i / 7) as u8).collect()
    }

    fn tmpdir(tag: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("memopro-{tag}-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn digest_is_deterministic_and_sensitive() {
        let a = data(DIGEST_CHUNK * 2 + 5);
        let d1 = digest(&a);
        let d2 = rayon::ThreadPoolBuilder::new()
            .num_threads(1)
            .build()
            .unwrap()
            .install(|| digest(&a));
        assert_eq!(d1, d2, "independent of thread count");
        assert_eq!(d1.0.len(), 16);
        let mut b = a.clone();
        b[DIGEST_CHUNK + 3] ^= 1;
        assert_ne!(d1, digest(&b));
        assert_ne!(digest(&a[..10]), digest(&a[..11]));
    }

    #[test]
    fn digest_parts_of_pieces_combine_to_the_whole() {
        let a = data(DIGEST_CHUNK * 5 + 77);
        let mut parts = digest_parts(&a[..DIGEST_CHUNK * 2]);
        parts.extend(digest_parts(&a[DIGEST_CHUNK * 2..DIGEST_CHUNK * 4]));
        parts.extend(digest_parts(&a[DIGEST_CHUNK * 4..]));
        assert_eq!(digest_combine(a.len(), &parts), digest(&a));
    }

    #[test]
    fn spill_roundtrip_is_bit_exact_and_private() {
        let dir = tmpdir("spill");
        let src = data(DIGEST_CHUNK * 2 + 123);
        let engine = Engine::new();
        let file = engine.write(&src, &dir).unwrap();
        assert_eq!(file.len, src.len() as u64);
        assert_eq!(file.digest, digest(&src));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&file.path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        let mut out = vec![0u8; src.len()];
        engine.read_into(&file, &mut out).unwrap();
        assert_eq!(out, src);
        std::fs::remove_file(&file.path).unwrap();
    }

    #[test]
    fn corrupted_or_changed_files_are_detected() {
        let dir = tmpdir("corrupt");
        let src = data(100_000);
        let engine = Engine::new();
        let file = engine.write(&src, &dir).unwrap();
        let mut bytes = std::fs::read(&file.path).unwrap();
        bytes[5000] ^= 0xff;
        std::fs::write(&file.path, &bytes).unwrap();
        let mut out = vec![0u8; src.len()];
        assert!(matches!(
            engine.read_into(&file, &mut out),
            Err(Error::Integrity(_))
        ));
        std::fs::write(&file.path, &bytes[..1000]).unwrap(); // truncated
        assert!(matches!(
            engine.read_into(&file, &mut out),
            Err(Error::Integrity(_))
        ));
        std::fs::remove_file(&file.path).unwrap();
    }

    #[test]
    fn source_region_read_lands_in_destination() {
        let dir = tmpdir("source");
        let path = dir.join("weights.bin");
        let blob = data(DIGEST_CHUNK + 4096);
        std::fs::write(&path, &blob).unwrap();
        let region = SourceRef {
            path: path.clone(),
            offset: 100,
            len: (DIGEST_CHUNK + 1000) as u64,
        };
        let mut dst = vec![0u8; region.len as usize];
        let d = Engine::new()
            .read_source_into(&region, &mut dst, None)
            .unwrap();
        assert_eq!(&dst[..], &blob[100..100 + region.len as usize]);
        assert_eq!(d, digest(&dst));
        let mut short = vec![0u8; 10];
        assert!(matches!(
            Engine::new().read_source_into(&region, &mut short, None),
            Err(Error::InvalidArgument(_))
        ));
        std::fs::remove_file(&path).unwrap();
    }
}