Your Agent Didn't Crash. The Pi Was Swapping Itself to a Crawl.

You check in after the overnight run. Nothing crashed. There is no OOM line in the journal. systemctl status says the agent unit is active. But the job that normally takes two minutes finished hours late, or it hit its timeout and gave up. When you opened SSH, every keystroke lagged like you were typing through mud. Load average was far above your core count, yet top showed the CPU mostly idle.

That pattern usually means the box was swap thrashing: memory was full, and the kernel spent the night moving pages of your agent, a headless browser, or a local model between RAM and a slow SD card or USB disk.

This post covers how to confirm thrashing with real numbers, rule out the problems that look similar, get relief without making things worse, make the fix persist, and add a fail-closed preflight so the next heavy job does not start into a box that is already drowning.

What thrashing actually looks like

Thrashing has a recognizable set of symptoms when you look at the right counters:

  • free -h shows the available column near zero and swap mostly used.
  • vmstat 1 10 shows non-zero si and so on most lines. Those columns are memory swapped in from disk and swapped out to disk per second. The wa column (percent of time waiting on I/O) is high, and the b column (processes blocked) is often above zero.
  • Load average sits far above the number of cores while us (user CPU) stays low. On Linux, processes waiting on disk count toward load.
  • top or ps shows processes in state D, uninterruptible sleep, usually waiting on I/O.
  • Job logs show long gaps between lines that are normally milliseconds apart.
  • The run timeout fires.
  • journalctl -k has no “Out of memory: Killed process” line.
  • If /proc/pressure/memory exists, its some and full avg10 values are high. Pressure stall information may not be enabled on every Pi kernel, so treat it as a bonus signal, not a requirement.

The key point: swap being used is not the problem by itself. Pages that went to swap once and stay there are fine; that is the kernel parking memory nobody is touching. Thrashing is continuous swap-in and swap-out while real work is trying to run. A box with 900 MB in swap and si/so at zero is healthy. A box with 200 MB in swap and si/so in the thousands every second is not.

Rule out the cousins

Several other failures produce “the job was slow or late” with no obvious crash.

  • The OOM killer. If memory ran out completely, a process gets killed and the kernel log says so. Check for the line before you assume thrashing. See the OOM killer and memory limits post.
  • Undervoltage or thermal throttling. On a Pi, vcgencmd get_throttled returns non-zero bits when the board has been undervolted or throttled. The CPU slows down, but si/so stay quiet. See the undervoltage and throttling post.
  • A run hung on the network or an interactive prompt. CPU is quiet, si/so are quiet, and the process is sleeping on a socket or waiting for input that will never come. The box itself feels responsive.
  • Overlapping runs. A missing lock or a missing timeout lets the second copy start before the first finishes. That can be the cause of thrashing, so fix both. See run timeouts and overlap protection.
  • A full disk. df -h shows 100 percent, and you get write errors such as “No space left on device,” not silent slowness.

Why it hides

Thrashing rarely triggers an alert. Nothing crashed, so crash alerting stays silent. The unit stays active, so the health check passes. A timeout in the logs looks like a flaky API or a network problem. It often only happens at night, when two heavy jobs overlap: a headless browser, a local model, a build. Swap on an SD card is very slow at random I/O, so even a modest amount of paging hurts a lot. And the swap size was often set by an image default that nobody ever looked at.

If your jobs keep finishing late without failing outright, a stalled automation alarm will catch the symptom even before you know the cause.

Step 1: Confirm with numbers

Run these during the slow window, or reproduce the overlap on purpose:

free -h
swapon --show
vmstat 1 10
uptime
nproc
ps -eo pid,user,rss,comm --sort=-rss | head -n 12
ps -eo state,pid,comm | awk '$1=="D"'
[ -r /proc/pressure/memory ] && cat /proc/pressure/memory
journalctl -k --since "yesterday" | grep -i "out of memory"
vcgencmd get_throttled 2>/dev/null

