The OS Upgrade Went Fine. Your Agent's Python venv Didn't.

You check in the morning after an overnight run. The agent service is green and the box answers ping. But the scheduled job that scrapes, summarizes, or publishes did nothing. Its log is either empty or ends in one short line about a missing interpreter or a module that you know you installed. Somewhere in the last few days, the OS or its python3 got upgraded, and the job’s virtual environment is still built for the old one.

This guide shows how to confirm that a broken venv is the problem, how to rule out the failures that look like it, how to rebuild it without making things worse, and what the related externally-managed-environment error means. It ends with a small fail-closed preflight you can put in front of any cron or systemd job.

The errors you’ll actually see

People usually describe it like this: “it worked for months and then stopped overnight,” “pip says the module is installed but Python can’t find it,” or “the script says bad interpreter but the file is right there.” The error strings vary with how the venv was created and what changed:

/home/pi/agent/.venv/bin/pip: bad interpreter: No such file or directory
/bin/sh: 1: /home/pi/agent/.venv/bin/python: not found
ModuleNotFoundError: No module named 'requests'
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
ModuleNotFoundError: No module named 'encodings'
error: externally-managed-environment

Under cron, the job just exits with a non-zero code. 126 and 127 are common, depending on the shell and on what exactly is missing. Under systemd, a missing executable in ExecStart usually shows up as status=203/EXEC in systemctl status, while a Python-level failure shows up as an ordinary non-zero exit.

Rule out the cousins first

A few other failures look a lot like this one.

  • Cron environment. If the job works when you run it by hand but fails under cron, and .venv/bin/python -c 'import requests' works in your shell, the problem is more likely PATH, HOME, or missing environment variables than the venv. See cron environment.
  • Dependency drift. If the interpreter version hasn’t changed but the traceback comes from inside a library (an AttributeError, or an ImportError for a name rather than a module), an unpinned package probably moved under you. That needs a different fix.
  • A security update restart. If the apt log only shows patch-level changes and python3 is still on the same minor version, the job may just have been interrupted by a restart. Check whether unattended security updates ran during the failure window.

If python3’s minor version changed, or its binary moved, keep reading.

Why it breaks

A venv is not a self-contained copy of Python. It’s a small directory containing a pyvenv.cfg file, a bin/ folder whose python entries are usually symlinks to the base interpreter, and a lib/python3.X/site-packages folder. The Python docs say venvs aren’t meant to be moved or copied, and they aren’t designed to survive a change in the base interpreter’s minor version.

There are two common ways this fails:

  1. The symlink points at a versioned binary that is gone. If the venv was created with python3.11 -m venv, or by pyenv or Homebrew paths that get removed on upgrade, bin/python is now a dangling link. Every script in bin/ has an absolute shebang pointing at that link, so you get bad interpreter. If the stdlib is gone but some path still resolves, you can get No module named 'encodings' instead.
  2. The symlink points at /usr/bin/python3, which still exists but is newer. Raspberry Pi OS and Debian moving from Bookworm (3.11) to Trixie (3.13) is one example. The interpreter starts, but it looks for packages under lib/python3.13/site-packages, while yours are in lib/python3.11/. Every import fails even though pip installed everything.

Compiled packages make this worse. A wheel built for one CPython ABI (cp311) won’t load in another (cp313), so copying site-packages across doesn’t work either.

Confirm it

Run these from the job’s project directory. Adjust .venv to your path.

ls -l .venv/bin/python*
readlink -f .venv/bin/python
cat .venv/pyvenv.cfg
python3 --version
ls /usr/bin/python3*
.venv/bin/python -c 'import sys; print(sys.version, sys.prefix)'
head -1 .venv/bin/pip

Here’s what to look for. If readlink -f points at a path that doesn’t exist, the link is dangling. If the version (or version_info) line in pyvenv.cfg has a different major.minor than python3 --version, the venv was built for an interpreter that is no longer the default. The sys.prefix line should print the venv path. If it prints /usr, the venv isn’t being used at all.

Then find out when the change happened:

zgrep -h -E 'Start-Date|Commandline|python3[.:]' /var/log/apt/history.log*
journalctl -u agent-job.service --since "2 days ago" --no-pager
cat /etc/os-release

