A/B zswap vs zram: zram stays the default

Add setup_zswap.sh and make setup_zram.sh its one-command revert
(shared lib/swap_switch.sh: systemd-boot/GRUB cmdline, live switch or
exit 3 "reboot to apply"). Add swap_bench.sh + python_pkg/swap_bench, a
seeded memory-pressure benchmark. 3 runs x 2 setups in vmbox and on the
host: zram has lower median PSI full in both (VM 5996 vs 10360 ms, host
7427 vs 8973 ms), so the host keeps booting with zram. Results in
linux_configuration/fixes/DOCS-zswap-vs-zram.md.

Bug-class-check: none — new feature and measurement, not a bug fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-27 12:33:11 +01:00
parent a36ff74e30
commit 5e0d8727d6
30 changed files with 2107 additions and 47 deletions

View File

@ -0,0 +1,17 @@
{
"title": "zswap vs zram A/B test with one-command switching",
"objective": "Measure zswap against the 32 GiB zram setup with a seeded benchmark in vmbox and on the host, keep the winner as the boot default, and make each setup script the one-command switch to its setup.",
"acceptance_criteria": [
"setup_zswap.sh switches live (no zram0; zswap Y/zstd/35) and the cmdline carries the zswap tokens after a reboot",
"Hibernate/resume works in vmbox with zswap on",
"setup_zram.sh reverts in one command; a second run of either script changes nothing",
"setup_zswap.sh exits 3 'reboot to apply' when zram cannot drain, and the next boot is on zswap",
"swap_bench.sh run is under 60 s, appends one row, and the same seed gives the same workload; summary names the winner by the agreed rule",
"DOCS-zswap-vs-zram.md holds VM and host tables (3 runs x 2 setups) and the raw rows; the host boots the winner"
],
"out_of_scope": [
"Hibernation config and swapfile priorities",
"fix_ubuntu_performance.sh"
],
"verifier": "test_swap_switch.sh 45/45, test_swap_bench.sh 27/27, pytest python_pkg/swap_bench 28 passed at 100% branch, vmbox_swap.sh phases all OK, vm wake hibernate resumed with zswap on, host and VM summaries both pick zram, host verified on zram with zswap.enabled=0."
}

View File

@ -0,0 +1,65 @@
{
"intent": "A/B test zswap against the 32 GiB zram setup with a seeded memory-pressure benchmark, in vmbox and on the host; keep the winner (zram) as the host default, with each setup script the one-command switch to its setup.",
"scope": [
"linux_configuration/fixes: setup_zswap.sh (new), setup_zram.sh (now also the revert), swap_bench.sh (new), lib/swap_switch.sh (new), DOCS-zswap-vs-zram.md + swap-bench-results.tsv (results)",
"python_pkg/swap_bench: seeded workload, row parsing, medians + winner rule",
"Swap-setup-aware wording in lib/arch_sysctl.sh, lib/arch_perf_probes.sh, optimize_arch_desktop.sh; swappiness stays 100",
"Non-goal: hibernation config (resume= stays on /swapfile), swapfile priorities"
],
"changes": [
"setup_zswap.sh persists zswap.enabled=1 zstd max_pool_percent=35 shrinker on every systemd-boot entry (or GRUB + grub-mkconfig), removes the zram-generator conf, switches live (swapoff zram0 first, zswap on after) or exits 3 'reboot to apply' when MemAvailable cannot absorb zram",
"setup_zram.sh restores zswap.enabled=0, reinstalls the conf (ZRAM_SIZE_MIB scales it for a small guest), starts zram0, then turns zswap off live",
"swap_bench.sh run host|vm: one seeded run per call in a MemoryMax=4G/MemorySwapMax=infinity scope (host) or system-wide (vm); records ratio, PSI some/full, major faults, disk writeback (pswpout minus zram writes), zswpwb, desktop session PSI; refuses a host run when MemAvailable < cap + 2G; summary applies the PSI-full / major-fault / 10 % rule",
"check_memory_pressure advice names the installed swap setup (zram, zswap or plain disk)"
],
"verification": [
{
"command": "linux_configuration/fixes/lib/tests/test_swap_switch.sh",
"result": "pass",
"evidence": "45 passed, 0 failed: live switch both ways, three loader entries, GRUB, exit 3, idempotent reruns byte-identical, grub-mkconfig failure loud"
},
{
"command": "linux_configuration/fixes/lib/tests/test_swap_bench.sh",
"result": "pass",
"evidence": "27 passed: scope properties, same seed same CRCs, refusals record no row, low-RAM guard, summary"
},
{
"command": "python3 -m pytest python_pkg/swap_bench --cov=python_pkg.swap_bench --cov-branch",
"result": "pass",
"evidence": "28 passed, 100% branch coverage"
},
{
"command": "lib/tests/test_arch_perf_probes_health.sh; arch_sysctl_quarantined_cases.sh",
"result": "pass",
"evidence": "34 passed; 23 passed"
},
{
"command": "vm run zsw 'sudo bash lib/tests/vmbox_swap.sh zram|booted-zram|again|zswap|booted-zswap|fill|exit3'",
"result": "pass",
"evidence": "every phase OK: live switch both ways, persistence after reboot, reruns unchanged, exit 3 then next boot on zswap"
},
{
"command": "vm wake zswh -- 'rtcwake -m no -s 60 && systemctl hibernate' (guest booted on the zswap cmdline, 3 GB in the pool)",
"result": "pass",
"evidence": "verdict hibernate, same boot_id after resume, zswap enabled=Y max_pool_percent=35"
},
{
"command": "swap_bench.sh run vm x6, run host x6; swap_bench.sh summary",
"result": "pass",
"evidence": "vm PSI full 5996 zram vs 10360 zswap; host 7427 vs 8973; winner zram on both; identical CRCs across all 12 runs"
},
{
"command": "sudo setup_zswap.sh then sudo setup_zram.sh on the host",
"result": "pass",
"evidence": "live both ways without reboot; /proc/cmdline zswap.enabled=0, zram0 prio 100, enabled=N, loader entries byte-identical to /var/lib/swap-switch/*.orig"
}
],
"risks": [
"Host benchmark numbers are noisy (other board jobs ran concurrently); the VM run, pressed system-wide, agrees with them",
"The vmbox guest that ran the benchmarks cold-booted on hibernate under both setups; a fresh guest resumed, cause not found"
],
"rollback": [
"sudo linux_configuration/fixes/setup_zram.sh restores the zram setup and zswap.enabled=0 on every loader entry; originals stay in /var/lib/swap-switch/*.orig",
"After rollback check: cat /proc/cmdline; swapon --show; cat /sys/module/zswap/parameters/enabled"
]
}

View File

@ -0,0 +1,173 @@
# zswap vs zram: A/B test
**Result: zram stays.** It won in the VM and on the host by the agreed
rule, and the host still boots with it.
The curiousbits author moved from zram to zswap (citing Chris Down and Hayden
James). This PC ran `setup_zram.sh`: a 32 GiB zstd zram device at priority
100 above two disk swapfiles at -1, swappiness 100, zswap off. With that
order a cold page never leaves zram for disk. This file records a seeded
benchmark of both setups, in a vmbox guest and on the host, and which one
the host now boots with.
## Setups
| | zram (`setup_zram.sh`) | zswap (`setup_zswap.sh`) |
| -------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| kernel cmdline | `zswap.enabled=0` | `zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=35 zswap.shrinker_enabled=1` |
| compressed RAM | `/dev/zram0`, 32 GiB uncompressed, zstd, prio 100 | zswap pool, at most 35 % of RAM, zstd, zsmalloc (the only pool on kernel 7.3, so there is no `zswap.zpool=`) |
| disk swap | `/swapfile` 40G + `/swapfile2` 24G at -1, overflow only | same files, the backing store zswap writes cold pages to |
| cold pages | stay in zram until it fills | the shrinker writes them back to disk |
| swappiness | 100 | 100 |
| hibernation | `resume=` on `/swapfile`, unchanged | unchanged |
The 35 % cap gives both setups the same RAM budget: 32 GiB at the measured
~3.2:1 is ~10 GiB, about 35 % of the host's 30 GiB. The vmbox guest scales
its zram device the same way (`ZRAM_SIZE_MIB` = 35 % of RAM × 3.2, 4.3 GiB
on a 3.9 GiB guest).
Each script is the one-command switch to its setup, and the revert from the
other:
```bash
sudo linux_configuration/fixes/setup_zswap.sh # exit 3 = reboot to apply
sudo linux_configuration/fixes/setup_zram.sh
```
`setup_zswap.sh` writes the cmdline first (every systemd-boot entry, or
GRUB's defaults plus `grub-mkconfig`), removes the zram-generator conf, then
switches live: swapoff zram0, then zswap on, so no page is compressed twice.
When MemAvailable cannot take back what zram holds plus 2 GiB, it leaves the
live state alone and exits 3: the next boot comes up on zswap.
`setup_zram.sh` restores `zswap.enabled=0`, reinstalls the conf, starts
zram0 and only then turns zswap off; pages still in the zswap pool drain as
they fault in. The original loader entries are kept in
`/var/lib/swap-switch/*.orig`.
## Method
`swap_bench.sh run host|vm` runs `python_pkg/swap_bench` once and appends
one row to `swap-bench-results.tsv`; `swap_bench.sh summary` prints the
medians and the winner. Every run stays under 60 s.
- **Workload.** A seeded anonymous mapping (seed 20261127): pages drawn from
a pool of Zipf-weighted text over a 64-word seeded vocabulary plus 5 %
random pages, about 3.2:1 under zstd. Then a seeded 25 % hot subset is
read three times, which is where the major faults come from. No file
contents and no clock go in, so the page count and both CRCs are the same
on every run, host or guest (C7).
- **Host.** 6 GiB under a transient `systemd-run --user --scope` with
`MemoryMax=4G`, `MemorySwapMax=infinity`, `RuntimeMaxSec=55`. Only the
scope is pressed; PSI, zswap counters and writeback come from the scope's
own `memory.pressure` and `memory.stat`. A host run refuses to start
when MemAvailable is below the 4 GiB cap plus 2 GiB, so the bench cannot
push the desktop into swap. (8 GiB took 37-45 s on zram with other jobs
running; zswap is slower, so 6 GiB keeps every run inside the 50 s limit.)
- **VM.** 4.5 GiB in a 3.9 GiB guest (8 GiB swapfile), no scope: the whole
guest is pressed and global counters are used.
- **Columns.** `ratio`: this run's stored-in over stored-out bytes (zram
`mm_stat` deltas at peak; zswap `zswapped/zswap` at peak). `psi_*_ms`:
memory stall time over the run. `majflt`: the workload's own major faults.
`disk_wb_pages`: pages written to disk swap, Δ`pswpout` minus Δ zram
writes (zram is a swap device, so `pswpout` counts it too). `zswpwb`:
zswap's writebacks. `desktop_full_ms` (host): full stall of the login
session scopes, i.e. the desktop, during the run.
- **Winner rule** (kuhy, 2026-11-27). Lower median PSI full wins; major
faults break a tie; a difference under 10 % (the run-to-run noise) is a
tie, and a tie on both keeps zram.
- **Known bias.** zswap's pool is charged to the cgroup that owns the pages;
zram's device memory is not. Under the host scope's 4 GiB cap, zswap's
pool eats into the scope's own RAM while zram's does not, so the host
numbers favour zram. The VM run, pressed system-wide, has no such bias.
## Results (2026-11-27, kernel 7.3.6)
Medians of 3 runs per setup, from `swap_bench.sh summary`:
### VM (vmbox, 3.9 GiB RAM, 4 vCPU, 8 GiB swapfile, 4.5 GiB workload)
| setup | runs | ratio | PSI some ms | PSI full ms | major faults | disk writeback pages | zswap writeback |
| ----- | ---- | ----- | ----------- | ----------- | ------------ | -------------------- | --------------- |
| zram | 3 | 3.21 | 5996 | 5996 | 124816 | 0 | 0 |
| zswap | 3 | 3.16 | 10366 | 10360 | 147757 | 92 | 92 |
Winner: **zram**. Median PSI full is 5996 ms for zram and 10360 ms for
zswap, 42 % lower. zram's three runs span 5782-6118 ms; zswap's span
8832-12826 ms.
### Host (30 GiB, 6 GiB workload in a 4 GiB scope)
| setup | runs | ratio | PSI some ms | PSI full ms | major faults | disk writeback pages | zswap writeback |
| ----- | ---- | ----- | ----------- | ----------- | ------------ | -------------------- | --------------- |
| zram | 3 | 2.83 | 7427 | 7427 | 172634 | 0 | 0 |
| zswap | 3 | 3.21 | 8973 | 8973 | 218408 | 617001 | 453067 |
Winner: **zram**. Median PSI full is 7427 ms for zram and 8973 ms for zswap,
17 % lower, which is past the 10 % noise bar. The host's spread is wide,
because other board jobs (gradle, an emulator, ollama) ran during the runs:
zram 5546-8223 ms, zswap 5490-11684 ms. Major faults point the same way
(-21 %). zswap wrote 1.3-2.3 GB of this run's pages back to disk per run
(`zswpwb` 331649-586700 pages), because its pool counts against the scope's
4 GiB. zram wrote nothing to disk. zram's ratio reads lower (2.8 vs 3.2)
only because `mm_stat` is device-wide, so other processes swapping during
the run dilute it. zswap's ratio comes from the scope's own counters.
The desktop was not pressed (C6). The login session scopes (i3 and
everything it started) stalled for 0-29 ms per run (`desktop_full_ms`),
against 8 ms over an idle 37 s measured the same way. Global PSI rises
during a run only because global PSI counts the bench scope's own stalls.
### Raw rows
```tsv
date env setup seed size_mib pages fill_crc touch_crc seconds ratio psi_some_ms psi_full_ms majflt disk_wb_pages zswpwb global_full_avg10 desktop_full_ms
2026-11-27T10:59:54Z vm zram 20261127 4608 1179648 531769134 2573270970 18.928 3.21 5996 5996 127223 0 0 34.56 na
2026-11-27T11:00:14Z vm zram 20261127 4608 1179648 531769134 2573270970 13.248 3.21 5782 5782 124816 0 0 39.31 na
2026-11-27T11:00:35Z vm zram 20261127 4608 1179648 531769134 2573270970 13.393 3.21 6118 6118 124559 0 0 43.00 na
2026-11-27T11:02:00Z vm zswap 20261127 4608 1179648 531769134 2573270970 28.698 3.15 10366 10360 147757 92 92 38.06 na
2026-11-27T11:02:29Z vm zswap 20261127 4608 1179648 531769134 2573270970 20.711 3.16 8833 8832 210005 128 128 40.12 na
2026-11-27T11:03:04Z vm zswap 20261127 4608 1179648 531769134 2573270970 27.756 3.18 12828 12826 127486 0 0 52.34 na
2026-11-27T11:16:58Z host zram 20261127 6144 1572864 2708526455 3876889511 24.548 2.83 5546 5546 177006 0 0 4.65 14
2026-11-27T11:17:33Z host zram 20261127 6144 1572864 2708526455 3876889511 30.586 2.82 8223 8223 168862 0 0 4.21 1
2026-11-27T11:18:05Z host zram 20261127 6144 1572864 2708526455 3876889511 29.029 3.18 7427 7427 172634 0 0 4.97 0
2026-11-27T11:20:54Z host zswap 20261127 6144 1572864 2708526455 3876889511 49.381 3.21 11684 11684 218408 617001 586700 3.06 6
2026-11-27T11:21:45Z host zswap 20261127 6144 1572864 2708526455 3876889511 45.383 3.21 8973 8973 208093 584944 453067 9.56 29
2026-11-27T11:22:25Z host zswap 20261127 6144 1572864 2708526455 3876889511 35.541 3.21 5490 5490 223518 835213 331649 7.50 13
```
## Host switch log
- zram → zswap, live: `setup_zswap.sh` ran as a system unit. zram0 held
9.9 GB (3.6 GB compressed), MemAvailable was 10.4 GB, and the swapoff
finished in under 35 s. About 3 GB spilled to the swapfiles while it
drained. After that MemAvailable was 4.3 GB, too little for a host run.
`echo 4G > /sys/fs/cgroup/user.slice/memory.reclaim` pushed the cold
pages into the zswap pool (10.9 GB stored in 3.4 GB), which is where zram
had held them.
- zswap → zram, live: `setup_zram.sh` (one command). All three loader
entries are byte-identical to their originals in `/var/lib/swap-switch/`,
and `/proc/cmdline` already said `zswap.enabled=0`, so no reboot was
needed. Pages still in the zswap pool and on the swapfiles (about 17 GB of
slots) come back as they fault in; zram takes all new swap-outs again.
## vmbox checks
`lib/tests/vmbox_swap.sh` (phases, run inside a BIOS/GRUB guest):
- **Live switch zram → zswap:** no zram0; zswap reads `Y`, `zstd`, `35`
and `Y`. After a reboot `/proc/cmdline` carries all four tokens.
- **Revert zswap → zram:** zram0 is back at prio 100 with zstd, zswap reads
`N`, and after a reboot `/proc/cmdline` has `zswap.enabled=0`.
- **Rerun on the same state:** the GRUB files hash the same, the swap list
is unchanged and nothing is reported as changed.
- **Exit 3:** zram held 1.7 GB of a 5 GB tmpfs file and MemAvailable was
50 MB. `setup_zswap.sh` exited 3 with "reboot to apply", leaving zram0
active and zswap off. The next boot came up on zswap.
- **Hibernate with zswap on:** a fresh guest booted with the zswap cmdline,
and a 3 GB tmpfs file went into the pool during hibernation (3.0 GB
stored in 73 MB after resume). `vm wake … systemctl hibernate` gave the `hibernate` verdict, the
guest resumed with the same boot_id, and zswap still read `Y` and `35`.
- **Not explained:** the guest that ran the benchmarks cold-booted on
every hibernate (`PM: Image not found`). This happened under zram as well
as zswap, so the swap setup is not the cause. A fresh guest resumed
under both its default zswap and `setup_zswap.sh`.