Read vmstat line by line. Ignore the first line, which is an average since boot. If most of the remaining lines show si and so above zero with high wa, you are thrashing.

swapon --show tells you where swap lives. Many Pi OS images use dphys-swapfile with a swap file such as /var/swap. Some current images use zram, which shows up as /dev/zram0. Check rather than assume, because the fix differs.

The ps ... --sort=-rss output shows who is holding the memory. On an agent box, the top entries are usually a Chromium process tree, a local model runner, or a build toolchain, not the agent itself.

Step 2: Get immediate relief safely

Stop the heaviest non-essential job through systemd so it shuts down cleanly and gives back memory:

sudo systemctl stop heavy-browser-job.service
vmstat 1 10

Wait until si and so settle near zero, then let the main agent finish its run. If the run already timed out, rerun it once the box is calm.

Avoid these moves:

  • Do not drop caches as a fix. Writing to drop_caches throws away useful file cache. It does nothing about anonymous memory that is being paged, and the box refills it immediately.
  • Do not swapoff -a on a box that is short on memory. The kernel has to pull everything in swap back into RAM. If it does not fit, you invite the OOM killer.
  • Do not kill -9 the agent mid-write as the first move. You risk corrupting state files or leaving half-written output. Stop the non-essential job first.

Step 3: Make the fix persist

Cap heavy units. Give each heavy unit a drop-in with systemd resource control. These directives need cgroup v2, which current Pi OS and Debian use.

sudo systemctl edit heavy-browser-job.service
[Service]
MemoryHigh=600M
MemoryMax=800M
MemorySwapMax=200M

MemoryHigh= throttles the unit and reclaims memory once usage passes the limit, so it slows down instead of dragging the whole box with it. MemoryMax= is a hard cap; if the unit hits it, the OOM killer acts inside that unit only. MemorySwapMax= caps how much swap the unit may use, so one job cannot push everything else out. The numbers above are an example for a box with a few gigabytes of RAM. Fit them to your RAM and to what the job actually needs, which you can read from systemctl status while it runs.

Confirm the values took effect:

sudo systemctl daemon-reload
systemctl show heavy-browser-job.service -p MemoryHigh -p MemoryMax -p MemorySwapMax

Stop heavy jobs from overlapping. Stagger timers so a headless browser and a local model never run at the same time, or serialize them behind a shared lock. A load governor generalizes this so new jobs wait when the box is busy.

Right-size swap. On dphys-swapfile, do this while the box is quiet:

sudo dphys-swapfile swapoff
sudo nano /etc/dphys-swapfile   # set CONF_SWAPSIZE=1024 (in MB), fit to your RAM
sudo dphys-swapfile setup
sudo dphys-swapfile swapon
swapon --show

CONF_MAXSWAP in the same file also caps the size, so check it if your change does not seem to stick. More swap is not a cure; it only gives the kernel somewhere to park idle pages. The real fix is fewer heavy jobs at once and caps on the ones you run.

If your image offers zram, compressed swap in RAM avoids disk I/O entirely and is often a better fit for small boards. If you must keep disk swap, prefer a USB SSD over the SD card. With dphys-swapfile you can point CONF_SWAPFILE at a path on the SSD, as long as that disk mounts reliably at boot.

Do not disable swap entirely as the standing fix on a small-RAM box. Without it, a brief spike goes straight to the OOM killer.

Step 4: Add a fail-closed preflight

This script refuses to start a heavy job when available memory is low or the box is already paging. It uses only bash, awk, and coreutils, plus curl if you want Discord alerts.

#!/usr/bin/env bash
# /usr/local/bin/swap-preflight.sh
# Exit 0 if memory is healthy, exit 1 if low or actively swapping.
set -u

MIN_AVAIL_MB="${MIN_AVAIL_MB:-300}"
MAX_SWAP_PAGES_PER_SEC="${MAX_SWAP_PAGES_PER_SEC:-50}"
SAMPLE_SECS="${SAMPLE_SECS:-5}"
MARKER_DIR="${MARKER_DIR:-/run/agent-preflight}"
MARKER="$MARKER_DIR/swap-thrash.alerted"

