memopro 0.2.0

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
//! Pager tests (Linux, macOS): data larger than the budget comes back bit for bit through plain loads
//! and stores, from one thread or several, and incompressible data is kept (and counted).

use super::*;
use crate::error::Error;

const MIB: usize = 1 << 20;

/// A pager with 256 KiB chunks, or `None` where userfaultfd is not permitted (said on stderr).
fn pager(budget_mib: u64) -> Option<Pager> {
    let config = PagerConfig {
        chunk: 256 * 1024,
        ..PagerConfig::new(budget_mib << 20)
    };
    match Pager::new(config) {
        Ok(p) => Some(p),
        Err(Error::Unsupported(why)) => {
            eprintln!("skipping the pager test: {why}");
            None
        }
        Err(e) => panic!("{e}"),
    }
}

fn pattern(i: usize) -> u32 {
    ((i / 7) % 1000) as u32 // compresses well, like widened bf16 or small integers
}

#[test]
fn memory_larger_than_the_budget_reads_back_exact() {
    let Some(p) = pager(8) else { return };
    let len = 32 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region of `len` bytes, used only here.
    let words = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
    assert!(words.iter().step_by(4099).all(|&w| w == 0), "starts zeroed");
    for (i, w) in words.iter_mut().enumerate() {
        *w = pattern(i);
    }
    let expect: u64 = (0..len / 4).map(|i| u64::from(pattern(i))).sum();
    for _ in 0..3 {
        let sum: u64 = words.iter().map(|&w| u64::from(w)).sum();
        assert_eq!(sum, expect);
    }
    let s = p.stats();
    assert!(s.evictions > 0 && s.restores > 0, "{s:?}");
    assert_eq!(s.overruns, 0, "{s:?}");
    assert!(s.peak_used <= s.limit, "{s:?}");
    // SAFETY: the region is no longer used.
    assert_eq!(unsafe { p.unmap(ptr) }.unwrap(), len);
    assert_eq!(p.stats().used, 0);
}

#[test]
fn threads_write_and_read_while_chunks_come_and_go() {
    let Some(p) = pager(8) else { return };
    let len = 24 * MIB;
    let ptr = p.map(len).unwrap() as usize;
    let quarter = len / 4 / 4; // words per thread
    std::thread::scope(|s| {
        for t in 0..4 {
            s.spawn(move || {
                // SAFETY: each thread writes its own quarter of the region.
                let words = unsafe {
                    std::slice::from_raw_parts_mut((ptr as *mut u32).add(t * quarter), quarter)
                };
                for round in 0..2u32 {
                    for (i, w) in words.iter_mut().enumerate() {
                        *w = pattern(t * quarter + i) + round;
                    }
                }
            });
        }
    });
    // SAFETY: the region, all threads done.
    let words = unsafe { std::slice::from_raw_parts(ptr as *const u32, len / 4) };
    for (i, &w) in words.iter().enumerate() {
        assert_eq!(w, pattern(i) + 1, "word {i}");
    }
    assert!(p.stats().evictions > 0);
    // SAFETY: done with it.
    unsafe { p.unmap(ptr as *mut u8) }.unwrap();
}

#[test]
fn incompressible_chunks_stay_and_are_counted() {
    let Some(p) = pager(4) else { return };
    let len = 8 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region.
    let bytes = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
    let mut x = 0x9E37_79B9_7F4A_7C15u64;
    for b in bytes.iter_mut() {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        *b = x as u8;
    }
    let mut y = 0x9E37_79B9_7F4A_7C15u64;
    for &b in bytes.iter() {
        y ^= y << 13;
        y ^= y >> 7;
        y ^= y << 17;
        assert_eq!(b, y as u8);
    }
    let s = p.stats();
    assert!(s.incompressible > 0 && s.overruns > 0, "{s:?}");
    // SAFETY: done with it.
    unsafe { p.unmap(ptr) }.unwrap();
}

#[test]
fn a_repeated_scan_keeps_a_budget_worth() {
    let Some(p) = pager(8) else { return };
    let len = 32 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region.
    let words = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
    for (i, w) in words.iter_mut().enumerate() {
        *w = pattern(i);
    }
    let mut restores = Vec::new();
    for _ in 0..3 {
        let before = p.stats().restores;
        std::hint::black_box(words.iter().map(|&w| u64::from(w)).sum::<u64>());
        restores.push(p.stats().restores - before);
    }
    let chunks = (len / (256 * 1024)) as u64;
    let fits = p.limit() / (256 * 1024) as u64;
    // LRU would bring every chunk back each pass; the reuse-distance choice keeps most of what fits
    assert!(
        restores[2] <= chunks - fits / 2,
        "{restores:?} of {chunks} chunks, room for {fits}"
    );
    // SAFETY: done with it.
    unsafe { p.unmap(ptr) }.unwrap();
}