If the apt history shows a python3 upgrade between the last good run and the first failed one, you’ve found the cause.

Fix it without making it worse

Don’t hand-edit symlinks, change pyvenv.cfg, or copy site-packages into a new version directory. Any of those might get one import working while leaving compiled extensions half-broken. Rebuild the venv instead.

cd /home/pi/agent
sudo systemctl stop agent-job.timer        # or comment out the cron line

# keep the old one for reference until the job passes
mv .venv .venv.old-$(date +%Y%m%d)

# build at the real path: venvs are not relocatable, so don't build elsewhere and rename
python3 -m venv .venv
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python -m pip install -r requirements.txt

# smoke test with the imports your job actually needs
.venv/bin/python -c 'import requests, yaml; print("imports ok")'
.venv/bin/python run_job.py --dry-run     # if your job supports something like this

sudo systemctl start agent-job.timer

If you don’t have a requirements file, you can’t run the old venv’s pip any more, but the *.dist-info directory names under .venv.old-*/lib/python3.X/site-packages/ still list package names and versions. Rebuild a pinned file from those.

Two things to expect on a Pi or a small ARM VPS. First, older pinned versions may not support the new Python minor at all. In that case you either bump those pins on purpose and retest, or run the job on the older interpreter (see below). Second, if there’s no prebuilt wheel for your architecture and Python version, pip will try to compile from source, which needs packages like build-essential and python3-dev. That can be slow on a Pi.

Delete .venv.old-* only after the job has passed at least one real scheduled run.

About externally-managed-environment

On Debian 12 and later, Raspberry Pi OS Bookworm and later, and Ubuntu 23.04 and later, the system Python is marked as externally managed (PEP 668). Running pip install against it, including pip install --user, fails with:

error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.

This often shows up right after the venv problem, because a broken or missing venv means the job, or the agent’s own install step, falls back to the system pip. Inside a working venv this error doesn’t appear. If you see it, take it as a sign that your venv isn’t being used.

Don’t use --break-system-packages on the box that runs your agent, and don’t delete the marker file. Mixing pip-installed packages into the Python that apt manages is how a later OS upgrade breaks system tools along with your job. Use one of these instead:

  • For project dependencies, use the venv, and always call it as .venv/bin/python -m pip install ....
  • For standalone command-line tools, use pipx install sometool, which gives each tool its own venv.
  • For tools the system itself needs, use the Debian package (apt install python3-xyz) where one exists.

If your agent can install packages itself, write the venv’s absolute pip command into its instructions or config so it never reaches for the system pip.

Make it stop for good

  • Pin everything. Use a requirements file with hashes (pip-compile --generate-hashes from pip-tools, or uv pip compile --generate-hashes) or a lockfile. When any requirement has a hash, pip enables hash-checking mode automatically. A rebuild is only safe if it reproduces what you had. More in dependency pinning.
  • Call the interpreter by absolute path. In cron and in systemd ExecStart, use /home/pi/agent/.venv/bin/python run_job.py. Don’t rely on source activate, which mostly adjusts PATH for interactive shells and does nothing useful in a unit file.
  • Record the expected version. Write the major.minor into a file next to your requirements when you build. The preflight below compares against pyvenv.cfg, and a separate file makes the expected version visible in your repo. Note that pyenv and uv both read .python-version, so naming it that will also change which interpreter they pick.
  • Treat release upgrades as planned work. Unattended upgrades normally stay within a release. A move from Bookworm to Trixie is something you do on purpose, so put “rebuild venvs and run preflight” on that checklist. Holding python3 itself with apt-mark hold tends to block other upgrades, so plan the release instead.
  • Decouple the interpreter if you need to. Tools like uv (uv python install, uv venv --python 3.12) or pyenv can give a project its own interpreter that apt won’t touch. The tradeoff is that you’re now responsible for patching it. Check the current docs for exact commands, because these tools change quickly.

A fail-closed preflight

This script exits 0 only if the venv’s Python exists and runs, its major.minor matches what pyvenv.cfg recorded at build time, and your critical imports succeed. The stdlib venv writes a version key. Tools like virtualenv and uv have been seen writing version_info instead, so the script accepts either. Check your own file.