View File

@ -143,6 +143,18 @@ check_storage_health() {
fi fi
} }
# swap_setup_advice — where to look first, by the installed swap setup:
# zram (fixes/setup_zram.sh), zswap (fixes/setup_zswap.sh) or plain disk.
swap_setup_advice() {
if grep -q '^/dev/zram' "${PROC_SWAPS:-/proc/swaps}" 2>/dev/null; then
echo "Swap is zram (fixes/setup_zram.sh); check zramctl usage"
elif [[ $(cat "${ZSWAP_ENABLED_FILE:-/sys/module/zswap/parameters/enabled}" 2>/dev/null) == Y ]]; then
echo "Swap is zswap over the disk swapfiles (fixes/setup_zswap.sh); check Zswap/Zswapped in /proc/meminfo"
else
echo "Swap is plain disk swap; check swapon --show"
fi
}
check_memory_pressure() { check_memory_pressure() {
local mem_total mem_available swap_total swap_free local mem_total mem_available swap_total swap_free
mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo) mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
@ -158,7 +170,7 @@ check_memory_pressure() {
echo "Swap usage: ${swap_pct}%" >>"$REPORT_FILE" echo "Swap usage: ${swap_pct}%" >>"$REPORT_FILE"
if [[ $swap_pct -ge 35 && ${mem_available:-0} -gt $((mem_total / 3)) ]]; then if [[ $swap_pct -ge 35 && ${mem_available:-0} -gt $((mem_total / 3)) ]]; then
add_finding "High swap usage while RAM is still available; this can cause stutter." add_finding "High swap usage while RAM is still available; this can cause stutter."
add_action "Swap is zram by design; check zramctl usage and the top memory users (ps aux --sort=-rss | head), then stop idle services." add_action "$(swap_setup_advice) and the top memory users (ps aux --sort=-rss | head), then stop idle services."
fi fi
fi fi

View File

@ -13,7 +13,9 @@ tweak_vm_sysctl() {
# by the test harness, which runs un-jailed in ci_mirror.sh and in CI. # by the test harness, which runs un-jailed in ci_mirror.sh and in CI.
local dropin="${SYSCTL_DROPIN_DIR:-/etc/sysctl.d}/90-desktop-performance.conf" local dropin="${SYSCTL_DROPIN_DIR:-/etc/sysctl.d}/90-desktop-performance.conf"
# Desktop workloads: high swappiness (zram swap is compressed RAM, see fixes/setup_zram.sh), aggressive VFS caching, tuned dirty ratios # Desktop workloads: high swappiness (swap is compressed RAM first, zram or
# zswap: fixes/setup_zram.sh or fixes/setup_zswap.sh), aggressive VFS
# caching, tuned dirty ratios
local -A params=( local -A params=(
["vm.swappiness"]="100" ["vm.swappiness"]="100"
["vm.vfs_cache_pressure"]="50" ["vm.vfs_cache_pressure"]="50"
@ -42,7 +44,7 @@ tweak_vm_sysctl() {
cat >"$dropin" <<'VMEOF' cat >"$dropin" <<'VMEOF'
# Desktop performance tuning — managed by optimize_arch_desktop.sh # Desktop performance tuning — managed by optimize_arch_desktop.sh
# #
# vm.swappiness=100 — favor the 32 GiB zram swap (zstd, prio 100) over dropping page cache # vm.swappiness=100 — favor compressed-RAM swap (zram or zswap, zstd) over dropping page cache
# vm.vfs_cache_pressure=50 — favor keeping inode/dentry caches (speeds up file operations) # vm.vfs_cache_pressure=50 — favor keeping inode/dentry caches (speeds up file operations)
# vm.dirty_ratio=15 — allow up to 15% RAM dirty before synchronous writeback # vm.dirty_ratio=15 — allow up to 15% RAM dirty before synchronous writeback
# vm.dirty_background_ratio=5 — start async writeback at 5% dirty # vm.dirty_background_ratio=5 — start async writeback at 5% dirty

View File

@ -0,0 +1,143 @@
#!/bin/bash
# Shared by setup_zram.sh and setup_zswap.sh: the zswap kernel-cmdline edit,
# the "can zram drain into RAM" guard, and the live zswap parameters.
#
# Sourced, not run; the caller sets SS_NAME (its prefix in messages). Every
# system path has an env override so the tests in lib/tests run against a
# fixture tree and never touch /boot, /etc or /sys.
readonly LOADER_ENTRIES_DIR="${LOADER_ENTRIES_DIR:-/boot/loader/entries}"
readonly GRUB_DEFAULT_FILE="${GRUB_DEFAULT_FILE:-/etc/default/grub}"
readonly GRUB_CFG_FILE="${GRUB_CFG_FILE:-/boot/grub/grub.cfg}"
readonly ZSWAP_PARAMS_DIR="${ZSWAP_PARAMS_DIR:-/sys/module/zswap/parameters}"
readonly ZRAM_SYSFS="${ZRAM_SYSFS:-/sys/block/zram0}"
readonly PROC_MEMINFO="${PROC_MEMINFO:-/proc/meminfo}"
readonly SWAP_SWITCH_BACKUP_DIR="${SWAP_SWITCH_BACKUP_DIR:-/var/lib/swap-switch}"
readonly ZRAM_DEV=/dev/zram0
readonly SS_MIN_SPARE_KIB=$((2 * 1024 * 1024)) # keep 2 GiB free after swapoff
ss_die() {
echo "${SS_NAME}: $*" >&2
exit 1
}
# ss_reboot_to_apply REASON — the boot config is already written; the live
# switch is not safe now. Exit 3 is the documented "reboot to apply" code.
ss_reboot_to_apply() {
echo "${SS_NAME}: $1; boot config is updated, reboot to apply" >&2
exit 3
}
as_root() {
if [[ $EUID -eq 0 ]]; then "$@"; else sudo -n "$@"; fi
}
ss_zram_active() {
swapon --noheadings --show=NAME | grep -qx "$ZRAM_DEV"
}
# ss_has_disk_swap — any active swap that is not zram (zswap needs one).
ss_has_disk_swap() {
swapon --noheadings --show=NAME | grep -qvx "$ZRAM_DEV"
}
# ss_can_drain — 0 when MemAvailable absorbs the zram contents with 2 GiB
# spare. The cost is the uncompressed data minus the compressed pages that
# swapoff frees as it drains; disk swap is NOT a swapoff target.
ss_can_drain() {
local orig total avail
read -r orig total < <(zramctl --bytes --noheadings --raw -o DATA,TOTAL "$ZRAM_DEV")
avail=$(awk '/^MemAvailable:/ {print $2}' "$PROC_MEMINFO")
((avail - (orig - total) / 1024 >= SS_MIN_SPARE_KIB))
}
# ss_edit_tokens TOKENS — filter stdin: drop every zswap.* word of a kernel
# cmdline and put TOKENS where the first one stood (appended if none). Words
# are space-separated; a leading key such as `options` is just a word.
ss_edit_tokens() {
local tokens="$1" word out placed=0
local -a words
read -r -a words
for word in "${words[@]}"; do
if [[ $word == zswap.* ]]; then
((placed)) || [[ -z $tokens ]] || out+=" ${tokens}"
placed=1
else
out+=" ${word}"
fi
done
((placed)) || [[ -z $tokens ]] || out+=" ${tokens}"
printf '%s\n' "${out# }"
}
# _ss_rewrite FILE KIND TOKENS — rewrite FILE's cmdline line(s); print
# "changed" when the content differs (and is then installed with a one-time
# backup of the original), nothing otherwise.
_ss_rewrite() {
local file="$1" kind="$2" tokens="$3" line tmp edited=0
tmp="$(mktemp)"
while IFS= read -r line || [[ -n $line ]]; do
if [[ $kind == loader && $line == options\ * ]] && ((! edited)); then
line="$(ss_edit_tokens "$tokens" <<<"$line")"
edited=1
elif [[ $kind == loader && $line == options\ * ]]; then
line="$(ss_edit_tokens "" <<<"$line")"
elif [[ $kind == grub && $line =~ ^GRUB_CMDLINE_LINUX_DEFAULT=\"(.*)\"$ ]]; then
line="GRUB_CMDLINE_LINUX_DEFAULT=\"$(ss_edit_tokens "$tokens" <<<"${BASH_REMATCH[1]}")\""
fi
printf '%s\n' "$line"
done <"$file" >"$tmp"
if cmp -s "$file" "$tmp"; then
rm -f "$tmp"
return 0
fi
local backup
backup="${SWAP_SWITCH_BACKUP_DIR}/$(basename "$file").orig"
as_root mkdir -p "$SWAP_SWITCH_BACKUP_DIR"
[[ -e $backup ]] || as_root cp -p "$file" "$backup"
as_root install -m 644 "$tmp" "$file"
rm -f "$tmp"
echo changed
}
# ss_set_boot_tokens TOKENS — persist the zswap.* words for the next boot:
# every systemd-boot entry when there are any, else GRUB's defaults (plus a
# grub.cfg rebuild when they changed). Other words, resume= included, stay.
ss_set_boot_tokens() {
local tokens="$1" entry changed=""
local -a entries=()
if [[ -d $LOADER_ENTRIES_DIR ]]; then
mapfile -t entries < <(find "$LOADER_ENTRIES_DIR" -maxdepth 1 -name '*.conf' | sort)
fi
if ((${#entries[@]})); then
for entry in "${entries[@]}"; do
changed+="$(_ss_rewrite "$entry" loader "$tokens")"
done
elif [[ -f $GRUB_DEFAULT_FILE ]]; then
changed="$(_ss_rewrite "$GRUB_DEFAULT_FILE" grub "$tokens")"
if [[ -n $changed ]]; then
# grub-mkconfig narrates every step on stderr; show it only on failure.
local log
log="$(as_root grub-mkconfig -o "$GRUB_CFG_FILE" 2>&1)" ||
ss_die "grub-mkconfig failed: $log"
fi
else
ss_die "no systemd-boot entries in $LOADER_ENTRIES_DIR and no $GRUB_DEFAULT_FILE"
fi
[[ -z $changed ]] || echo "${SS_NAME}: kernel cmdline now carries: $tokens"
}
# ss_zswap_set NAME VALUE — write a live zswap parameter when it differs.
ss_zswap_set() {
local path="${ZSWAP_PARAMS_DIR}/$1"
[[ $(cat "$path") == "$2" ]] && return 0
printf '%s\n' "$2" | as_root tee "$path" >/dev/null
}
ss_report() {
swapon --show
local p
for p in enabled compressor max_pool_percent shrinker_enabled; do
printf 'zswap %s=%s\n' "$p" "$(cat "${ZSWAP_PARAMS_DIR}/$p")"
done
}

View File

@ -0,0 +1,125 @@
#!/usr/bin/env bash
# lib/tests/swap_switch_harness.sh — fake machine for setup_zram.sh,
# setup_zswap.sh and lib/swap_switch.sh.
#
# Sourced, not executed. Every path the scripts touch (loader entries, GRUB
# defaults, the zram conf, /sys/module/zswap, /sys/block/zram0, meminfo, the
# backup dir) is redirected into $TEST_TMPDIR through the scripts' env
# overrides, and the commands that change live state are stubs that update
# fixture files, so a second run sees the result of the first:
#
# $DEV/swaps active swap names, one per line (swapon/swapoff/systemctl)
# $DEV/zramctl "DATA TOTAL" bytes for zram0
# zram disksize $ZRAM_SYSFS/disksize, set by the systemd-zram-setup stub
#
# run_all.sh runs un-jailed in CI, so these overrides are all that keeps the
# suite off the real /boot and /sys.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FIXES_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
export FIXES_DIR
# shellcheck source=lib_test_core.sh
. "${SCRIPT_DIR}/lib_test_core.sh"
export LOADER_ENTRIES_DIR="${TEST_TMPDIR}/boot/loader/entries"
export GRUB_DEFAULT_FILE="${TEST_TMPDIR}/etc/default/grub"
export GRUB_CFG_FILE="${TEST_TMPDIR}/boot/grub/grub.cfg"
export ZRAM_CONF="${TEST_TMPDIR}/etc/systemd/zram-generator.conf"
export ZSWAP_PARAMS_DIR="${TEST_TMPDIR}/sys/module/zswap/parameters"
export ZRAM_SYSFS="${TEST_TMPDIR}/sys/block/zram0"
export PROC_MEMINFO="${TEST_TMPDIR}/proc/meminfo"
export SWAP_SWITCH_BACKUP_DIR="${TEST_TMPDIR}/var/lib/swap-switch"
export ZRAM_GENERATOR_BIN="${TEST_TMPDIR}/zram-generator"
readonly GIB=1073741824
readonly WANT_BYTES=$((32 * GIB))
export WANT_BYTES
readonly HOST_OPTS="root=PARTUUID=x zswap.enabled=0 rw rootfstype=ext4 resume=UUID=y resume_offset=22429696"
export HOST_OPTS
# _sw_machine STATE — build a fresh fake machine. STATE is zram (zram0 active
# at 32G, zswap off), zswap (no zram, zswap on) or bare (neither).
_sw_machine() {
local state="$1"
rm -rf "${TEST_TMPDIR:?}/boot" "${TEST_TMPDIR:?}/etc" "${TEST_TMPDIR:?}/sys" \
"${TEST_TMPDIR:?}/proc" "${TEST_TMPDIR:?}/var"
mkdir -p "$LOADER_ENTRIES_DIR" "$ZSWAP_PARAMS_DIR" "$ZRAM_SYSFS" \
"${PROC_MEMINFO%/*}" "${ZRAM_CONF%/*}"
: >"$ZRAM_GENERATOR_BIN"
chmod +x "$ZRAM_GENERATOR_BIN"
local entry
for entry in linux linux-fallback linux-lts; do
printf 'title Arch Linux (%s)\nlinux /vmlinuz-%s\noptions %s\n' \
"$entry" "$entry" "$HOST_OPTS" >"${LOADER_ENTRIES_DIR}/${entry}.conf"
done
printf 'MemTotal: 31000000 kB\nMemAvailable: 15000000 kB\n' >"$PROC_MEMINFO"
printf '%s %s\n' $((11 * GIB)) $((3 * GIB)) >"${DEV}/zramctl"
printf 'zstd\n' >"${ZSWAP_PARAMS_DIR}/compressor"
printf '20\n' >"${ZSWAP_PARAMS_DIR}/max_pool_percent"
printf 'Y\n' >"${ZSWAP_PARAMS_DIR}/shrinker_enabled"
printf '/swapfile\n/swapfile2\n' >"${DEV}/swaps"
case "$state" in
zram)
cp "${FIXES_DIR}/zram-generator.conf" "$ZRAM_CONF"
printf '%s\n' "$WANT_BYTES" >"${ZRAM_SYSFS}/disksize"
printf '/dev/zram0\n' >>"${DEV}/swaps"
printf 'N\n' >"${ZSWAP_PARAMS_DIR}/enabled"
;;
zswap)
sed -i 's/zswap.enabled=0/zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=35 zswap.shrinker_enabled=1/' \
"${LOADER_ENTRIES_DIR}"/*.conf
printf '0\n' >"${ZRAM_SYSFS}/disksize"
printf 'Y\n' >"${ZSWAP_PARAMS_DIR}/enabled"
printf '35\n' >"${ZSWAP_PARAMS_DIR}/max_pool_percent"
;;
bare)
printf '0\n' >"${ZRAM_SYSFS}/disksize"
printf 'N\n' >"${ZSWAP_PARAMS_DIR}/enabled"
;;
esac
_t_reset_calls
}
# _sw_snapshot — checksum of every boot-config file, for byte-identity checks.
_sw_snapshot() {
cat "${LOADER_ENTRIES_DIR}"/*.conf "$GRUB_DEFAULT_FILE" 2>/dev/null | md5sum
}
# _sw_param NAME — current fake zswap parameter.
_sw_param() { cat "${ZSWAP_PARAMS_DIR}/$1"; }
_sw_stubs() {
_t_stub_stdin sudo <<'STUB'
[[ $1 == -n ]] && shift
exec "$@"
STUB
_t_stub udevadm 'exit 0'
_t_stub pacman 'exit 0'
_t_stub grub-mkconfig 'exit 0'
_t_stub_stdin swapon <<'STUB'
swaps="${LIB_TEST_DEV}/swaps"
case "$*" in
*--show=NAME*) cat "$swaps" ;;
*--show*) printf 'NAME TYPE\n'; sed 's/$/ swap/' "$swaps" ;;
*) printf '%s\n' "${*: -1}" >>"$swaps" ;;
esac
STUB
_t_stub_stdin swapoff <<'STUB'
grep -vx -- "$1" "${LIB_TEST_DEV}/swaps" >"${LIB_TEST_DEV}/swaps.new" || true
mv "${LIB_TEST_DEV}/swaps.new" "${LIB_TEST_DEV}/swaps"
STUB
_t_stub_cat zramctl zramctl
_t_stub_stdin systemctl <<'STUB'
case "$*" in
"restart systemd-zram-setup@zram0.service")
size="$(sed -n 's/^zram-size *= *//p' "$ZRAM_CONF")"
echo $(((size) * 1024 * 1024)) >"${ZRAM_SYSFS}/disksize" ;;
"stop systemd-zram-setup@zram0.service") echo 0 >"${ZRAM_SYSFS}/disksize" ;;
"start dev-zram0.swap") echo /dev/zram0 >>"${LIB_TEST_DEV}/swaps" ;;
esac
exit 0
STUB
}
_sw_stubs

View File

@ -133,6 +133,16 @@ fi
# stubbing awk supplies controlled figures without touching /proc. The stub # stubbing awk supplies controlled figures without touching /proc. The stub
# answers on the pattern the lib greps for, and defers to the real awk for # answers on the pattern the lib greps for, and defers to the real awk for
# any other call (check_thermal_state and collect_basics use it too). # any other call (check_thermal_state and collect_basics use it too).
# The advice names the installed swap setup, read from fixture copies of
# /proc/swaps and the zswap enabled flag.
export PROC_SWAPS="${TEST_TMPDIR}/proc_swaps"
export ZSWAP_ENABLED_FILE="${TEST_TMPDIR}/zswap_enabled"
_swap_fixture() { # _swap_fixture zram|zswap|disk
printf 'Filename Type Size Used Priority\n/swapfile file 1 0 -1\n' >"$PROC_SWAPS"
[[ $1 == zram ]] && printf '/dev/zram0 partition 1 0 100\n' >>"$PROC_SWAPS"
if [[ $1 == zswap ]]; then echo Y; else echo N; fi >"$ZSWAP_ENABLED_FILE"
}
_high_swap() {
arch_reset arch_reset
_t_stub_stdin awk <<'STUB_BODY' _t_stub_stdin awk <<'STUB_BODY'
case "$1" in case "$1" in
@ -144,12 +154,24 @@ case "$1" in
esac esac
STUB_BODY STUB_BODY
check_memory_pressure check_memory_pressure
}
_swap_fixture zswap
_high_swap
_t_contains "$(_t_actions)" "zswap" "check_memory_pressure: names zswap when it is installed"
_t_contains "$(_t_actions)" "Zswapped" "check_memory_pressure: points at the zswap pool counters"
_t_lacks "$(_t_actions)" "zramctl" "check_memory_pressure: no zramctl advice under zswap"
_swap_fixture disk
_high_swap
_t_contains "$(_t_actions)" "swapon --show" "check_memory_pressure: plain disk swap points at swapon"
_t_lacks "$(_t_actions)" "zram" "check_memory_pressure: plain disk swap does not claim zram"
_swap_fixture zram
_high_swap
_t_contains "$(_t_report)" "Swap usage: 75%" \ _t_contains "$(_t_report)" "Swap usage: 75%" \
"check_memory_pressure: computes the swap usage percentage" "check_memory_pressure: computes the swap usage percentage"
_t_contains "$(_t_findings)" "High swap usage while RAM is still available" \ _t_contains "$(_t_findings)" "High swap usage while RAM is still available" \
"check_memory_pressure: flags heavy swapping while RAM is free" "check_memory_pressure: flags heavy swapping while RAM is free"
_t_lacks "$(_t_actions)" "swappiness" \ _t_lacks "$(_t_actions)" "swappiness" \
"check_memory_pressure: does not suggest tuning swappiness (zram setup runs at 100)" "check_memory_pressure: does not suggest tuning swappiness (both swap setups run at 100)"
_t_contains "$(_t_actions)" "zramctl" \ _t_contains "$(_t_actions)" "zramctl" \
"check_memory_pressure: points at zramctl usage" "check_memory_pressure: points at zramctl usage"
_t_contains "$(_t_actions)" "ps aux --sort=-rss" \ _t_contains "$(_t_actions)" "ps aux --sort=-rss" \

View File

@ -0,0 +1,109 @@
#!/usr/bin/env bash
# lib/tests/test_swap_bench.sh — swap_bench.sh runs the seeded workload in
# the right place, records one row per run, and never records a failed run.
#
# /proc, /sys and the cgroup tree are fixture files; systemd-run is a stub
# that drops its options and runs the command, so no scope and no memory
# pressure is created. The workload itself is the real Python at 1 MiB.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FIXES_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
# shellcheck source=lib_test_core.sh
. "${SCRIPT_DIR}/lib_test_core.sh"
BENCH="${FIXES_DIR}/swap_bench.sh"
readonly BENCH
export SWAP_BENCH_RESULTS="${TEST_TMPDIR}/results.tsv"
export PROC_VMSTAT="${TEST_TMPDIR}/proc/vmstat"
export PROC_PRESSURE="${TEST_TMPDIR}/proc/pressure_memory"
export PROC_MEMINFO="${TEST_TMPDIR}/proc/meminfo"
export PROC_SELF_CGROUP="${TEST_TMPDIR}/proc/self_cgroup"
export CGROUP_ROOT="${TEST_TMPDIR}/cgroup"
export ZRAM_SYSFS="${TEST_TMPDIR}/sys/block/zram0"
export ZSWAP_PARAMS_DIR="${TEST_TMPDIR}/sys/module/zswap/parameters"
mkdir -p "${TEST_TMPDIR}/proc" "${CGROUP_ROOT}/bench.scope" "$ZRAM_SYSFS" "$ZSWAP_PARAMS_DIR"
psi='some avg10=0.00 avg60=0.00 avg300=0.00 total=5000
full avg10=0.00 avg60=0.00 avg300=0.00 total=2000'
printf '%s\n' "$psi" >"$PROC_PRESSURE"
printf '%s\n' "$psi" >"${CGROUP_ROOT}/bench.scope/memory.pressure"
mkdir -p "${CGROUP_ROOT}/user.slice/user-1000.slice/session-1.scope"
printf '%s\n' "$psi" >"${CGROUP_ROOT}/user.slice/user-1000.slice/session-1.scope/memory.pressure"
printf 'zswap 0\nzswapped 0\nzswpwb 0\n' >"${CGROUP_ROOT}/bench.scope/memory.stat"
printf 'pswpout 10\nzswpwb 0\n' >"$PROC_VMSTAT"
printf 'MemAvailable: 9000000 kB\nZswap: 0 kB\nZswapped: 0 kB\n' >"$PROC_MEMINFO"
printf '0::/bench.scope\n' >"$PROC_SELF_CGROUP"
printf '1 0 0 0 1 0 80 0 0 0 0\n' >"${ZRAM_SYSFS}/stat"
printf '4096 1024 0 0\n' >"${ZRAM_SYSFS}/mm_stat"
_t_stub_stdin systemd-run <<'STUB'
while [[ $1 != -- ]]; do shift; done
shift
exec "$@"
STUB
_t_stub_cat swapon swaps
_setup() { # _setup zram|zswap|none|both
case "$1" in
zram | both) printf '/swapfile\n/dev/zram0\n' >"${DEV}/swaps" ;;
*) printf '/swapfile\n' >"${DEV}/swaps" ;;
esac
case "$1" in zswap | both) echo Y ;; *) echo N ;; esac >"${ZSWAP_PARAMS_DIR}/enabled"
_t_reset_calls
}
_col() { awk -F'\t' -v c="$1" 'NR==1 {for (i=1;i<=NF;i++) if ($i==c) n=i; next} {print $n}' "$SWAP_BENCH_RESULTS"; }
echo "host run under a swap-allowed scope (C6)"
_setup zram
_t_run bash "$BENCH" run host --seed 7 --size-mib 1
_t_eq 0 "$?" "run host: exits 0"
_t_contains "$(_t_calls)" "MemoryMax=4G" "run host: scope caps RAM at 4G"
_t_contains "$(_t_calls)" "MemorySwapMax=infinity" "run host: scope may swap"
_t_contains "$(_t_calls)" "RuntimeMaxSec=55" "run host: scope dies before the 60 s cap"
_t_eq "zram" "$(_col setup)" "run host: row records the zram setup"
_t_eq "host" "$(_col env)" "run host: row records env"
_t_contains "$out" "global memory PSI full avg10" "run host: prints the global PSI"
_t_eq 0 "$(_col desktop_full_ms)" "run host: records the session scopes' PSI stall"
echo "same seed, same workload (C7)"
_t_run bash "$BENCH" run host --seed 7 --size-mib 1
_t_eq 1 "$(grep -c '^date' "$SWAP_BENCH_RESULTS")" "rerun: header written once"
_t_eq 1 "$(_col fill_crc | sort -u | wc -l)" "rerun: same fill checksum"
_t_eq 1 "$(_col touch_crc | sort -u | wc -l)" "rerun: same touch checksum"
_t_eq 256 "$(_col pages | sort -u)" "rerun: same page count"
echo "vm run is system-wide, no scope"
_setup zswap
_t_run bash "$BENCH" run vm --seed 7 --size-mib 1
_t_eq 0 "$?" "run vm: exits 0"
_t_lacks "$(_t_calls)" "systemd-run" "run vm: no scope"
_t_eq zswap "$(_col setup | tail -1)" "run vm: row records zswap"
echo "refusals record nothing"
rows="$(wc -l <"$SWAP_BENCH_RESULTS")"
_setup none
_t_run bash "$BENCH" run host --size-mib 1
_t_eq 1 "$?" "neither setup: exit 1"
_t_contains "$out" "neither zram nor zswap" "neither setup: says so"
_setup both
_t_run bash "$BENCH" run host --size-mib 1
_t_eq 1 "$?" "both setups: exit 1"
_setup zram
_t_run bash "$BENCH" run host --size-mib 0
_t_eq 1 "$?" "failed workload: exit 1"
_t_contains "$out" "no row recorded" "failed workload: says no row"
printf 'MemAvailable: 6000000 kB\n' >"$PROC_MEMINFO"
_t_run bash "$BENCH" run host --size-mib 1
_t_eq 1 "$?" "low MemAvailable: host run refused"
_t_contains "$out" "press the desktop" "low MemAvailable: says why"
printf 'MemAvailable: 9000000 kB\nZswap: 0 kB\nZswapped: 0 kB\n' >"$PROC_MEMINFO"
_t_run bash "$BENCH" run cloud
_t_eq 2 "$?" "unknown env: usage exit 2"
_t_eq "$rows" "$(wc -l <"$SWAP_BENCH_RESULTS")" "refusals: no row appended"
echo "summary (C8)"
_t_run bash "$BENCH" summary
_t_eq 0 "$?" "summary: exits 0"
_t_contains "$out" "| host | zram | 2 |" "summary: host zram medians over 2 runs"
_t_contains "$out" "vm winner: n/a" "summary: no vm winner without both setups"
printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]

View File

@ -0,0 +1,121 @@
#!/usr/bin/env bash
# lib/tests/test_swap_switch.sh — setup_zswap.sh / setup_zram.sh switch the
# swap setup live, persist it on the kernel cmdline, and are idempotent.
set -uo pipefail
# shellcheck source=swap_switch_harness.sh
. "$(dirname "${BASH_SOURCE[0]}")/swap_switch_harness.sh"
ZSWAP="${FIXES_DIR}/setup_zswap.sh"
ZRAM="${FIXES_DIR}/setup_zram.sh"
readonly ZSWAP ZRAM
# _absent PATH WHAT / _same A B WHAT — file assertions as plain if/else.
_absent() { if [[ -e $1 ]]; then _t_fail "$2"; else _t_pass "$2"; fi; }
_same() { if cmp -s "$1" "$2"; then _t_pass "$3"; else _t_fail "$3"; fi; }
readonly ZSWAP_TOKENS="zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=35 zswap.shrinker_enabled=1"
echo "zram -> zswap, live (C1)"
_sw_machine zram
_t_run bash "$ZSWAP"
_t_eq 0 "$?" "setup_zswap: exits 0 with room to drain zram"
_t_lacks "$(cat "${DEV}/swaps")" "/dev/zram0" "setup_zswap: zram0 swapped off"
_t_contains "$(_t_calls)" "swapoff /dev/zram0" "setup_zswap: ran swapoff on zram0"
_t_eq Y "$(_sw_param enabled)" "setup_zswap: enabled=Y"
_t_eq zstd "$(_sw_param compressor)" "setup_zswap: compressor=zstd"
_t_eq 35 "$(_sw_param max_pool_percent)" "setup_zswap: max_pool_percent=35"
for f in "${LOADER_ENTRIES_DIR}"/*.conf; do
_t_contains "$(cat "$f")" "options root=PARTUUID=x ${ZSWAP_TOKENS} rw rootfstype=ext4 resume=UUID=y resume_offset=22429696" \
"setup_zswap: $(basename "$f") has the zswap tokens in place, resume kept"
done
_t_eq 1 "$(grep -o 'zswap.enabled' "${LOADER_ENTRIES_DIR}/linux.conf" | wc -l)" \
"setup_zswap: one zswap.enabled token per entry"
_absent "$ZRAM_CONF" "setup_zswap: zram conf removed"
_t_eq 3 "$(find "$SWAP_SWITCH_BACKUP_DIR" -name '*.conf.orig' | wc -l)" \
"setup_zswap: backed up the three original entries"
_t_contains "$out" "/swapfile" "setup_zswap: prints swapon --show"
echo "zswap again is a no-op (C4)"
before="$(_sw_snapshot)"
_t_reset_calls
_t_run bash "$ZSWAP"
_t_eq 0 "$?" "setup_zswap rerun: exits 0"
_t_eq "$before" "$(_sw_snapshot)" "setup_zswap rerun: boot config byte-identical"
_t_lacks "$(_t_calls)" "swapoff" "setup_zswap rerun: no swapoff"
_t_lacks "$(_t_calls)" "daemon-reload" "setup_zswap rerun: no daemon-reload"
echo "zswap -> zram revert (C3)"
_t_reset_calls
_t_run bash "$ZRAM"
_t_eq 0 "$?" "setup_zram: exits 0"
_t_contains "$(cat "${DEV}/swaps")" "/dev/zram0" "setup_zram: zram0 is swap again"
_t_eq "$WANT_BYTES" "$(cat "${ZRAM_SYSFS}/disksize")" "setup_zram: zram0 is 32G"
_t_eq N "$(_sw_param enabled)" "setup_zram: zswap enabled=N"
_t_contains "$(cat "${LOADER_ENTRIES_DIR}/linux-lts.conf")" "options ${HOST_OPTS}" \
"setup_zram: entry back to the original options line"
_same "${FIXES_DIR}/zram-generator.conf" "$ZRAM_CONF" "setup_zram: conf installed"
echo "zram again is a no-op (C4)"
before="$(_sw_snapshot)"
_t_reset_calls
_t_run bash "$ZRAM"
_t_eq 0 "$?" "setup_zram rerun: exits 0"
_t_eq "$before" "$(_sw_snapshot)" "setup_zram rerun: boot config byte-identical"
_t_lacks "$(_t_calls)" "swapoff" "setup_zram rerun: no swapoff"
echo "zram full, too little RAM: exit 3 (C5)"
_sw_machine zram
printf 'MemTotal: 31000000 kB\nMemAvailable: 9000000 kB\n' >"$PROC_MEMINFO"
_t_run bash "$ZSWAP"
_t_eq 3 "$?" "setup_zswap: exit 3 when zram cannot drain"
_t_contains "$out" "reboot to apply" "setup_zswap: says reboot to apply"
_t_contains "$(cat "${DEV}/swaps")" "/dev/zram0" "setup_zswap exit 3: zram0 still active"
_t_eq N "$(_sw_param enabled)" "setup_zswap exit 3: zswap still off"
_t_contains "$(cat "${LOADER_ENTRIES_DIR}/linux.conf")" "$ZSWAP_TOKENS" \
"setup_zswap exit 3: next boot comes up on zswap"
_absent "$ZRAM_CONF" "setup_zswap exit 3: zram conf removed"
echo "no disk swap: refuse"
_sw_machine bare
: >"${DEV}/swaps"
_t_run bash "$ZSWAP"
_t_eq 1 "$?" "setup_zswap: refuses with no disk swap to back zswap"
_t_contains "$out" "no disk swap" "setup_zswap: names the missing backing swap"
echo "GRUB machine"
_sw_machine zram
rm -rf "$LOADER_ENTRIES_DIR"
mkdir -p "${GRUB_DEFAULT_FILE%/*}"
printf 'GRUB_TIMEOUT=1\nGRUB_CMDLINE_LINUX_DEFAULT="loglevel=3 resume=/dev/vda2"\n' >"$GRUB_DEFAULT_FILE"
_t_run bash "$ZSWAP"
_t_eq 0 "$?" "setup_zswap grub: exits 0"
_t_contains "$(cat "$GRUB_DEFAULT_FILE")" "GRUB_CMDLINE_LINUX_DEFAULT=\"loglevel=3 resume=/dev/vda2 ${ZSWAP_TOKENS}\"" \
"setup_zswap grub: tokens appended inside the quotes"
_t_contains "$(_t_calls)" "grub-mkconfig -o ${GRUB_CFG_FILE}" "setup_zswap grub: regenerated grub.cfg"
_t_reset_calls
_t_run bash "$ZSWAP"
_t_lacks "$(_t_calls)" "grub-mkconfig" "setup_zswap grub rerun: no grub-mkconfig"
_t_run bash "$ZRAM"
_t_contains "$(cat "$GRUB_DEFAULT_FILE")" 'GRUB_CMDLINE_LINUX_DEFAULT="loglevel=3 resume=/dev/vda2 zswap.enabled=0"' \
"setup_zram grub: zswap.enabled=0 replaces the zswap tokens"
echo "grub-mkconfig failure is loud"
_t_stub grub-mkconfig 'echo boom >&2; exit 1'
_t_run bash "$ZSWAP"
_t_eq 1 "$?" "setup_zswap grub: grub-mkconfig failure exits 1"
_t_contains "$out" "grub-mkconfig failed: boom" "setup_zswap grub: shows grub-mkconfig's output"
_t_stub grub-mkconfig 'exit 0'
echo "neither bootloader: refuse"
_sw_machine zram
rm -rf "$LOADER_ENTRIES_DIR"
_t_run bash "$ZSWAP"
_t_eq 1 "$?" "setup_zswap: refuses with no loader entries and no GRUB"
echo "scaled zram for a small guest"
_sw_machine zswap
ZRAM_SIZE_MIB=4370 _t_run bash "$ZRAM"
_t_eq 0 "$?" "setup_zram ZRAM_SIZE_MIB: exits 0"
_t_eq $((4370 * 1024 * 1024)) "$(cat "${ZRAM_SYSFS}/disksize")" "setup_zram ZRAM_SIZE_MIB: zram0 sized to it"
_t_contains "$(cat "$ZRAM_CONF")" "zram-size = 4370" "setup_zram ZRAM_SIZE_MIB: conf carries it"
printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]

View File

@ -0,0 +1,145 @@
#!/usr/bin/env bash
# lib/tests/vmbox_swap.sh — prove setup_zram.sh / setup_zswap.sh in a vmbox
# guest (BIOS/GRUB): live switch both ways, persistence across a reboot,
# idempotence, and the exit-3 "reboot to apply" path.
#
# Runs INSIDE the guest, as root, one phase per call so each stays under a
# minute. Never on the host: it swaps zram off and rewrites GRUB. Not named
# test_*.sh, so run_all.sh and CI never pick it up. From the host:
#
# vm new zsw; vm hibernate-setup zsw --swap-mb 8192
# vm repo zsw ~/src/testsAndMisc --worktree # lands in ~/testsAndMisc
# C="sudo bash ~/testsAndMisc/linux_configuration/fixes/lib/tests/vmbox_swap.sh"
# vm run zsw "$C zram"; vm run zsw 'sudo systemctl reboot'; vm start zsw
# vm run zsw "$C booted-zram"; vm run zsw "$C again"
# vm run zsw "$C zswap"; vm run zsw "$C again"
# vm run zsw 'sudo systemctl reboot'; vm start zsw; vm run zsw "$C booted-zswap"
# vm run zsw "$C zram"; vm run zsw "$C fill"; vm run zsw "$C exit3"
# vm run zsw 'sudo systemctl reboot'; vm start zsw; vm run zsw "$C booted-zswap"
#
# The guest's zram device is scaled to the same RAM budget as the host's
# 32 GiB on ~30 GiB: 35 % of RAM compressed at the 3.2:1 the bench measures.
# Each phase prints one OK/FAIL line per check and exits non-zero on a FAIL.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly FIXES="${HERE}/../.."
readonly ZSWAP_TOKENS="zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=35 zswap.shrinker_enabled=1"
readonly P=/sys/module/zswap/parameters
readonly FILL_DIR=/mnt/swapfill
FAILED=0
ok() { printf 'OK %s\n' "$1"; }
bad() {
printf 'FAIL %s\n' "$1"
FAILED=1
}
# want WHAT EXPECTED ACTUAL
want() { if [[ $3 == "$2" ]]; then ok "$1"; else bad "$1 (want '$2', got '$3')"; fi; }
# has WHAT HAYSTACK NEEDLE
has() { if [[ $2 == *"$3"* ]]; then ok "$1"; else bad "$1 (no '$3' in: $2)"; fi; }
zram_mib() { awk '/^MemTotal:/ {print int($2 / 1024 * 35 * 32 / 1000)}' /proc/meminfo; }
zram_swap() { swapon --noheadings --show=NAME,PRIO | awk '$1 == "/dev/zram0" {print $2}'; }
grub_line() { grep '^GRUB_CMDLINE_LINUX_DEFAULT=' /etc/default/grub; }
check_zram_live() {
want "zram0 is swap at prio 100" 100 "$(zram_swap)"
want "zram0 compresses with zstd" zstd "$(zramctl --noheadings -o ALGORITHM /dev/zram0 | tr -d ' ')"
want "zswap enabled=N" N "$(cat "$P/enabled")"
}
check_zswap_live() {
want "no zram0 swap" "" "$(zram_swap)"
want "zswap enabled=Y" Y "$(cat "$P/enabled")"
want "zswap compressor=zstd" zstd "$(cat "$P/compressor")"
want "zswap max_pool_percent=35" 35 "$(cat "$P/max_pool_percent")"
want "zswap shrinker_enabled=Y" Y "$(cat "$P/shrinker_enabled")"
}
phase_zram() {
ZRAM_SIZE_MIB="$(zram_mib)" bash "${FIXES}/setup_zram.sh"
check_zram_live
has "GRUB defaults carry zswap.enabled=0" "$(grub_line)" "zswap.enabled=0"
has "grub.cfg carries zswap.enabled=0" "$(cat /boot/grub/grub.cfg)" "zswap.enabled=0"
}
phase_zswap() {
bash "${FIXES}/setup_zswap.sh"
check_zswap_live
has "GRUB defaults carry the zswap tokens" "$(grub_line)" "$ZSWAP_TOKENS"
has "grub.cfg carries the zswap tokens" "$(cat /boot/grub/grub.cfg)" "$ZSWAP_TOKENS"
has "resume= kept" "$(grub_line)" "resume_offset="
}
phase_booted_zram() {
has "/proc/cmdline has zswap.enabled=0" "$(cat /proc/cmdline)" "zswap.enabled=0"
check_zram_live
}
phase_booted_zswap() {
has "/proc/cmdline has the zswap tokens" "$(cat /proc/cmdline)" "$ZSWAP_TOKENS"
check_zswap_live
}
# again — rerun the script of whichever setup is live; nothing may change.
phase_again() {
local script=setup_zswap.sh before after out
[[ -n $(zram_swap) ]] && script=setup_zram.sh
before="$(
md5sum /etc/default/grub /boot/grub/grub.cfg
swapon --show
)"
out="$(ZRAM_SIZE_MIB="$(zram_mib)" bash "${FIXES}/${script}" 2>&1)"
after="$(
md5sum /etc/default/grub /boot/grub/grub.cfg
swapon --show
)"
want "${script} rerun: GRUB files and swap list unchanged" "$before" "$after"
has "${script} rerun: prints swapon --show" "$out" "NAME"
want "${script} rerun: no cmdline change reported" "" "$(grep 'cmdline now' <<<"$out" || true)"
}
# fill — push more into zram than MemAvailable can take back: a tmpfs file
# is swappable shmem, and RAM stays full of the rest of it.
phase_fill() {
mkdir -p "$FILL_DIR"
mountpoint -q "$FILL_DIR" || mount -t tmpfs -o size=7G tmpfs "$FILL_DIR"
yes "$(seq -s ' ' 1 40)" | head -c 5G >"${FILL_DIR}/blob" || true
zramctl
grep MemAvailable /proc/meminfo
}
phase_exit3() {
local rc=0 out
out="$(bash "${FIXES}/setup_zswap.sh" 2>&1)" || rc=$?
want "setup_zswap exits 3 when zram cannot drain" 3 "$rc"
has "setup_zswap says reboot to apply" "$out" "reboot to apply"
want "zram0 still active" 100 "$(zram_swap)"
want "zswap still off" N "$(cat "$P/enabled")"
has "GRUB defaults already carry the zswap tokens" "$(grub_line)" "$ZSWAP_TOKENS"
}
main() {
[[ $EUID -eq 0 ]] || {
echo "run as root inside the guest" >&2
exit 2
}
case "${1:-}" in
zram) phase_zram ;;
zswap) phase_zswap ;;
booted-zram) phase_booted_zram ;;
booted-zswap) phase_booted_zswap ;;
again) phase_again ;;
fill) phase_fill ;;
exit3) phase_exit3 ;;
*)
echo "usage: $0 zram|zswap|booted-zram|booted-zswap|again|fill|exit3" >&2
exit 2
;;
esac
return "$FAILED"
}
main "$@"
exit $?

View File

@ -5,7 +5,7 @@
# Tuning areas: # Tuning areas:
# 1. CPU scheduler — performance governor on all cores # 1. CPU scheduler — performance governor on all cores
# 2. I/O scheduler — optimal scheduler per drive type (none for NVMe, mq-deadline for SATA SSD) # 2. I/O scheduler — optimal scheduler per drive type (none for NVMe, mq-deadline for SATA SSD)
# 3. Memory / swap — high swappiness for zram swap, tune dirty page writeback for responsiveness # 3. Memory / swap — high swappiness for compressed-RAM swap (zram or zswap), tune dirty page writeback for responsiveness
# 4. Kernel network — TCP BBR, fastopen, larger buffers # 4. Kernel network — TCP BBR, fastopen, larger buffers
# 5. Filesystem — fstrim timer, noatime advisory # 5. Filesystem — fstrim timer, noatime advisory
# 6. NVIDIA GPU — max performance level via persistence mode # 6. NVIDIA GPU — max performance level via persistence mode

View File

@ -1,60 +1,55 @@
#!/bin/bash #!/bin/bash
# Install fixes/zram-generator.conf and resize the live /dev/zram0 to match. # Switch swap to zram (the default) and size /dev/zram0 to match the conf.
#
# Also the one-command revert from setup_zswap.sh: puts zswap.enabled=0 back
# on the kernel cmdline, installs fixes/zram-generator.conf, starts zram0,
# and only then turns zswap off live. That order is always safe: pages left
# in the zswap pool drain back as they fault in.
# #
# Resizing needs the device reset, i.e. swapoff first: the zram pages move back # Resizing needs the device reset, i.e. swapoff first: the zram pages move back
# into RAM (disk swap is NOT a target of swapoff), so the script refuses when # into RAM (disk swap is NOT a target of swapoff), so the script refuses when
# MemAvailable could not absorb them. Disk swapfiles are left alone. # MemAvailable could not absorb them. Disk swapfiles are left alone.
# #
# Env overrides (tests/VM): ZRAM_CONF, ZRAM_WANT_BYTES, ZRAM_SKIP_APPLY=1. # Env overrides (tests/VM): ZRAM_CONF, ZRAM_SIZE_MIB (a smaller device for a
# small guest; default 32768), ZRAM_GENERATOR_BIN, ZRAM_SKIP_APPLY=1, plus
# those in lib/swap_switch.sh.
set -euo pipefail set -euo pipefail
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SRC_DIR readonly SRC_DIR
readonly SS_NAME=setup_zram
readonly ZRAM_CONF="${ZRAM_CONF:-/etc/systemd/zram-generator.conf}" readonly ZRAM_CONF="${ZRAM_CONF:-/etc/systemd/zram-generator.conf}"
readonly ZRAM_WANT_BYTES="${ZRAM_WANT_BYTES:-34359738368}" # 32 GiB readonly ZRAM_SIZE_MIB="${ZRAM_SIZE_MIB:-32768}"
readonly DEV=/dev/zram0 readonly ZRAM_WANT_BYTES=$((ZRAM_SIZE_MIB * 1024 * 1024))
readonly MIN_SPARE_KIB=$((2 * 1024 * 1024)) # keep 2 GiB free after swapoff readonly ZRAM_GENERATOR_BIN="${ZRAM_GENERATOR_BIN:-/usr/lib/systemd/system-generators/zram-generator}"
# shellcheck source=lib/swap_switch.sh
die() { . "${SRC_DIR}/lib/swap_switch.sh"
echo "setup_zram: $*" >&2
exit 1
}
as_root() {
if [[ $EUID -eq 0 ]]; then "$@"; else sudo -n "$@"; fi
}
ensure_package() { ensure_package() {
[[ -x /usr/lib/systemd/system-generators/zram-generator ]] && return 0 [[ -x $ZRAM_GENERATOR_BIN ]] && return 0
as_root pacman -S --needed --noconfirm zram-generator as_root pacman -S --needed --noconfirm zram-generator
} }
disksize() { disksize() {
# sysfs is world-readable; blockdev needs root. Absent device reads as 0. # sysfs is world-readable; blockdev needs root. Absent device reads as 0.
cat /sys/block/zram0/disksize 2>/dev/null || echo 0 cat "${ZRAM_SYSFS}/disksize" 2>/dev/null || echo 0
} }
# KiB of RAM the swapoff will newly occupy: uncompressed data minus the # install_conf — the repo conf, with zram-size swapped for ZRAM_SIZE_MIB
# compressed pages that get freed as it drains. # when that is not the default. Rewrites only when the content differs.
swapoff_cost_kib() { install_conf() {
local line orig total local tmp
line=$(zramctl --bytes --noheadings --raw -o DATA,TOTAL "$DEV") tmp="$(mktemp)"
read -r orig total <<<"$line" sed -E "s/^zram-size = .*/zram-size = ${ZRAM_SIZE_MIB}/" "$SRC_DIR/zram-generator.conf" >"$tmp"
echo $(((orig - total) / 1024)) [[ $ZRAM_SIZE_MIB == 32768 ]] && cp "$SRC_DIR/zram-generator.conf" "$tmp"
} cmp -s "$tmp" "$ZRAM_CONF" || as_root install -D -m 644 "$tmp" "$ZRAM_CONF"
rm -f "$tmp"
mem_available_kib() {
awk '/^MemAvailable:/ {print $2}' /proc/meminfo
} }
resize_live() { resize_live() {
if [[ -b $DEV ]] && swapon --noheadings --show=NAME | grep -qx "$DEV"; then if [[ -b $ZRAM_DEV ]] && ss_zram_active; then
local cost avail ss_can_drain || ss_die "MemAvailable too low to drain zram (needs its contents + 2G spare)"
cost=$(swapoff_cost_kib) as_root swapoff "$ZRAM_DEV"
avail=$(mem_available_kib)
((avail - cost >= MIN_SPARE_KIB)) ||
die "MemAvailable ${avail}K too low to drain zram (needs ${cost}K + 2G spare)"
as_root swapoff "$DEV"
fi fi
# udev probes the freed device after swapoff and holds it open for a moment # udev probes the freed device after swapoff and holds it open for a moment
# ("Device or resource busy" on reset), so settle and retry the restart: # ("Device or resource busy" on reset), so settle and retry the restart:
@ -63,7 +58,7 @@ resize_live() {
for try in 1 2 3 4 5; do for try in 1 2 3 4 5; do
as_root udevadm settle as_root udevadm settle
as_root systemctl restart systemd-zram-setup@zram0.service && break as_root systemctl restart systemd-zram-setup@zram0.service && break
((try < 5)) || die "zram0 stayed busy after 5 resets" ((try < 5)) || ss_die "zram0 stayed busy after 5 resets"
sleep 1 sleep 1
done done
as_root systemctl start dev-zram0.swap 2>/dev/null || true as_root systemctl start dev-zram0.swap 2>/dev/null || true
@ -71,15 +66,18 @@ resize_live() {
main() { main() {
ensure_package ensure_package
as_root install -D -m 644 "$SRC_DIR/zram-generator.conf" "$ZRAM_CONF" ss_set_boot_tokens "zswap.enabled=0"
install_conf
[[ ${ZRAM_SKIP_APPLY:-0} == 1 ]] && return 0 [[ ${ZRAM_SKIP_APPLY:-0} == 1 ]] && return 0
as_root systemctl daemon-reload as_root systemctl daemon-reload
if [[ $(disksize) -ne $ZRAM_WANT_BYTES ]]; then if [[ $(disksize) -ne $ZRAM_WANT_BYTES ]] || ! ss_zram_active; then
resize_live resize_live
fi fi
[[ $(disksize) -eq $ZRAM_WANT_BYTES ]] || die "zram0 is $(disksize) bytes, want $ZRAM_WANT_BYTES" [[ $(disksize) -eq $ZRAM_WANT_BYTES ]] || ss_die "zram0 is $(disksize) bytes, want $ZRAM_WANT_BYTES"
ss_zswap_set enabled N
zramctl zramctl
swapon --show ss_report
} }
main "$@" main "$@"
exit $?

View File

@ -0,0 +1,50 @@
#!/bin/bash
# Switch swap to zswap: compressed RAM cache in front of the disk swapfiles.
#
# Persists zswap.enabled=1, zstd, a 35% pool cap (the RAM budget the 32 GiB
# zram device gets at ~3:1) and the shrinker on the kernel cmdline, removes
# the zram-generator conf, then switches live: swapoff zram0 first, zswap on
# after, so no page is ever compressed twice. When MemAvailable cannot absorb
# what zram holds, it leaves the live state alone and exits 3: reboot to
# apply. resume= stays on /swapfile. setup_zram.sh is the one-command revert.
#
# Env overrides (tests/VM): ZRAM_CONF plus those in lib/swap_switch.sh.
set -euo pipefail
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SRC_DIR
readonly SS_NAME=setup_zswap
readonly ZRAM_CONF="${ZRAM_CONF:-/etc/systemd/zram-generator.conf}"
readonly ZSWAP_TOKENS="zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=35 zswap.shrinker_enabled=1"
# shellcheck source=lib/swap_switch.sh
. "${SRC_DIR}/lib/swap_switch.sh"
# Drop the zram-generator conf so the next boot makes no zram0. The package
# stays installed: setup_zram.sh reinstalls the conf to revert.
disable_zram_conf() {
[[ -e $ZRAM_CONF ]] || return 0
as_root mkdir -p "$SWAP_SWITCH_BACKUP_DIR"
as_root cp -p "$ZRAM_CONF" "${SWAP_SWITCH_BACKUP_DIR}/zram-generator.conf.last"
as_root rm -f "$ZRAM_CONF"
as_root systemctl daemon-reload
}
main() {
ss_has_disk_swap || ss_die "no disk swap is active; zswap needs one to back it"
ss_set_boot_tokens "$ZSWAP_TOKENS"
disable_zram_conf
if ss_zram_active; then
ss_can_drain || ss_reboot_to_apply "zram0 holds more than MemAvailable can absorb"
as_root swapoff "$ZRAM_DEV"
# ExecStop resets the device and frees its memory.
as_root systemctl stop systemd-zram-setup@zram0.service
fi
ss_zswap_set compressor zstd
ss_zswap_set max_pool_percent 35
ss_zswap_set shrinker_enabled Y
ss_zswap_set enabled Y
ss_report
}
main "$@"
exit $?

View File

@ -0,0 +1,13 @@
date env setup seed size_mib pages fill_crc touch_crc seconds ratio psi_some_ms psi_full_ms majflt disk_wb_pages zswpwb global_full_avg10 desktop_full_ms
2026-11-27T10:59:54Z vm zram 20261127 4608 1179648 531769134 2573270970 18.928 3.21 5996 5996 127223 0 0 34.56 na
2026-11-27T11:00:14Z vm zram 20261127 4608 1179648 531769134 2573270970 13.248 3.21 5782 5782 124816 0 0 39.31 na
2026-11-27T11:00:35Z vm zram 20261127 4608 1179648 531769134 2573270970 13.393 3.21 6118 6118 124559 0 0 43.00 na
2026-11-27T11:02:00Z vm zswap 20261127 4608 1179648 531769134 2573270970 28.698 3.15 10366 10360 147757 92 92 38.06 na
2026-11-27T11:02:29Z vm zswap 20261127 4608 1179648 531769134 2573270970 20.711 3.16 8833 8832 210005 128 128 40.12 na
2026-11-27T11:03:04Z vm zswap 20261127 4608 1179648 531769134 2573270970 27.756 3.18 12828 12826 127486 0 0 52.34 na
2026-11-27T11:16:58Z host zram 20261127 6144 1572864 2708526455 3876889511 24.548 2.83 5546 5546 177006 0 0 4.65 14
2026-11-27T11:17:33Z host zram 20261127 6144 1572864 2708526455 3876889511 30.586 2.82 8223 8223 168862 0 0 4.21 1
2026-11-27T11:18:05Z host zram 20261127 6144 1572864 2708526455 3876889511 29.029 3.18 7427 7427 172634 0 0 4.97 0
2026-11-27T11:20:54Z host zswap 20261127 6144 1572864 2708526455 3876889511 49.381 3.21 11684 11684 218408 617001 586700 3.06 6
2026-11-27T11:21:45Z host zswap 20261127 6144 1572864 2708526455 3876889511 45.383 3.21 8973 8973 208093 584944 453067 9.56 29
2026-11-27T11:22:25Z host zswap 20261127 6144 1572864 2708526455 3876889511 35.541 3.21 5490 5490 223518 835213 331649 7.50 13
1 date env setup seed size_mib pages fill_crc touch_crc seconds ratio psi_some_ms psi_full_ms majflt disk_wb_pages zswpwb global_full_avg10 desktop_full_ms
2 2026-11-27T10:59:54Z vm zram 20261127 4608 1179648 531769134 2573270970 18.928 3.21 5996 5996 127223 0 0 34.56 na
3 2026-11-27T11:00:14Z vm zram 20261127 4608 1179648 531769134 2573270970 13.248 3.21 5782 5782 124816 0 0 39.31 na
4 2026-11-27T11:00:35Z vm zram 20261127 4608 1179648 531769134 2573270970 13.393 3.21 6118 6118 124559 0 0 43.00 na
5 2026-11-27T11:02:00Z vm zswap 20261127 4608 1179648 531769134 2573270970 28.698 3.15 10366 10360 147757 92 92 38.06 na
6 2026-11-27T11:02:29Z vm zswap 20261127 4608 1179648 531769134 2573270970 20.711 3.16 8833 8832 210005 128 128 40.12 na
7 2026-11-27T11:03:04Z vm zswap 20261127 4608 1179648 531769134 2573270970 27.756 3.18 12828 12826 127486 0 0 52.34 na
8 2026-11-27T11:16:58Z host zram 20261127 6144 1572864 2708526455 3876889511 24.548 2.83 5546 5546 177006 0 0 4.65 14
9 2026-11-27T11:17:33Z host zram 20261127 6144 1572864 2708526455 3876889511 30.586 2.82 8223 8223 168862 0 0 4.21 1
10 2026-11-27T11:18:05Z host zram 20261127 6144 1572864 2708526455 3876889511 29.029 3.18 7427 7427 172634 0 0 4.97 0
11 2026-11-27T11:20:54Z host zswap 20261127 6144 1572864 2708526455 3876889511 49.381 3.21 11684 11684 218408 617001 586700 3.06 6
12 2026-11-27T11:21:45Z host zswap 20261127 6144 1572864 2708526455 3876889511 45.383 3.21 8973 8973 208093 584944 453067 9.56 29
13 2026-11-27T11:22:25Z host zswap 20261127 6144 1572864 2708526455 3876889511 35.541 3.21 5490 5490 223518 835213 331649 7.50 13

View File

@ -0,0 +1,149 @@
#!/bin/bash
# Seeded memory-pressure benchmark for the zram-vs-zswap A/B test.
#
# swap_bench.sh run host [--seed N] [--size-mib M] # on kuhy's desktop
# swap_bench.sh run vm [--seed N] [--size-mib M] # inside a vmbox guest
# swap_bench.sh summary [TSV] # medians + winner
#
# One run per call, each under 60 s, appending one row to the results TSV.
# Host mode confines the pressure to a transient scope (RAM capped, swap
# allowed), so only the bench swaps and the desktop keeps its memory; its
# PSI and zswap counters are the scope's own. VM mode puts the whole guest
# under pressure and uses global counters. A run that fails or times out
# records nothing. The Python side (python_pkg/swap_bench) holds the
# workload, the parsing and the winner rule; this script only places it.
# Method and results: DOCS-zswap-vs-zram.md.
set -euo pipefail
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SRC_DIR}/../.." && pwd)"
readonly SRC_DIR REPO_ROOT
readonly RESULTS="${SWAP_BENCH_RESULTS:-${SRC_DIR}/swap-bench-results.tsv}"
readonly PROC_VMSTAT="${PROC_VMSTAT:-/proc/vmstat}"
readonly PROC_PRESSURE="${PROC_PRESSURE:-/proc/pressure/memory}"
readonly PROC_MEMINFO="${PROC_MEMINFO:-/proc/meminfo}"
readonly PROC_SELF_CGROUP="${PROC_SELF_CGROUP:-/proc/self/cgroup}"
readonly CGROUP_ROOT="${CGROUP_ROOT:-/sys/fs/cgroup}"
readonly ZRAM_SYSFS="${ZRAM_SYSFS:-/sys/block/zram0}"
readonly ZSWAP_PARAMS_DIR="${ZSWAP_PARAMS_DIR:-/sys/module/zswap/parameters}"
readonly HOST_MEMORY_MAX="${SWAP_BENCH_MEMORY_MAX:-4G}"
# A wrapper on PATH may add properties a scope refuses (Nice=); point this at
# /usr/bin/systemd-run to bypass it.
readonly SYSTEMD_RUN="${SWAP_BENCH_SYSTEMD_RUN:-systemd-run}"
readonly DEFAULT_SEED=20261127
readonly DEFAULT_HOST_MIB=6144
readonly DEFAULT_VM_MIB=4608
readonly WORKLOAD_TIMEOUT=50 # scope RuntimeMaxSec=55 is the backstop
die() {
echo "swap_bench: $*" >&2
exit 1
}
usage() {
sed -n '4,6s/^# \{0,1\}//p' "${BASH_SOURCE[0]}" >&2
exit 2
}
py() { PYTHONPATH="$REPO_ROOT" python3 -m python_pkg.swap_bench "$@"; }
detect_setup() {
local zram=0 zswap=0
swapon --noheadings --show=NAME | grep -qx /dev/zram0 && zram=1
[[ $(cat "${ZSWAP_PARAMS_DIR}/enabled") == Y ]] && zswap=1
((zram && zswap)) && die "zram0 is swap AND zswap is on: pages are compressed twice; run setup_zram.sh or setup_zswap.sh"
((zram)) && echo zram && return 0
((zswap)) && echo zswap && return 0
die "neither zram nor zswap is active"
}
# snap DIR — copy the global counters one run is measured against, plus
# the PSI of every login session scope: that is the desktop (i3 and what it
# launched), which the host bench scope is not part of.
snap() {
mkdir -p "$1"
cp "$PROC_VMSTAT" "$1/vmstat"
cp "$PROC_PRESSURE" "$1/pressure"
local -a sessions=("${CGROUP_ROOT}"/user.slice/user-*.slice/session-*.scope/memory.pressure)
[[ -e ${sessions[0]} ]] && cat "${sessions[@]}" >"$1/desktop_pressure"
if [[ -e ${ZRAM_SYSFS}/mm_stat ]]; then
cp "${ZRAM_SYSFS}/mm_stat" "$1/mm_stat"
cp "${ZRAM_SYSFS}/stat" "$1/zram_stat"
fi
}
# host_has_room — 0 when MemAvailable covers the scope's RAM cap plus 2 GiB,
# so pressing the scope cannot push the desktop itself into swap.
host_has_room() {
local cap_kib avail_kib
cap_kib=$(($(numfmt --from=iec "$HOST_MEMORY_MAX") / 1024))
avail_kib=$(awk '/^MemAvailable:/ {print $2}' "$PROC_MEMINFO")
((avail_kib >= cap_kib + 2 * 1024 * 1024))
}
global_full_avg10() { awk '/^full/ {sub("avg10=", "", $2); print $2}' "$PROC_PRESSURE"; }
# inner DIR ENV SIZE SEED — runs inside the scope (host) or the guest (vm).
inner() {
local dir="$1" env="$2" size="$3" seed="$4" cg
cg="${CGROUP_ROOT}$(sed -n 's/^0:://p' "$PROC_SELF_CGROUP")"
local -a snaps=(--snapshot "${PROC_MEMINFO}=${dir}/peak/meminfo")
[[ $env == host ]] && snaps+=(--snapshot "${cg}/memory.stat=${dir}/peak/memory.stat")
[[ -e ${ZRAM_SYSFS}/mm_stat ]] && snaps+=(--snapshot "${ZRAM_SYSFS}/mm_stat=${dir}/peak/mm_stat")
timeout "$WORKLOAD_TIMEOUT" env PYTHONPATH="$REPO_ROOT" python3 -m python_pkg.swap_bench \
run --size-mib "$size" --seed "$seed" "${snaps[@]}" >"${dir}/workload.txt"
if [[ $env == host ]]; then
cp "${cg}/memory.pressure" "${dir}/cg_pressure"
cp "${cg}/memory.stat" "${dir}/cg_memory.stat"
fi
}
cmd_run() {
local env="${1:-}" seed="$DEFAULT_SEED" size=""
[[ $env == host || $env == vm ]] || usage
shift
while (($#)); do
case "$1" in
--seed) seed="$2" ;;
--size-mib) size="$2" ;;
*) usage ;;
esac
shift 2
done
[[ -n $size ]] || { [[ $env == host ]] && size=$DEFAULT_HOST_MIB || size=$DEFAULT_VM_MIB; }
local setup dir rc=0
setup="$(detect_setup)"
[[ $env == vm ]] || host_has_room ||
die "MemAvailable is below ${HOST_MEMORY_MAX} + 2G: a host run now would press the desktop too"
dir="$(mktemp -d)"
RUN_DIR="$dir" # global: the EXIT trap runs after this function's locals are gone
trap 'rm -rf "${RUN_DIR:?}"' EXIT
echo "global memory PSI full avg10 before: $(global_full_avg10)"
snap "${dir}/before"
if [[ $env == host ]]; then
"$SYSTEMD_RUN" --user --scope --quiet --unit="swap-bench-$$" \
-p MemoryMax="$HOST_MEMORY_MAX" -p MemorySwapMax=infinity -p RuntimeMaxSec=55 \
-- bash "${BASH_SOURCE[0]}" _inner "$dir" "$env" "$size" "$seed" || rc=$?
else
bash "${BASH_SOURCE[0]}" _inner "$dir" "$env" "$size" "$seed" || rc=$?
fi
((rc == 0)) || die "workload failed (exit $rc): no row recorded"
snap "${dir}/after"
echo "global memory PSI full avg10 after: $(global_full_avg10)"
local -a header=()
[[ -s $RESULTS ]] || header=(--header)
py row --dir "$dir" --env "$env" --setup "$setup" --seed "$seed" --size-mib "$size" \
--date "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${header[@]}" | tee -a "$RESULTS"
}
main() {
case "${1:-}" in
run) cmd_run "${@:2}" ;;
summary) py summary "${2:-$RESULTS}" ;;
_inner) inner "${@:2}" ;;
*) usage ;;
esac
}
main "$@"
exit $?