#[test]
fn two_arrays_used_in_step_do_not_ping_pong() {
    // `dst[i] = src[i] + 1` over two regions larger than the budget: evicting the chunk just
    // faulted in (the other operand) made every few elements fault (CI took hours, 0128)
    let Some(p) = pager(8) else { return };
    let len = 16 * MIB;
    let (src, dst) = (p.map(len).unwrap(), p.map(len).unwrap());
    // SAFETY: two fresh regions of `len` bytes, used only here.
    let (a, b) = unsafe {
        (
            std::slice::from_raw_parts_mut(src as *mut u32, len / 4),
            std::slice::from_raw_parts_mut(dst as *mut u32, len / 4),
        )
    };
    for (i, w) in a.iter_mut().enumerate() {
        *w = pattern(i);
    }
    let before = p.stats().faults;
    for (x, y) in b.iter_mut().zip(a.iter()) {
        *x = *y + 1;
    }
    let faults = p.stats().faults - before;
    let chunks = (2 * len / (256 * 1024)) as u64;
    assert!(faults <= 4 * chunks, "{faults} faults for {chunks} chunks");
    assert!(
        b.iter()
            .enumerate()
            .step_by(1009)
            .all(|(i, &w)| w == pattern(i) + 1)
    );
    // SAFETY: done with both.
    unsafe {
        p.unmap(src).unwrap();
        p.unmap(dst).unwrap();
    }
}

/// The process footprint, or `None` (said on stderr) where it cannot be measured.
fn footprint() -> Option<u64> {
    let f = crate::rt::process_footprint();
    if f.is_none() {
        eprintln!("skipping: no process footprint here");
    }
    f
}

#[test]
#[ignore = "measures the whole process: run with --ignored --test-threads=1"]
fn evicted_chunks_leave_the_process() {
    // tests run in parallel threads of one process: allow other tests' memory as slack
    let Some(p) = pager(8) else { return };
    let Some(start) = footprint() else { return };
    let len = 96 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region.
    let words = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
    for (i, w) in words.iter_mut().enumerate() {
        *w = pattern(i);
    }
    let grown = footprint().unwrap().saturating_sub(start);
    assert!(
        grown < 48 * MIB as u64,
        "footprint grew {grown} for 96 MiB under 8 MiB"
    );
    assert!(
        words
            .iter()
            .enumerate()
            .step_by(997)
            .all(|(i, &w)| w == pattern(i))
    );
    // SAFETY: done with it.
    unsafe { p.unmap(ptr) }.unwrap();
}

#[test]
#[ignore = "measures the whole process: run with --ignored --test-threads=1"]
fn a_process_budget_counts_memory_outside_the_pager() {
    let Some(now) = footprint() else { return };
    let config = PagerConfig {
        chunk: 256 * 1024,
        process_budget: Some(now + 24 * MIB as u64),
        ..PagerConfig::new(64 << 20)
    };
    let p = match Pager::new(config) {
        Ok(p) => p,
        Err(Error::Unsupported(why)) => return eprintln!("skipping: {why}"),
        Err(e) => panic!("{e}"),
    };
    let outside = vec![7u8; 16 * MIB]; // memory the pager does not own, touched
    let len = 32 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region.
    let words = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
    for (i, w) in words.iter_mut().enumerate() {
        *w = pattern(i);
    }
    assert!(
        words
            .iter()
            .enumerate()
            .step_by(991)
            .all(|(i, &w)| w == pattern(i))
    );
    let s = p.stats();
    // a 64 MiB budget alone would have kept all 32 MiB; the process budget left far less
    assert!(s.evictions > 0, "{s:?}");
    assert!(s.limit_low < 24 * MIB as u64, "{s:?}");
    assert!(s.outside_peak >= 16 * MIB as u64, "{s:?}");
    std::hint::black_box(&outside);
    // SAFETY: done with it.
    unsafe { p.unmap(ptr) }.unwrap();
}

#[test]
#[ignore = "measures the whole process: run with --ignored --test-threads=1"]
fn a_process_budget_lost_to_memory_outside_keeps_the_chunks_room() {
    // 0284: once memory outside the pager alone passes the process budget, squeezing the
    // chunks to the floor cannot keep the budget, it only refaults; the chunks keep the room
    // they last had, so data that fit before is read again without restores
    let Some(now) = footprint() else { return };
    let config = PagerConfig {
        chunk: 256 * 1024,
        process_budget: Some(now + 40 * MIB as u64),
        ..PagerConfig::new(64 << 20)
    };
    let p = match Pager::new(config) {
        Ok(p) => p,
        Err(Error::Unsupported(why)) => return eprintln!("skipping: {why}"),
        Err(e) => panic!("{e}"),
    };
    let len = 16 * MIB;
    let ptr = p.map(len).unwrap();
    // SAFETY: a fresh region.
    let words = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
    for (i, w) in words.iter_mut().enumerate() {
        *w = pattern(i);
    }
    // fresh pages straight from the OS (malloc would reuse memory earlier tests freed, and the
    // footprint would not grow): now the process is over its budget without the pager
    let outside_len = 64 * MIB;
    // SAFETY: an anonymous private mapping, unmapped below.
    let outside = unsafe {
        libc::mmap(
            std::ptr::null_mut(),
            outside_len,
            libc::PROT_READ | libc::PROT_WRITE,
            libc::MAP_PRIVATE | libc::MAP_ANON,
            -1,
            0,
        )
    };
    assert_ne!(outside, libc::MAP_FAILED);
    // SAFETY: the mapping is `outside_len` writable bytes.
    unsafe { std::ptr::write_bytes(outside as *mut u8, 7, outside_len) };
    std::thread::sleep(std::time::Duration::from_millis(100)); // trims run every 10 ms
    let before = p.stats().restores;
    for _ in 0..3 {
        assert!(words.iter().enumerate().all(|(i, &w)| w == pattern(i)));
    }
    let s = p.stats();
    assert!(s.holds > 0, "{s:?}");
    assert!(
        s.restores - before < (len / (256 * 1024)) as u64,
        "refaulted although the budget was lost anyway: {s:?}"
    );
    // SAFETY: done with both.
    unsafe {
        libc::munmap(outside, outside_len);
        p.unmap(ptr).unwrap();
    }
}