read_swap() {
  awk '$1=="pswpin"{i=$2} $1=="pswpout"{o=$2} END{print i+0, o+0}' /proc/vmstat
}

avail_mb=$(awk '/^MemAvailable:/{print int($2/1024)}' /proc/meminfo)

read -r in1 out1 < <(read_swap)
sleep "$SAMPLE_SECS"
read -r in2 out2 < <(read_swap)

in_rate=$(( (in2 - in1) / SAMPLE_SECS ))
out_rate=$(( (out2 - out1) / SAMPLE_SECS ))
total_rate=$(( in_rate + out_rate ))

summary="avail=${avail_mb}MB (min ${MIN_AVAIL_MB}) swap_in=${in_rate}/s swap_out=${out_rate}/s pages (max ${MAX_SWAP_PAGES_PER_SEC}/s)"

if [ "$avail_mb" -ge "$MIN_AVAIL_MB" ] && [ "$total_rate" -le "$MAX_SWAP_PAGES_PER_SEC" ]; then
  echo "swap-preflight OK: $summary"
  rm -f "$MARKER" 2>/dev/null
  exit 0
fi

echo "swap-preflight FAIL: $summary" >&2
logger -t swap-preflight "FAIL: $summary" 2>/dev/null

if [ -n "${DISCORD_WEBHOOK_URL:-}" ] && [ ! -e "$MARKER" ]; then
  msg="$(hostname): heavy job skipped, memory pressure. $summary"
  if curl -fsS -m 10 -H "Content-Type: application/json" \
       -d "{\"content\":\"${msg}\"}" "$DISCORD_WEBHOOK_URL" >/dev/null 2>&1; then
    mkdir -p "$MARKER_DIR" 2>/dev/null && touch "$MARKER" 2>/dev/null
  else
    echo "swap-preflight: alert delivery failed" >&2
  fi
fi

exit 1

The counters pswpin and pswpout are cumulative pages swapped in and out since boot, so the difference between two reads divided by the sample length gives a rate. A page is usually 4 KiB, larger on some Pi kernels. MemAvailable is in kB, hence the divide by 1024. The script never prints the webhook URL. The marker lives in /run, so it clears on reboot, and the script removes it as soon as the box is healthy again, which means you get one alert per outage.

If the job runs as a non-root user, create the marker directory at boot with a tmpfiles entry, for example d /run/agent-preflight 0755 agent agent - in /etc/tmpfiles.d/agent-preflight.conf.

Cron, chaining with && so the job only runs on a pass:

30 2 * * * . /etc/agent/preflight.env; /usr/local/bin/swap-preflight.sh && /usr/local/bin/nightly-browser-job.sh

As a systemd gate, so the unit fails to start instead of crawling:

[Service]
EnvironmentFile=-/etc/agent/preflight.env
ExecStartPre=/usr/local/bin/swap-preflight.sh

Keep /etc/agent/preflight.env readable only by the job’s user, since it holds the webhook URL.

A standing routine

  • Before adding a new heavy job: check its peak memory by hand, give it MemoryHigh= and MemoryMax=, and schedule it away from the other heavy jobs.
  • After changing models or browser automation: rerun vmstat 1 10 during a real run. A bigger model or a new browser flow can quietly double the footprint.
  • Weekly: glance at vmstat during the busy window and confirm si and so stay near zero.
  • After reboot: run swapon --show to confirm swap is where you expect and the size you set.

If you want ready-made prompts for walking an agent through this kind of triage, start with the free prompts. The OpenClaw Agent Ops Toolkit collects preflights and runbooks like this one for unattended boxes, and the bundle packages it with the rest of the MarketMai operator material.

More from the build log

Suggested

Want the full MarketMai stack?

Get the core MarketMai guides and operator playbooks in one premium bundle for $49.

View Bundle