View File

@ -0,0 +1,5 @@
"""Seeded memory-pressure workload for the zswap-vs-zram A/B test.
Driven by ``linux_configuration/fixes/swap_bench.sh``; see
``linux_configuration/fixes/DOCS-zswap-vs-zram.md`` for the method.
"""

View File

@ -0,0 +1,9 @@
"""``python -m python_pkg.swap_bench`` entry point."""
from __future__ import annotations
import sys
from python_pkg.swap_bench import cli
sys.exit(cli.main())

View File

@ -0,0 +1,84 @@
"""``python -m python_pkg.swap_bench run|row|summary`` for swap_bench.sh."""
from __future__ import annotations
import argparse
from pathlib import Path
import sys
from python_pkg.swap_bench.stats import compute_row, format_row
from python_pkg.swap_bench.summary import summarize
from python_pkg.swap_bench.workload import Spec, run
def _snapshot(text: str) -> tuple[Path, Path]:
src, sep, dest = text.partition("=")
if not sep:
msg = f"--snapshot wants SRC=DEST, got {text!r}"
raise argparse.ArgumentTypeError(msg)
return Path(src), Path(dest)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="swap_bench")
sub = parser.add_subparsers(dest="cmd", required=True)
p_run = sub.add_parser("run", help="run the seeded workload once")
p_run.add_argument("--size-mib", type=int, required=True)
p_run.add_argument("--seed", type=int, required=True)
p_run.add_argument("--rounds", type=int, default=3)
p_run.add_argument("--hot-share", type=float, default=0.25)
p_run.add_argument("--snapshot", type=_snapshot, action="append", default=[])
p_row = sub.add_parser("row", help="print one TSV row for a run directory")
p_row.add_argument("--dir", type=Path, required=True)
p_row.add_argument("--env", required=True)
p_row.add_argument("--setup", required=True)
p_row.add_argument("--seed", type=int, required=True)
p_row.add_argument("--size-mib", type=int, required=True)
p_row.add_argument("--date", required=True)
p_row.add_argument("--header", action="store_true", help="print the header first")
p_sum = sub.add_parser("summary", help="medians and the winner for a TSV")
p_sum.add_argument("tsv", type=Path)
return parser
def _cmd_run(args: argparse.Namespace) -> int:
try:
spec = Spec(
size_mib=args.size_mib,
seed=args.seed,
rounds=args.rounds,
hot_share=args.hot_share,
)
except ValueError as exc:
sys.stderr.write(f"swap_bench: {exc}\n")
return 2
result = run(spec, args.snapshot)
for field in ("pages", "fill_crc", "touch_crc", "majflt", "seconds"):
sys.stdout.write(f"{field}={getattr(result, field)}\n")
return 0
def _cmd_row(args: argparse.Namespace) -> int:
row = compute_row(
args.dir,
env=args.env,
setup=args.setup,
seed=args.seed,
size_mib=args.size_mib,
date=args.date,
)
if args.header:
sys.stdout.write(format_row(None) + "\n")
sys.stdout.write(format_row(row) + "\n")
return 0
def main(argv: list[str] | None = None) -> int:
"""Dispatch a subcommand; return its exit code."""
args = _parser().parse_args(argv)
if args.cmd == "run":
return _cmd_run(args)
if args.cmd == "row":
return _cmd_row(args)
sys.stdout.write(summarize(args.tsv))
return 0

