forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6c956a2Tahinli2 months ago3708 commits

memguard-runner.sh53 lines, 2.7 KiBHistoryRawDownload
1#!/usr/bin/env bash
2# Wraps a test/bin invocation in a transient user cgroup scope so a runaway
3# allocation dies inside its own cgroup instead of triggering a machine-wide
4# OOM kill. Used as the cargo target runner (see .cargo/config.toml) so every
5# `cargo test`/`cargo run` invocation of this workspace is capped, from any
6# checkout (main repo or worktree).
7set -euo pipefail
8
9if [ "${EC_NOMEMGUARD:-0}" = "1" ]; then
10 echo "memguard-runner: EC_NOMEMGUARD=1, running without memory cap" >&2
11 exec "$@"
12fi
13
14if ! systemd-run --user --scope --quiet -p MemoryMax=10G true >/dev/null 2>&1; then
15 echo "memguard-runner: systemd-run --user --scope unavailable, running without memory cap" >&2
16 exec "$@"
17fi
18
19# Explicit unique unit name: systemd-run derives `run-p<pid>.scope` when no
20# --unit is given, so a scope left loaded from an earlier run (or a reused
21# pid) collides with "Unit run-pNNN.scope was already loaded or has a
22# fragment file" -- the wrapped binary then never starts, which reads as a
23# broken tree rather than a runner collision. Measured 2026-09-29: three
24# lanes hit it in one batch and their workaround was invoking the test
25# binary directly, losing the memory cap.
26#
27# The collision is detected by PROBING, never by the wrapped command's exit
28# status: `systemd-run --scope` returns the command's own status, so
29# retrying on non-zero would run every failing test twice.
30unit="memguard-$$-$(date +%s%N)"
31# The probe must NOT reuse `$unit`: a transient scope stays loaded after it
32# exits, so probing and then exec'ing under the same --unit fails with
33# "unit was already loaded or has a fragment file" -- measured directly on
34# 2026-09-29 (the probe's own scope was the collision). Probe under "-probe".
35if ! systemd-run --user --scope --quiet --unit="${unit}-probe" -p MemoryMax=10G true >/dev/null 2>&1; then
36 # Clear a stale fragment for this name (and any leftover default-named
37 # scope) and probe once more before giving up on the cap.
38 rm -f "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/systemd/user/${unit}.scope" \
39 "${HOME}/.config/systemd/user/${unit}.scope" \
40 "${HOME}"/.config/systemd/user/run-p*.scope 2>/dev/null || true
41 systemctl --user daemon-reload 2>/dev/null || true
42 if ! systemd-run --user --scope --quiet --unit="${unit}-r" -p MemoryMax=10G true >/dev/null 2>&1; then
43 echo "memguard-runner: scope unavailable even after clearing stale fragments, running without memory cap" >&2
44 exec "$@"
45 fi
46 exec systemd-run --user --scope --quiet --same-dir --unit="${unit}-r" \
47 -p MemoryMax=10G -p MemorySwapMax=2G \
48 -- "$@"
49fi
50
51exec systemd-run --user --scope --quiet --same-dir --unit="$unit" \
52 -p MemoryMax=10G -p MemorySwapMax=2G \
53 -- "$@"