Adhiraj Singh ← All notes

Pausing a Render Doesn't Give Its Memory Back

thermal-sentry is one Python file that watches over a long Blender render on my laptop. It reads the CPU package temperature, free memory, free disk space and the battery level. When one of them gets dangerous, it pauses the render before the heat, the kernel or a flat battery kills it. It has no dependencies and runs on Linux only.

The design started from one cheap trick: SIGSTOP. A stopped process is frozen in place. It keeps its position and the frame it was halfway through, and SIGCONT resumes it exactly where it was. For heat, a low battery, a full disk and a manual pause, that's the whole answer: freeze, wait, continue.

Memory is where the trick fails. Most of the interesting code in the file deals with that one exception.

A frozen job still holds its RAM

A stopped process still owns every page of memory it allocated. If the laptop is running out of memory because Blender is using it, freezing Blender doesn't help. The memory stays allocated and the kernel's out-of-memory killer still has a target. The job just stops making progress while it waits to be killed. The README puts it in a parenthesis: "a frozen job still holds its RAM, so it has to go; its current frame is lost."

So the sentry has two kinds of action. Heat, battery, disk and manual pause freeze the job, and nothing is lost. Memory danger stops the job, and the frame in progress is thrown away. Losing that frame is what it costs to keep the machine alive.

The memory check runs even while the job is frozen. If I've paused a render by hand and memory runs short anyway, the job still gets killed. There's a test for exactly that case: test_stopped_job_is_still_killed_on_memory_danger.

Stopping before the kernel does

If a frame is going to be lost, I want the sentry to choose when, instead of leaving the out-of-memory killer to pick whatever process it likes. So memory_danger checks three things:

def memory_danger(self, r, now):
    c = self.cfg
    if r.mem_total <= 0:
        return ""  # /proc/meminfo unreadable: never act on a zero
    if r.headroom < c.mem_floor:
        return f"only {r.headroom:.0f} MB of RAM+swap left"
    if r.psi_full10 is not None and r.psi_full10 >= c.psi_limit:
        return f"the system is thrashing ({r.psi_full10:.0f}% memory stall)"
    if now - self.started_at >= STARTUP_GRACE and r.headroom < 2 * c.mem_floor:
        pts = [(t, h) for t, h in self.hist if now - t <= 30]
        if len(pts) >= 5:
            s = slope(pts)
            if s < 0 and (r.headroom - c.mem_floor) / -s < 30:
                return f"{r.headroom:.0f} MB left, falling {-s:.0f} MB/s"
    return ""

Headroom is available RAM plus free swap, and the floor defaults to 500 MB. The pressure check reads the "full" line of /proc/pressure/memory. That number is the share of the last ten seconds in which every task was stalled waiting for memory. At 25% the machine is thrashing, even if headroom is still above the floor. The third check fits a least-squares slope to the last 30 seconds of headroom and stops the job if that line would reach the floor within the next 30 seconds.

The prediction has two guards. It only applies once headroom drops below twice the floor. It's also switched off for the first two minutes of each run, because Blender loading a scene's textures looks just like a memory leak. The first line matters too. If /proc/meminfo can't be read, every value comes back as zero, and a read failure must never look like an empty machine.

Killing a frozen process takes two signals

Here the freezing causes its own problem. A stopped process doesn't act on most signals until it's continued. SIGTERM just waits. So the stop path sends both:

for sig in (signal.SIGTERM, signal.SIGCONT):  # a stopped job only sees TERM once continued
    try:
        os.killpg(p.pid, sig)
    except (ProcessLookupError, PermissionError):
        pass

Then the sentry waits up to 20 seconds and sends SIGKILL to the whole process group. The job runs in its own session, so Blender and anything it starts are frozen, measured and killed together.

The same problem shows up if the sentry itself is killed outright. Before the job starts, the sentry sets PR_SET_PDEATHSIG so the job gets SIGKILL when the sentry dies. The docstring says why it's SIGKILL: it "works even while the job is SIGSTOPped." Without that, a dead sentry could leave behind a frozen Blender holding gigabytes of RAM, with nothing left to resume it.

When something else kills it first

The sentry checks every two seconds, and memory can run out faster than that. So it has plans for losing that race.

If the job exits from SIGKILL, the sentry assumes the kernel's out-of-memory killer did it. It treats that like one of its own memory stops: it counts a failure and starts a cooldown.

The worse case is systemd-oomd, which kills the whole unit, sentry included. The sentry can't react to its own death, so it leaves a record behind. Every check writes a status file marked "clean": false, and only a normal exit marks it "clean": true. The next sentry with the same name reads that file in recover(). Suppose the previous sentry died uncleanly in the last ten minutes, with less than twice the floor free. Then the new one starts with a memory cooldown instead of going straight back into the same kill.

That matters because of how I run it. The Earth film for the Imagine Infinity site renders under systemd-run with Restart=on-abnormal, so systemd restarts the unit after oomd kills it. Without recover(), that restart would be the quickest way to repeat the crash.

Coming back only when it fits

After a heat pause, the job resumes once 30 minutes have passed and the CPU is down to 70 °C. After a memory stop, the condition is different: there has to be enough free memory for the job to finish. The sentry measures that instead of guessing. On every check it adds up resident and swapped memory across the job's process group and keeps the peak. After a memory stop, it won't restart until the cooldown is over and headroom covers that peak, plus the floor, plus a 500 MB margin.

def need(self, r):
    # Never demand more than the machine could ever free.
    return min(self.mem_need, 0.9 * r.mem_total) if r.mem_total else self.mem_need

Capping the requirement at 90% of RAM plus swap means the sentry never waits for memory the machine doesn't have. The peak also carries over to the next sentry: recover() reads it back from the old status file.

The retries are limited too. After three failed runs in a row with no progress, the sentry gives up. No progress means no new frame and less than ten minutes of running time. Giving up is a plain non-zero exit, which Restart=on-abnormal doesn't restart, so the unit stays down.

The frame I throw away

Killing the job loses the current frame, and it doesn't always lose it cleanly. A kill or a power cut in the middle of a write can leave a truncated PNG on disk. If the renderer skips frames that already exist, it would skip that broken frame forever. So when --frames is set, the sentry checks every PNG before each start or restart. Each file needs the 8-byte PNG signature at the start and the IEND chunk at the end. Any file that fails is moved to .thermal-sentry-broken/ and gets rendered again.

What the exception cost

Every trigger that freezes the job is a few lines: a threshold, a flag, SIGSTOP, SIGCONT. Memory is the exception, and it accounts for most of the rest of the file:

If SIGSTOP freed memory, none of that would exist. It doesn't, so the sentry has to decide which frame to lose, and then make sure losing it doesn't cause another crash.