#[test]
fn several_pagers_serve_their_own_faults() {
    let (Some(a), Some(b)) = (pager(4), pager(4)) else {
        return;
    };
    let len = 12 * MIB;
    let (pa, pb) = (a.map(len).unwrap() as usize, b.map(len).unwrap() as usize);
    std::thread::scope(|s| {
        for (ptr, add) in [(pa, 1u32), (pb, 2u32)] {
            s.spawn(move || {
                // SAFETY: each thread uses its own region.
                let w = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u32, len / 4) };
                for (i, x) in w.iter_mut().enumerate() {
                    *x = pattern(i) + add;
                }
                for _ in 0..2 {
                    assert!(w.iter().enumerate().all(|(i, &x)| x == pattern(i) + add));
                }
            });
        }
    });
    assert!(a.stats().restores > 0 && b.stats().restores > 0);
    // SAFETY: done with both.
    unsafe {
        a.unmap(pa as *mut u8).unwrap();
        b.unmap(pb as *mut u8).unwrap();
    }
}

#[test]
fn a_process_budget_with_no_room_left_still_makes_progress() {
    // the process already holds more than its budget: the pager keeps a few chunks anyway
    // (counted as overruns), or uses the room the machine still has since the budget is lost
    // (0306, counted as holds), instead of letting a copy's two operands evict each other forever
    let config = PagerConfig {
        chunk: 256 * 1024,
        process_budget: Some(1),
        ..PagerConfig::new(64 << 20)
    };
    let p = match Pager::new(config) {
        Ok(p) => p,
        Err(Error::Unsupported(why)) => return eprintln!("skipping: {why}"),
        Err(e) => panic!("{e}"),
    };
    let len = 8 * MIB;
    let (src, dst) = (p.map(len).unwrap(), p.map(len).unwrap());
    // SAFETY: two fresh regions, used only here.
    let (a, b) = unsafe {
        (
            std::slice::from_raw_parts_mut(src as *mut u32, len / 4),
            std::slice::from_raw_parts_mut(dst as *mut u32, len / 4),
        )
    };
    for (i, w) in a.iter_mut().enumerate() {
        *w = pattern(i);
    }
    b.copy_from_slice(a);
    assert!(
        b.iter()
            .enumerate()
            .step_by(331)
            .all(|(i, &w)| w == pattern(i))
    );
    let s = p.stats();
    assert!(s.overruns > 0 || s.holds > 0, "{s:?}");
    // SAFETY: done with both.
    unsafe {
        p.unmap(src).unwrap();
        p.unmap(dst).unwrap();
    }
}

#[test]
fn compressed_copies_filling_the_budget_do_not_stop_a_copy() {
    // data that compresses to more than the budget: the compressed copies alone fill it, and
    // a copy between two regions still finishes (over budget, counted) instead of ping-ponging
    let Some(p) = pager(2) else { return };
    let len = 16 * MIB;
    let (src, dst) = (p.map(len).unwrap(), p.map(len).unwrap());
    // SAFETY: two fresh regions, used only here.
    let (a, b) = unsafe {
        (
            std::slice::from_raw_parts_mut(src as *mut u32, len / 4),
            std::slice::from_raw_parts_mut(dst as *mut u32, len / 4),
        )
    };
    let mut x = 0x2545_F491_4F6C_DD1Du64;
    for w in a.iter_mut() {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        *w = (x as u32) & 0xFFFF_0000; // like bf16 widened to f32: about half compresses away
    }
    let expect: u64 = a.iter().map(|&w| u64::from(w)).sum();
    b.copy_from_slice(a);
    assert_eq!(b.iter().map(|&w| u64::from(w)).sum::<u64>(), expect);
    assert!(p.stats().overruns > 0);
    // SAFETY: done with both.
    unsafe {
        p.unmap(src).unwrap();
        p.unmap(dst).unwrap();
    }
}