View File

@ -0,0 +1,23 @@
"""Deterministic byte and integer streams from a seed.
``random.Random`` would do, but the repo's lint (S311) refuses it outright;
SHAKE-256 gives the same reproducibility, in bulk, from the standard library.
Every stream is named by a label, so adding a stream never shifts another.
"""
from __future__ import annotations
import array
import hashlib
def stream_bytes(seed: int, label: str, n: int) -> bytes:
"""Return ``n`` bytes fixed by ``seed`` and ``label``."""
return hashlib.shake_256(f"{seed}/{label}".encode()).digest(n)
def stream_u32(seed: int, label: str, n: int) -> array.array[int]:
"""Return ``n`` unsigned 32-bit ints fixed by ``seed`` and ``label``."""
out = array.array("I") # 4 bytes on every Linux target this runs on
out.frombytes(stream_bytes(seed, label, n * out.itemsize))
return out

View File

@ -0,0 +1,159 @@
"""Turn the raw files of one swap_bench.sh run into one TSV row.
swap_bench.sh copies /proc and /sys files into a run directory:
- ``before/`` and ``after/``: vmstat, pressure (global PSI), zram_stat and
mm_stat (absent without zram), desktop_pressure (every login session
scope's PSI, concatenated);
- ``peak/``: mm_stat, meminfo and the scope's memory.stat, copied by the
workload while its mapping is still live;
- ``cg_pressure`` and ``cg_memory.stat``: the scope's totals at exit;
- ``workload.txt``: the workload's ``key=value`` output.
On the host the scope's own counters are used (the desktop keeps running);
in a VM the whole guest is the experiment, so global deltas are used.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
COLUMNS = (
"date",
"env",
"setup",
"seed",
"size_mib",
"pages",
"fill_crc",
"touch_crc",
"seconds",
"ratio",
"psi_some_ms",
"psi_full_ms",
"majflt",
"disk_wb_pages",
"zswpwb",
"global_full_avg10",
"desktop_full_ms",
)
_SECTOR_PER_PAGE = 8 # 512-byte sectors in a 4 KiB page
def _read(path: Path) -> str:
return path.read_text() if path.exists() else ""
def _kv(path: Path, sep: str | None = None) -> dict[str, int]:
"""Parse ``key value`` (or ``key: value kB``) lines into ints."""
out: dict[str, int] = {}
for line in _read(path).splitlines():
key, _, rest = line.partition(":") if sep else line.partition(" ")
out[key.strip()] = int(rest.split()[0])
return out
def _fields(path: Path) -> list[int]:
return [int(x) for x in _read(path).split()]
def _psi(path: Path) -> dict[str, dict[str, float]]:
"""Parse a PSI file into ``{"some": {...}, "full": {...}}``."""
out: dict[str, dict[str, float]] = {}
for line in _read(path).splitlines():
kind, *pairs = line.split()
out[kind] = {k: float(v) for k, v in (p.split("=") for p in pairs)}
return out
def _full_total(path: Path) -> float:
"""Sum the ``full`` stall totals of a file holding several PSI files."""
return sum(
float(line.split("total=")[1])
for line in _read(path).splitlines()
if line.startswith("full")
)
def _desktop_full_ms(run: Path, env: str) -> str:
"""Stall the login sessions saw; ``na`` in a VM, whose bench runs in one."""
if env != "host" or not (run / "before/desktop_pressure").exists():
return "na"
delta = _full_total(run / "after/desktop_pressure") - _full_total(
run / "before/desktop_pressure"
)
return str(round(delta / 1000))
def _ratio(stored_in: float, stored_out: float) -> str:
return f"{stored_in / stored_out:.2f}" if stored_out > 0 else "na"
def _zram_delta(run: Path, a: str, b: str, index: int) -> int:
first, last = _fields(run / a), _fields(run / b)
return last[index] - first[index] if first and last else 0
def _compute_ratio(run: Path, env: str, setup: str) -> str:
if setup == "zram":
return _ratio(
_zram_delta(run, "before/mm_stat", "peak/mm_stat", 0),
_zram_delta(run, "before/mm_stat", "peak/mm_stat", 1),
)
if env == "host":
cg = _kv(run / "peak/memory.stat")
return _ratio(cg.get("zswapped", 0), cg.get("zswap", 0))
mem = _kv(run / "peak/meminfo", sep=":")
return _ratio(mem.get("Zswapped", 0), mem.get("Zswap", 0))
def compute_row(
run: Path, *, env: str, setup: str, seed: int, size_mib: int, date: str
) -> dict[str, str]:
"""Return one result row (all values as strings) for run directory ``run``."""
if env not in {"host", "vm"}:
msg = f"env must be host or vm, got {env!r}"
raise ValueError(msg)
work = dict(line.split("=", 1) for line in _read(run / "workload.txt").split())
before, after = _kv(run / "before/vmstat"), _kv(run / "after/vmstat")
zram_pages = (
_zram_delta(run, "before/zram_stat", "after/zram_stat", 6) // _SECTOR_PER_PAGE
)
disk_wb = max(0, after["pswpout"] - before["pswpout"] - zram_pages)
if env == "host":
psi = _psi(run / "cg_pressure")
some, full = psi["some"]["total"], psi["full"]["total"]
zswpwb = _kv(run / "cg_memory.stat").get("zswpwb", 0)
else:
g0, g1 = _psi(run / "before/pressure"), _psi(run / "after/pressure")
some = g1["some"]["total"] - g0["some"]["total"]
full = g1["full"]["total"] - g0["full"]["total"]
zswpwb = after.get("zswpwb", 0) - before.get("zswpwb", 0)
values = {
"date": date,
"env": env,
"setup": setup,
"seed": str(seed),
"size_mib": str(size_mib),
"pages": work["pages"],
"fill_crc": work["fill_crc"],
"touch_crc": work["touch_crc"],
"seconds": work["seconds"],
"ratio": _compute_ratio(run, env, setup),
"psi_some_ms": str(round(some / 1000)),
"psi_full_ms": str(round(full / 1000)),
"majflt": work["majflt"],
"disk_wb_pages": str(disk_wb),
"zswpwb": str(zswpwb),
"global_full_avg10": f"{_psi(run / 'after/pressure')['full']['avg10']:.2f}",
"desktop_full_ms": _desktop_full_ms(run, env),
}
return {c: values[c] for c in COLUMNS}
def format_row(row: dict[str, str] | None) -> str:
"""Tab-join a row in column order; ``None`` gives the header line."""
return "\t".join(COLUMNS if row is None else (row[c] for c in COLUMNS))

View File

@ -0,0 +1,69 @@
"""Per-setup medians of a results TSV and the agreed winner rule.
Rule (kuhy, 2026-11-27): lower PSI ``full`` wins; major faults break a tie;
a difference under 10 % (the run-to-run noise) is a tie, and a tie on both
keeps zram, the incumbent.
"""
from __future__ import annotations
import csv
from statistics import median
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
NOISE = 0.10
_METRICS = ("ratio", "psi_some_ms", "psi_full_ms", "majflt", "disk_wb_pages", "zswpwb")
def _differs(a: float, b: float) -> bool:
top = max(a, b)
return top > 0 and abs(a - b) / top >= NOISE
def pick_winner(zram: dict[str, float], zswap: dict[str, float]) -> tuple[str, str]:
"""Return ``(winner, reason)`` from the two setups' medians."""
for key, label in (("psi_full_ms", "PSI full"), ("majflt", "major faults")):
if _differs(zram[key], zswap[key]):
winner = "zram" if zram[key] < zswap[key] else "zswap"
return (
winner,
f"lower median {label} ({zram[key]:g} zram vs {zswap[key]:g} zswap)",
)
return "zram", "PSI full and major faults within 10 %: the incumbent stays"
def _medians(rows: list[dict[str, str]]) -> dict[str, float]:
out: dict[str, float] = {}
for key in _METRICS:
values = [float(r[key]) for r in rows if r[key] != "na"]
out[key] = median(values) if values else float("nan")
return out
def summarize(path: Path) -> str:
"""Markdown table of medians per env and setup, then one winner line per env."""
with path.open(newline="") as fh:
rows = list(csv.DictReader(fh, delimiter="\t"))
groups: dict[tuple[str, str], list[dict[str, str]]] = {}
for row in rows:
groups.setdefault((row["env"], row["setup"]), []).append(row)
titles = ("env", "setup", "runs", "ratio", "PSI some ms", "PSI full ms")
titles += ("major faults", "disk writeback pages", "zswap writeback")
lines = ["| " + " | ".join(titles) + " |", "|---" * len(titles) + "|"]
medians: dict[tuple[str, str], dict[str, float]] = {}
for (env, setup), members in sorted(groups.items()):
med = medians[env, setup] = _medians(members)
cells = [env, setup, str(len(members)), f"{med['ratio']:.2f}"]
cells += [f"{med[key]:g}" for key in _METRICS[1:]]
lines.append("| " + " | ".join(cells) + " |")
lines.append("")
for env in sorted({env for env, _ in groups}):
if (env, "zram") in medians and (env, "zswap") in medians:
winner, reason = pick_winner(medians[env, "zram"], medians[env, "zswap"])
lines.append(f"{env} winner: {winner}: {reason}")
else:
lines.append(f"{env} winner: n/a (needs runs of both setups)")
return "\n".join(lines) + "\n"