It can optionally send one Discord alert per outage. It uses a marker under /run, which is cleared on reboot and on the next passing run. It reads the webhook from an env file without sourcing it, and never prints the URL.

#!/usr/bin/env bash
# venv-preflight.sh: exit 0 only if the job's venv is usable.
set -u

VENV="${VENV:-/home/pi/agent/.venv}"
IMPORTS="${IMPORTS:-requests yaml}"
NAME="${NAME:-agent-job}"
ENV_FILE="${ENV_FILE:-/home/pi/agent/alert.env}"  # line: DISCORD_WEBHOOK_URL=https://...
MARKER="/run/agent-preflight/${NAME}.alerted"
PY="$VENV/bin/python"

fail() {
  echo "preflight FAIL ($NAME): $1" >&2
  if [ -r "$ENV_FILE" ] && [ ! -e "$MARKER" ]; then
    url=$(grep -m1 '^DISCORD_WEBHOOK_URL=' "$ENV_FILE" | cut -d= -f2-)
    if [ -n "$url" ]; then
      msg=$(printf '%s' "venv preflight FAIL on $(hostname) ($NAME): $1" | tr -cd '[:alnum:] ._:/()=,-')
      curl -fsS -m 10 -H 'Content-Type: application/json' \
        -d "{\"content\":\"$msg\"}" "$url" >/dev/null 2>&1 \
        && touch "$MARKER" 2>/dev/null
    fi
  fi
  exit 1
}

[ -f "$VENV/pyvenv.cfg" ] || fail "no pyvenv.cfg in $VENV"
[ -x "$PY" ] || fail "venv python missing or dangling at $PY"

actual=$("$PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null) \
  || fail "venv python does not run"

recorded=$(sed -n -E 's/^[[:space:]]*version(_info)?[[:space:]]*=[[:space:]]*([0-9]+\.[0-9]+).*/\2/p' \
  "$VENV/pyvenv.cfg" | head -n1)
[ -n "$recorded" ] || fail "no version or version_info line in pyvenv.cfg"
[ "$actual" = "$recorded" ] || fail "venv built for $recorded but interpreter is $actual"

for mod in $IMPORTS; do
  "$PY" -c "import $mod" >/dev/null 2>&1 || fail "import $mod failed"
done

rm -f "$MARKER" 2>/dev/null
echo "preflight ok ($NAME): python $actual"
exit 0

The marker directory has to exist and be writable by the job’s user. A tmpfiles.d entry such as d /run/agent-preflight 0755 pi pi - in /etc/tmpfiles.d/agent-preflight.conf recreates it at boot. If the marker can’t be written, the script still fails closed. You’ll just get an alert on every failed run instead of one per outage.

In cron, chain it with && so the job never starts on a bad venv:

15 3 * * * { /home/pi/agent/bin/venv-preflight.sh && /home/pi/agent/.venv/bin/python /home/pi/agent/run_job.py; } >> /home/pi/agent/logs/job.log 2>&1

In systemd, use it as ExecStartPre. If it exits non-zero, the unit fails and ExecStart never runs:

[Service]
Type=oneshot
User=pi
Environment=VENV=/home/pi/agent/.venv
Environment="IMPORTS=requests yaml"
ExecStartPre=/home/pi/agent/bin/venv-preflight.sh
ExecStart=/home/pi/agent/.venv/bin/python /home/pi/agent/run_job.py

A standing routine

  • Keep a pinned, hashed requirements file or lockfile for every venv a job uses.
  • Call the venv interpreter by absolute path everywhere. Never rely on activate.
  • Put the preflight in front of every scheduled Python job.
  • Before any OS release upgrade, list your venvs. Afterwards, rebuild them and run each preflight by hand.
  • After any python3 change in the apt log, run the preflights the same day, not after the overnight run.
  • Never use --break-system-packages on the agent box. Use a venv, pipx, or apt.
  • Keep the old venv until the rebuilt one has passed a real scheduled run.

If you want ready-made checks like this for the rest of your agent box, start with the free prompts. The OpenClaw Agent Ops Toolkit collects preflights, runbooks, and alerting patterns for unattended jobs in one place, and the bundle includes it along with the rest of the MarketMai ops 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