View File

@ -0,0 +1 @@
"""Tests for the swap_bench subpackage."""

View File

@ -0,0 +1,61 @@
"""Fixture trees of the raw files swap_bench.sh copies for one run."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from pathlib import Path
_PSI = (
"some avg10=0.00 avg60=0.00 avg300=0.00 total={some}\n"
"full avg10={f10} avg60=0.00 avg300=0.00 total={full}\n"
)
def _write(root: Path, name: str, text: str) -> None:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
@pytest.fixture
def run_dir(tmp_path: Path) -> Path:
"""A zram run: 3 GiB in, 1 GiB compressed, 800 pages to disk."""
gib = 1 << 30
_write(
tmp_path,
"workload.txt",
"pages=256\nfill_crc=11\ntouch_crc=22\nmajflt=500\nseconds=12.5\n",
)
_write(tmp_path, "before/vmstat", "pswpout 1000\nzswpwb 5\npgmajfault 9\n")
_write(tmp_path, "after/vmstat", "pswpout 9000\nzswpwb 7\npgmajfault 9\n")
_write(tmp_path, "before/zram_stat", "1 0 0 0 1 0 8000 0 0 0 0\n")
_write(tmp_path, "after/zram_stat", "1 0 0 0 1 0 65600 0 0 0 0\n")
_write(tmp_path, "before/mm_stat", f"{gib} {gib // 2} 0 0\n")
_write(tmp_path, "peak/mm_stat", f"{4 * gib} {gib + gib // 2} 0 0\n")
_write(tmp_path, "before/pressure", _PSI.format(some=1000, full=500, f10="0.10"))
_write(
tmp_path, "after/pressure", _PSI.format(some=301000, full=200500, f10="0.20")
)
_write(
tmp_path,
"before/desktop_pressure",
2 * _PSI.format(some=0, full=1000, f10="0.00"),
)
_write(
tmp_path,
"after/desktop_pressure",
2 * _PSI.format(some=0, full=4000, f10="0.00"),
)
_write(tmp_path, "cg_pressure", _PSI.format(some=40000, full=30000, f10="1.00"))
_write(tmp_path, "cg_memory.stat", "zswpwb 3\nzswap 100\nzswapped 400\n")
_write(tmp_path, "peak/memory.stat", "zswap 1000\nzswapped 3500\n")
_write(
tmp_path,
"peak/meminfo",
"MemTotal: 100 kB\nZswap: 200 kB\nZswapped: 500 kB\n",
)
return tmp_path

View File

@ -0,0 +1,91 @@
"""Tests for the swap_bench command line."""
from __future__ import annotations
import runpy
from typing import TYPE_CHECKING
import pytest
from python_pkg.swap_bench import cli
from python_pkg.swap_bench.stats import COLUMNS
if TYPE_CHECKING:
from pathlib import Path
def _out(capsys: pytest.CaptureFixture[str]) -> str:
return capsys.readouterr().out
def test_run_prints_key_value_lines(
capsys: pytest.CaptureFixture[str], tmp_path: Path
) -> None:
"""``run`` prints one key=value line per result field."""
src = tmp_path / "s"
src.write_text("x")
argv = [
"run",
"--size-mib",
"1",
"--seed",
"5",
"--rounds",
"1",
"--snapshot",
f"{src}={tmp_path / 'd'}",
]
assert cli.main(argv) == 0
lines = dict(line.split("=", 1) for line in _out(capsys).splitlines())
assert lines["pages"] == "256"
assert set(lines) == {"pages", "fill_crc", "touch_crc", "majflt", "seconds"}
assert (tmp_path / "d").read_text() == "x"
def test_run_rejects_bad_spec(capsys: pytest.CaptureFixture[str]) -> None:
"""A bad spec exits 2 with the reason on stderr."""
assert cli.main(["run", "--size-mib", "0", "--seed", "5"]) == 2
assert "size_mib" in capsys.readouterr().err
def test_run_rejects_bad_snapshot() -> None:
"""A snapshot without ``=`` is a usage error."""
with pytest.raises(SystemExit):
cli.main(["run", "--size-mib", "1", "--seed", "1", "--snapshot", "nope"])
def test_row_with_and_without_header(
capsys: pytest.CaptureFixture[str], run_dir: Path
) -> None:
"""``row`` prints the TSV row, optionally after the header."""
base = ["row", "--dir", str(run_dir), "--env", "host", "--setup", "zram"]
base += ["--seed", "1", "--size-mib", "1", "--date", "d"]
assert cli.main([*base, "--header"]) == 0
header, row = _out(capsys).splitlines()
assert header.split("\t") == list(COLUMNS)
assert row.startswith("d\thost\tzram\t")
assert cli.main(base) == 0
assert len(_out(capsys).splitlines()) == 1
def test_summary(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None:
"""``summary`` prints the medians table."""
path = tmp_path / "r.tsv"
path.write_text("\t".join(COLUMNS) + "\n")
assert cli.main(["summary", str(path)]) == 0
assert "| env | setup |" in _out(capsys)
def test_module_entry_point(monkeypatch: pytest.MonkeyPatch) -> None:
"""``python -m python_pkg.swap_bench`` delegates to cli.main."""
calls: list[int] = []
def fake_main() -> int:
calls.append(1)
return 0
monkeypatch.setattr(cli, "main", fake_main)
with pytest.raises(SystemExit) as exc:
runpy.run_module("python_pkg.swap_bench", run_name="__main__")
assert exc.value.code == 0
assert calls == [1]

View File

@ -0,0 +1,20 @@
"""Tests for the SHAKE-256 seeded streams."""
from __future__ import annotations
from python_pkg.swap_bench.seeded import stream_bytes, stream_u32
def test_streams_are_fixed_by_seed_and_label() -> None:
"""Same seed and label repeat; a different seed or label differs."""
assert stream_bytes(1, "a", 16) == stream_bytes(1, "a", 16)
assert stream_bytes(1, "a", 16) != stream_bytes(2, "a", 16)
assert stream_bytes(1, "a", 16) != stream_bytes(1, "b", 16)
def test_u32_stream_length_and_range() -> None:
"""``stream_u32`` returns n values below 2**32."""
values = stream_u32(3, "x", 100)
assert len(values) == 100
assert all(0 <= v < 1 << 32 for v in values)
assert len(set(values)) > 90

View File

@ -0,0 +1,86 @@
"""Tests for turning one run's raw /proc and /sys copies into a TSV row."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from python_pkg.swap_bench.stats import COLUMNS, compute_row, format_row
if TYPE_CHECKING:
from pathlib import Path
def _row(run_dir: Path, env: str, setup: str) -> dict[str, str]:
return compute_row(run_dir, env=env, setup=setup, seed=1, size_mib=1, date="d")
def test_zram_host_row(run_dir: Path) -> None:
"""Host zram: scope PSI, per-run mm_stat ratio, zram writes not disk."""
row = _row(run_dir, "host", "zram")
assert row["ratio"] == "3.00" # (4-1) GiB in over (1.5-0.5) GiB stored
assert row["psi_some_ms"] == "40"
assert row["psi_full_ms"] == "30"
assert row["majflt"] == "500"
# 8000 pswpout pages minus (65600-8000)/8 = 7200 zram pages.
assert row["disk_wb_pages"] == "800"
assert row["zswpwb"] == "3"
assert row["global_full_avg10"] == "0.20"
assert row["pages"] == "256"
assert row["desktop_full_ms"] == "6" # two sessions, 3000 us each
assert list(row) == list(COLUMNS)
def test_zswap_host_ratio_from_cgroup(run_dir: Path) -> None:
"""Host zswap: ratio from the scope's zswapped/zswap at peak."""
assert _row(run_dir, "host", "zswap")["ratio"] == "3.50"
def test_vm_rows_are_system_wide(run_dir: Path) -> None:
"""VM: global PSI and zswpwb deltas, ratio from /proc/meminfo."""
row = _row(run_dir, "vm", "zswap")
assert row["psi_some_ms"] == "300"
assert row["psi_full_ms"] == "200"
assert row["zswpwb"] == "2"
assert row["ratio"] == "2.50"
assert row["desktop_full_ms"] == "na"
def test_host_without_sessions_has_no_desktop_psi(run_dir: Path) -> None:
"""No login session scope (a headless host) gives na, not zero."""
(run_dir / "before/desktop_pressure").unlink()
assert _row(run_dir, "host", "zram")["desktop_full_ms"] == "na"
def test_missing_zram_files_mean_no_zram(run_dir: Path) -> None:
"""Without zram stats, every pswpout page counts as disk writeback."""
for name in (
"before/zram_stat",
"after/zram_stat",
"before/mm_stat",
"peak/mm_stat",
):
(run_dir / name).unlink()
row = _row(run_dir, "vm", "zram")
assert row["disk_wb_pages"] == "8000"
assert row["ratio"] == "na"
def test_zero_pool_ratio_is_na(run_dir: Path) -> None:
"""A run that never reached the pool has no ratio, not a crash."""
(run_dir / "peak/meminfo").write_text("Zswap: 0 kB\nZswapped: 0 kB\n")
assert _row(run_dir, "vm", "zswap")["ratio"] == "na"
def test_bad_env_is_refused(run_dir: Path) -> None:
"""Only host and vm exist."""
with pytest.raises(ValueError, match="env"):
_row(run_dir, "cloud", "zram")
def test_format_row_is_tab_separated(run_dir: Path) -> None:
"""format_row joins the columns in order with tabs."""
row = _row(run_dir, "host", "zram")
assert format_row(row) == "\t".join(row[c] for c in COLUMNS)
assert format_row(None) == "\t".join(COLUMNS)

View File

@ -0,0 +1,84 @@
"""Tests for the per-setup medians and the agreed winner rule."""
from __future__ import annotations
from typing import TYPE_CHECKING
from python_pkg.swap_bench.stats import COLUMNS
from python_pkg.swap_bench.summary import pick_winner, summarize
if TYPE_CHECKING:
from pathlib import Path
def _tsv(tmp_path: Path, rows: list[tuple[str, str, str, str, str]]) -> Path:
"""Rows of (env, setup, psi_full_ms, majflt, ratio)."""
lines = ["\t".join(COLUMNS)]
for env, setup, full, majflt, ratio in rows:
row = dict.fromkeys(COLUMNS, "0")
row.update(env=env, setup=setup, psi_full_ms=full, majflt=majflt, ratio=ratio)
lines.append("\t".join(row[c] for c in COLUMNS))
path = tmp_path / "r.tsv"
path.write_text("\n".join(lines) + "\n")
return path
def test_lower_psi_full_wins() -> None:
"""PSI full decides when it differs by 10% or more."""
assert (
pick_winner(
{"psi_full_ms": 100, "majflt": 1}, {"psi_full_ms": 50, "majflt": 9}
)[0]
== "zswap"
)
assert (
pick_winner(
{"psi_full_ms": 50, "majflt": 9}, {"psi_full_ms": 100, "majflt": 1}
)[0]
== "zram"
)
def test_majflt_breaks_a_psi_tie() -> None:
"""Under 10% PSI difference, major faults decide."""
winner, reason = pick_winner(
{"psi_full_ms": 100, "majflt": 1000}, {"psi_full_ms": 95, "majflt": 500}
)
assert winner == "zswap"
assert "major faults" in reason
def test_double_tie_keeps_zram() -> None:
"""Under 10% on both, the incumbent zram stays."""
winner, reason = pick_winner(
{"psi_full_ms": 100, "majflt": 100}, {"psi_full_ms": 95, "majflt": 95}
)
assert winner == "zram"
assert "incumbent" in reason
def test_zero_values_tie() -> None:
"""Both zero is a tie, not a division by zero."""
assert (
pick_winner({"psi_full_ms": 0, "majflt": 0}, {"psi_full_ms": 0, "majflt": 0})[0]
== "zram"
)
def test_summarize_medians_and_winner(tmp_path: Path) -> None:
"""Medians per env and setup, a winner line per env with both setups."""
path = _tsv(
tmp_path,
[
("host", "zram", "100", "10", "3.00"),
("host", "zram", "300", "30", "3.20"),
("host", "zram", "200", "20", "na"),
("host", "zswap", "50", "10", "3.50"),
("vm", "zram", "10", "1", "3.00"),
],
)
text = summarize(path)
assert "| host | zram | 3 | 3.10 |" in text
assert "| 200 |" in text
assert "host winner: zswap" in text
assert "vm winner: n/a (needs runs of both setups)" in text

View File

@ -0,0 +1,78 @@
"""Tests for the seeded swap-pressure workload.
Sizes stay at a few MiB: the anonymous mapping is real memory, but far too
small to push anything into swap, so the tests check determinism and the
output contract, not kernel behaviour.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from python_pkg.swap_bench.workload import PAGE, Spec, build_pool, run
if TYPE_CHECKING:
from pathlib import Path
def test_pool_is_seeded_and_page_sized() -> None:
"""Same seed gives the same pool; every template is one page."""
a = build_pool(seed=7, pool_pages=64, random_share=0.25)
b = build_pool(seed=7, pool_pages=64, random_share=0.25)
assert a == b
assert len(a) == 64
assert all(len(p) == PAGE for p in a)
assert build_pool(seed=8, pool_pages=64, random_share=0.25) != a
def test_pool_random_share_controls_random_pages() -> None:
"""random_share=0 yields only text pages; 1 yields only random ones."""
text = build_pool(seed=1, pool_pages=16, random_share=0.0)
assert all(p.rstrip(b" ").replace(b" ", b"").isalpha() for p in text)
rand = build_pool(seed=1, pool_pages=16, random_share=1.0)
assert not any(p.replace(b" ", b"").isalpha() for p in rand)
def test_run_is_deterministic() -> None:
"""Two runs with one spec report identical pages and checksums (C7)."""
spec = Spec(size_mib=2, seed=42, pool_pages=32, rounds=2)
first, second = run(spec), run(spec)
assert first.pages == second.pages == 2 * 256
assert first.fill_crc == second.fill_crc
assert first.touch_crc == second.touch_crc
assert first.majflt >= 0
assert first.seconds >= 0
def test_run_seed_changes_checksum() -> None:
"""A different seed is a different workload."""
a = run(Spec(size_mib=1, seed=1, pool_pages=16, rounds=1))
b = run(Spec(size_mib=1, seed=2, pool_pages=16, rounds=1))
assert a.fill_crc != b.fill_crc
def test_run_handles_partial_last_chunk() -> None:
"""A page count that is not a chunk multiple is still filled fully."""
spec = Spec(size_mib=1, seed=3, pool_pages=8, rounds=1, chunk_pages=100)
assert run(spec).pages == 256
def test_spec_rejects_bad_values() -> None:
"""Non-positive sizes and shares outside [0, 1] are refused."""
with pytest.raises(ValueError, match="size_mib"):
Spec(size_mib=0, seed=1)
with pytest.raises(ValueError, match="hot_share"):
Spec(size_mib=1, seed=1, hot_share=1.5)
with pytest.raises(ValueError, match="random_share"):
Spec(size_mib=1, seed=1, random_share=-0.1)
def test_run_copies_snapshots_while_mapped(tmp_path: Path) -> None:
"""Snapshots are copied during the run, creating the destination dir."""
src = tmp_path / "src"
src.write_text("zswap 7\n")
dest = tmp_path / "peak" / "memory.stat"
run(Spec(size_mib=1, seed=1, pool_pages=8, rounds=1), [(src, dest)])
assert dest.read_text() == "zswap 7\n"

View File

@ -0,0 +1,146 @@
"""Fill anonymous memory with seeded pages, then re-touch a hot subset.
Every byte depends on the seed alone (no file contents, no clock), so the
same seed is the same workload on the host and in a guest, on any day. The
page mix compresses about 3.4:1 under zstd: Zipf-weighted text from a
64-word seeded vocabulary, plus a share of incompressible random pages.
"""
from __future__ import annotations
from bisect import bisect
from dataclasses import dataclass
from itertools import accumulate
import mmap
import resource
import string
import time
from typing import TYPE_CHECKING
import zlib
from python_pkg.swap_bench.seeded import stream_bytes, stream_u32
if TYPE_CHECKING:
from collections.abc import Sequence
from pathlib import Path
PAGE = 4096
_VOCAB_WORDS = 64
_WORDS_PER_PAGE = 900 # comfortably more than one page of text
_U32 = 1 << 32
@dataclass(frozen=True)
class Spec:
"""One workload: how much memory, which seed, how hot the re-touch is."""
size_mib: int
seed: int
random_share: float = 0.05
hot_share: float = 0.25
rounds: int = 3
pool_pages: int = 1024
chunk_pages: int = 64
def __post_init__(self) -> None:
"""Refuse specs that would make an empty or undefined workload."""
for name in ("size_mib", "rounds", "pool_pages", "chunk_pages"):
if getattr(self, name) <= 0:
msg = f"{name} must be positive"
raise ValueError(msg)
for name in ("random_share", "hot_share"):
if not 0.0 <= getattr(self, name) <= 1.0:
msg = f"{name} must be within [0, 1]"
raise ValueError(msg)
@dataclass(frozen=True)
class Result:
"""What one run did; identical across runs of one spec except timing."""
pages: int
fill_crc: int
touch_crc: int
majflt: int
seconds: float
def build_pool(seed: int, pool_pages: int, random_share: float) -> list[bytes]:
"""Return ``pool_pages`` seeded page templates, ``random_share`` random."""
lengths = stream_u32(seed, "word-length", _VOCAB_WORDS)
letters = stream_bytes(seed, "word-letters", _VOCAB_WORDS * 10)
vocab = [
"".join(
string.ascii_lowercase[c % 26]
for c in letters[w * 10 : w * 10 + 3 + lengths[w] % 8]
)
for w in range(_VOCAB_WORDS)
]
cumulative = list(accumulate(1 / (rank + 1) for rank in range(_VOCAB_WORDS)))
scale = cumulative[-1] / _U32
n_random = round(pool_pages * random_share)
pool = [stream_bytes(seed, f"random-page-{i}", PAGE) for i in range(n_random)]
for i in range(pool_pages - n_random):
draws = stream_u32(seed, f"text-page-{i}", _WORDS_PER_PAGE)
text = " ".join(vocab[bisect(cumulative, d * scale)] for d in draws)
pool.append(text.encode()[:PAGE])
keys = stream_u32(seed, "shuffle", pool_pages)
return [pool[i] for i in sorted(range(pool_pages), key=keys.__getitem__)]
def _fill(buf: mmap.mmap, spec: Spec, pool: list[bytes]) -> int:
"""Write every page of ``buf`` from the pool; return the data CRC."""
pages = len(buf) // PAGE
picks = stream_u32(spec.seed, "fill", pages)
crc = 0
for first in range(0, pages, spec.chunk_pages):
count = min(spec.chunk_pages, pages - first)
chunk = b"".join(
pool[picks[j] % len(pool)] for j in range(first, first + count)
)
buf[first * PAGE : (first + count) * PAGE] = chunk
crc = zlib.crc32(chunk, crc)
return crc
def _touch(buf: mmap.mmap, spec: Spec) -> int:
"""Read a seeded hot subset ``rounds`` times; return the read CRC.
Each page is hot with probability ``hot_share``; hot pages are visited in
the order of their seeded key, i.e. a fixed random order.
"""
pages = len(buf) // PAGE
keys = stream_u32(spec.seed, "hot", pages)
limit = spec.hot_share * _U32
hot = sorted((k, i) for i, k in enumerate(keys) if k < limit)
crc = 0
for _ in range(spec.rounds):
for _key, page in hot:
crc = zlib.crc32(buf[page * PAGE : (page + 1) * PAGE], crc)
return crc
def run(spec: Spec, snapshots: Sequence[tuple[Path, Path]] = ()) -> Result:
"""Run one workload in a fresh anonymous mapping.
Each ``(src, dest)`` in ``snapshots`` is copied after the touch phase,
while the mapping is still live: that is when the zram/zswap pool holds
this run's pages, so its compression ratio can be read.
"""
pool = build_pool(spec.seed, spec.pool_pages, spec.random_share)
start_flt = resource.getrusage(resource.RUSAGE_SELF).ru_majflt
start = time.monotonic()
with mmap.mmap(-1, spec.size_mib * 1024 * 1024) as buf:
fill_crc = _fill(buf, spec, pool)
touch_crc = _touch(buf, spec)
for src, dest in snapshots:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(src.read_bytes())
pages = len(buf) // PAGE
return Result(
pages=pages,
fill_crc=fill_crc,
touch_crc=touch_crc,
majflt=resource.getrusage(resource.RUSAGE_SELF).ru_majflt - start_flt,
seconds=round(time.monotonic() - start, 3),
)