Linux administrator reviewing systemd runtime-directory settings and service restart logs.

A systemd Restart Can Preserve Files That Stop and Start Remove

Mon, Nov 30, 2026

A maintenance script can report a successful restart, a replacement invocation can appear, and an old runtime marker can still be present. That is not automatically an error. Under RuntimeDirectoryPreserve=restart, systemd documents preservation of RuntimeDirectory= contents across both manual and automatic restarts; under RuntimeDirectoryPreserve=no, the default, the managed runtime directory is removed when the service stops. With yes, it remains even after an ordinary stop. The operational problem is therefore not “did the command return zero?” but “did this exact lifecycle transaction produce the file-retention behavior the service owner approved?”

This playbook is for system administrators, service owners and platform engineers approving that contract. It defines an owned, disposable Linux VM fixture using an ordinary account and a working systemd user manager. Ten fresh services seed one synthetic sentinel.bin only in the first generation, then test manual restart, completed stop followed by start, automatic failure restart, and stopped-unit cleanup. The evidence joins the manager’s loaded policy, raw INVOCATION_ID, exact marker bytes and command results.

Execution status: NOT EXECUTED. Overall disposition: HOLD. This research environment did not run the full fixture on an owned disposable VM and retain evidence. Every behavioral row below is therefore an authored EXPECTED result derived from the v257 documentation baseline and the fixture logic, not an observation. This is a runtime-directory retention test, not an application-readiness test, reboot/logout durability test, or claim that retained bytes are safe for an application to reuse.

Define the runtime-file retention contract

The fixture uses one file, sentinel.bin, inside one systemd-managed RuntimeDirectory=. The controller alone creates it, with exact ASCII bytes RUNTIME_SENTINEL:<case-id> followed by one newline. The worker reads it once at startup, closes the handle, and never creates, rewrites, renames or deletes it. That separation keeps the deletion authority under test where it belongs: the manager’s lifecycle policy.

The v257 systemd.exec manual, directly checked on November 30, 2026, has a page header identifying systemd 257.13 and states no publication date; it defines three values. RuntimeDirectoryPreserve=no is the default and removes managed runtime directories when the service stops. restart preserves them across both a systemctl restart transaction and automatic restarts controlled by Restart=. yes preserves them after the service stops. The directive was added in version 235. For user units, RuntimeDirectory= is rooted below $XDG_RUNTIME_DIR, and $RUNTIME_DIRECTORY exposes the absolute managed path to the service. These are established semantics in the chosen versioned baseline, not a feature claimed to have launched in 2026.

Keep three lifetimes separate: the service process lifetime, the managed runtime-directory lifetime, and any application decision to trust retained bytes. A replacement PID proves only that a new process exists. A retained marker proves a pathname and byte sequence survived the tested transaction. It does not prove that stale state is semantically valid. A service owner may want retention for reconstructible cache state or may reject it because any old marker is hazardous.

Use five dispositions. ACCEPT means policy, operation and captured receipts match the declared contract. REPAIR means valid evidence shows the current maintenance procedure violates the desired contract. HOLD means execution, manager identity, versions or evidence are incomplete. RECONCILE means retained fixture resources are uncertain and must be inventoried before cleanup. REVERT means restore an identified prior configuration, then validate again; rollback does not recreate deleted bytes.

Startup receipts here only identify generations and what each generation read. For the separate question of when dependents may safely proceed, keep systemd startup-readiness acceptance as its own contract.

Verify the user manager and record the baseline

Run only on an owned disposable Linux VM as a normal account with a functioning per-user systemd manager. Every lifecycle command in this playbook uses systemctl --user. Do not “fix” a missing user bus by switching to a privileged system manager: system and user unit search paths differ, and user RuntimeDirectory= paths resolve under the user runtime root. The v257 unit manual shows distinct system and user load paths and defines %t as /run/ for the system manager but $XDG_RUNTIME_DIR for user managers.

Capture the operating-system identity, username and UID, XDG_RUNTIME_DIR, systemctl client version, running manager version, resolved Python interpreter, hashes of the worker/controller sources and a unique run namespace. Record complete stdout, stderr and exit status. The existing persistent timer catch-up validation uses the same evidence principle: inability to contact the intended user manager is a reason to stop, not permission to substitute another manager.

Use a fresh run token such as rtdp-20261130T120000Z-<random>. Before any case, refuse to proceed if its unit file, unit identity, external evidence directory or expected managed runtime path already exists. Do not overwrite fragments, consume old receipts or silently adopt a leftover runtime directory. A clean namespace is part of the oracle, because preexisting bytes can otherwise look like preservation.

Identify the client and running manager separately

Capture these commands independently:

set -u
mkdir -p "$CAPTURE"
(systemctl --version; printf 'rc=%s\n' "$?") >"$CAPTURE/systemctl-client.txt" 2>&1
(systemctl --user show --property=Version --all; printf 'rc=%s\n' "$?") \
  >"$CAPTURE/user-manager.txt" 2>&1
(id; printf 'XDG_RUNTIME_DIR=%s\n' "${XDG_RUNTIME_DIR-}"; \
 cat /etc/os-release; command -v python3; python3 --version) \
  >"$CAPTURE/host.txt" 2>&1

systemctl --version identifies the installed client binary; it does not by itself identify the manager process answering --user. systemctl show is intended for machine-parsable manager/unit properties and exposes normalized configuration plus runtime state. The documentation baseline for this article is the versioned v257 branch, and the four versioned manuals cited here currently present a 257.13 header. That baseline is not a claim about the VM you later execute. If the running manager differs, record the difference and inspect its matching manuals before approval.

Build a worker that cannot restore the sentinel

The fixture uses Type=exec. In v257, that means the manager considers startup reached after the main binary has been successfully executed; it does not mean the worker has completed its first marker read. That is why the controller waits for an explicit startup receipt before seeding or evaluating a replacement generation.

Save this as worker.py outside every RuntimeDirectory=:

#!/usr/bin/env python3
import hashlib, json, os, pathlib, sys, tempfile, time
from datetime import datetime, timezone

case_id, evidence_s, control_s = sys.argv[1:4]
evidence = pathlib.Path(evidence_s)
control = pathlib.Path(control_s)
runtime = pathlib.Path(os.environ["RUNTIME_DIRECTORY"])
inv = os.environ["INVOCATION_ID"]
sentinel = runtime / "sentinel.bin"

def atomic_json(path, obj):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=path.parent, text=True)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(obj, f, sort_keys=True)
            f.write("\n")
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
    finally:
        try:
            os.unlink(tmp)
        except FileNotFoundError:
            pass

mono = time.monotonic_ns()
base = {
    "schema": 1,
    "case_id": case_id,
    "receipt_type": "startup",
    "invocation_id": inv,
    "runtime_directory": str(runtime),
    "monotonic_ns": mono,
    "utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}

try:
    data = sentinel.read_bytes()
    base.update(
        sentinel_state="present",
        sentinel_text=data.decode("ascii"),
        sentinel_sha256=hashlib.sha256(data).hexdigest(),
        read_error=None,
    )
except FileNotFoundError as e:
    base.update(
        sentinel_state="missing",
        sentinel_text=None,
        sentinel_sha256=None,
        read_error=type(e).__name__,
    )
except Exception as e:
    base.update(
        sentinel_state="error",
        sentinel_text=None,
        sentinel_sha256=None,
        read_error=type(e).__name__,
    )

atomic_json(evidence / f"startup-{mono}-{inv}.json", base)

request = control / "fail.request"
while True:
    if request.exists():
        consumed = control / f"fail.consumed.{inv}"
        try:
            os.replace(request, consumed)
        except FileNotFoundError:
            pass
        else:
            sys.exit(17)
    time.sleep(0.05)

The worker has no code path that writes sentinel.bin. Its evidence and failure control live outside the managed runtime directory. The controller seeds only after generation one has emitted a missing receipt, then it verifies the bytes itself.

Separate runtime data from controller evidence

Each case gets a fresh unit name, external evidence directory, external control directory and relative runtime-directory name. RuntimeDirectoryMode=0700 makes the synthetic area private to the owning account. The worker records $RUNTIME_DIRECTORY; the controller independently expects %t/<runtime-name>. The systemd.exec table maps user RuntimeDirectory= paths to $XDG_RUNTIME_DIR, while the unit specifier table maps %t to that same user runtime root.

The fixture deliberately uses one plain managed directory: no symlink destination aliases, shared users, nested ownership schemes or mount substitutions. R01–R08 use Restart=no. R09–R10 use Restart=on-failure, RestartMode=normal and RestartSec=1s. Exit 17 is left out of SuccessExitStatus= and RestartPreventExitStatus=. Under v257, a nonzero exit is restartable with on-failure, while a systemd-initiated stop does not itself trigger that policy; RestartMode=normal is the default path through failed/inactive state.

Fix the ten-case expected manifest before execution

Write the oracle before starting any service. It must never learn expected values from what the worker happened to report. NULL below means “the file is expected to be absent,” not a zero-length file. Every row begins with a fresh unit and first-generation seed; every replacement invocation must have a different raw INVOCATION_ID. systemd documents INVOCATION_ID as a randomized 128-bit identifier represented by 32 hexadecimal characters and assigns a new one to each runtime cycle.

Before seeding, require the first receipt to say missing and independently confirm the runtime directory exists. The behavioral status of all ten rows is EXPECTED / NOT EXECUTED.

Case

Preserve policy

Operation

Stopped checkpoint

Replacement sentinel

Exact expected text

Status

R01

omitted

restart

not sampled

missing

NULL

EXPECTED / NOT EXECUTED

R02

no

restart

not sampled

missing

NULL

EXPECTED / NOT EXECUTED

R03

no

stop; inspect; start

directory absent

missing

NULL

EXPECTED / NOT EXECUTED

R04

restart

restart

not sampled

present

RUNTIME_SENTINEL:R04\n

EXPECTED / NOT EXECUTED

R05

restart

stop; inspect; start

directory absent

missing

NULL

EXPECTED / NOT EXECUTED

R06

yes

restart

not sampled

present

RUNTIME_SENTINEL:R06\n

EXPECTED / NOT EXECUTED

R07

yes

stop; inspect; start

directory and exact seed present

present

RUNTIME_SENTINEL:R07\n

EXPECTED / NOT EXECUTED

R08

yes

stop; clean runtime; start

present before clean; absent after

missing

NULL

EXPECTED / NOT EXECUTED

R09

restart

automatic restart after exit 17

not a manual-stop case

present

RUNTIME_SENTINEL:R09\n

EXPECTED / NOT EXECUTED

R10

no

automatic restart after exit 17

not a manual-stop case

missing

NULL

EXPECTED / NOT EXECUTED

The displayed \n denotes one newline byte in the fixture payload.

Give every generation an explicit receipt

The receipt schema is deliberately narrow:

Field

Required meaning

schema

integer 1

case_id

exact R01–R10 token

receipt_type

startup

invocation_id

raw runtime-assigned 32-hex $INVOCATION_ID

runtime_directory

worker-observed $RUNTIME_DIRECTORY

sentinel_state

missing, present, or error

sentinel_text

exact ASCII text for present; null for missing

sentinel_sha256

worker digest for present; null for missing

read_error

FileNotFoundError only for missing

monotonic_ns, utc

ordering key and UTC timestamp

The controller independently calculates the expected digest from the authored seed bytes and compares it with the worker digest. It also requires monotonic receipt ordering, distinct invocation IDs, one completed receipt per generation and the expected managed path. Each worker writes a temporary JSON file and atomically renames it inside the external evidence directory, so the controller never treats a partially written file as a receipt.

Authored schema example (not observed output):

{
  "schema": 1,
  "case_id": "R04",
  "receipt_type": "startup",
  "invocation_id": "<actual runtime-assigned 32-hex ID>",
  "sentinel_state": "present",
  "sentinel_text": "RUNTIME_SENTINEL:R04\n",
  "sentinel_sha256": "<digest of independently specified bytes>"
}

Never replace those placeholders with made-up identifiers or hashes. The eventual evidence package must contain the values captured from the run.

Show what the default policy removes

R01 and R02 are separate cases because “omitted” and explicit no should be demonstrated independently. Under the v257 baseline, no is documented as the default. For each case, start the unique service, wait for receipt one, require missing, confirm the expected runtime directory exists, then seed and independently verify the exact bytes and digest. Only then request systemctl --user restart <unit>.

Do not infer the replacement read from the return of systemctl restart. Type=exec only establishes successful execution of the service binary, and the replacement worker still has to reach its own read and atomic receipt. Wait for exactly one additional receipt, require a new INVOCATION_ID, and then evaluate its sentinel_state.

The expected result for R01 and R02 is missing. A newly existing runtime directory after the replacement activation is not evidence of preservation: systemd creates the managed directory when the unit starts. The question is whether sentinel.bin survived into that new generation, and the only acceptable “missing” classification is the worker’s FileNotFoundError paired with an independent path check.

A compact case controller can be built around these helpers; the complete connected controller below also drives all remaining cases:

#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import time

POLICY = {
    "R01": None,
    "R02": "no",
    "R03": "no",
    "R04": "restart",
    "R05": "restart",
    "R06": "yes",
    "R07": "yes",
    "R08": "yes",
    "R09": "restart",
    "R10": "no",
}

OP = {
    "R01": "restart",
    "R02": "restart",
    "R03": "stop-start",
    "R04": "restart",
    "R05": "stop-start",
    "R06": "restart",
    "R07": "stop-start",
    "R08": "clean",
    "R09": "auto",
    "R10": "auto",
}

EXPECT = {
    "R01": None,
    "R02": None,
    "R03": None,
    "R04": b"RUNTIME_SENTINEL:R04\n",
    "R05": None,
    "R06": b"RUNTIME_SENTINEL:R06\n",
    "R07": b"RUNTIME_SENTINEL:R07\n",
    "R08": None,
    "R09": b"RUNTIME_SENTINEL:R09\n",
    "R10": None,
}

def sh(cmd, raw, name, check=True):
    p = subprocess.run(cmd, text=True, capture_output=True)
    (raw / f"{name}.stdout").write_text(p.stdout)
    (raw / f"{name}.stderr").write_text(p.stderr)
    (raw / f"{name}.rc").write_text(str(p.returncode) + "\n")
    if check and p.returncode:
        raise RuntimeError(f"{name} rc={p.returncode}")
    return p

def receipts(ev):
    out = []
    for p in sorted(ev.glob("startup-*.json")):
        out.append(json.loads(p.read_text()))
    return sorted(out, key=lambda x: x["monotonic_ns"])

def wait_count(ev, n, deadline=15):
    end = time.monotonic() + deadline
    while time.monotonic() < end:
        rows = receipts(ev)
        if len(rows) == n:
            return rows
        if len(rows) > n:
            raise RuntimeError("extra generation")
        time.sleep(0.05)
    raise TimeoutError(f"expected {n} receipts")

def snap(path):
    if not path.exists():
        return {"state": "absent"}
    if path.is_dir():
        return {
            "state": "dir",
            "entries": sorted(p.name for p in path.iterdir()),
        }
    data = path.read_bytes()
    return {
        "state": "file",
        "bytes_hex": data.hex(),
        "sha256": hashlib.sha256(data).hexdigest(),
    }

def main(case, root, worker):
    if case not in POLICY:
        raise SystemExit("case must be R01..R10")

    run = root.name
    unit = f"rl-rtdp-{run}-{case}.service"
    rname = f"rl-rtdp-{run}-{case}"
    userdir = pathlib.Path.home() / ".config/systemd/user"
    unitpath = userdir / unit
    ev = root / case / "evidence"
    ctl = root / case / "control"
    raw = root / case / "raw"

    for d in (ev, ctl, raw):
        d.mkdir(parents=True, exist_ok=False)

    runtime = pathlib.Path(os.environ["XDG_RUNTIME_DIR"]) / rname
    if unitpath.exists() or runtime.exists():
        raise RuntimeError("preexisting unit/runtime path")

    py = pathlib.Path(sys.executable).resolve()
    userdir.mkdir(parents=True, exist_ok=True)

    lines = [
        "[Service]",
        "Type=exec",
        f"ExecStart={py} {worker} {case} {ev} {ctl}",
        f"RuntimeDirectory={rname}",
        "RuntimeDirectoryMode=0700",
    ]

    if POLICY[case] is not None:
        lines.append(f"RuntimeDirectoryPreserve={POLICY[case]}")

    if case in ("R09", "R10"):
        lines += [
            "Restart=on-failure",
            "RestartMode=normal",
            "RestartSec=1s",
        ]
    else:
        lines += ["Restart=no"]

    unitpath.write_text("\n".join(lines) + "\n")

    try:
        sh(
            ["systemctl", "--user", "daemon-reload"],
            raw,
            "daemon-reload",
        )
        sh(
            ["systemctl", "--user", "cat", unit],
            raw,
            "cat",
        )
        sh(
            [
                "systemctl",
                "--user",
                "show",
                unit,
                "--all",
                "--property=FragmentPath,DropInPaths,RuntimeDirectory,"
                "RuntimeDirectoryPreserve,Type,Restart,RestartMode,"
                "ExecStart,ActiveState,SubState",
            ],
            raw,
            "show-before",
        )

        sh(["systemctl", "--user", "start", unit], raw, "start1")
        rows = wait_count(ev, 1)
        first = rows[0]

        if (
            first["sentinel_state"] != "missing"
            or first["read_error"] != "FileNotFoundError"
        ):
            raise AssertionError("first generation not clean")

        if (
            pathlib.Path(first["runtime_directory"]) != runtime
            or not runtime.is_dir()
        ):
            raise AssertionError("runtime path mismatch")

        payload = f"RUNTIME_SENTINEL:{case}\n".encode("ascii")
        sentinel = runtime / "sentinel.bin"
        sentinel.write_bytes(payload)

        if sentinel.read_bytes() != payload:
            raise AssertionError("seed verification failed")

        (raw / "seed.sha256").write_text(
            hashlib.sha256(payload).hexdigest() + "\n"
        )

        op = OP[case]

        if op == "restart":
            sh(
                ["systemctl", "--user", "restart", unit],
                raw,
                "restart",
            )

        elif op == "stop-start":
            sh(
                ["systemctl", "--user", "stop", unit],
                raw,
                "stop",
            )
            sh(
                ["systemctl", "--user", "is-active", unit],
                raw,
                "inactive",
                check=False,
            )
            (raw / "stopped.json").write_text(
                json.dumps(snap(runtime), sort_keys=True) + "\n"
            )
            sh(
                ["systemctl", "--user", "start", unit],
                raw,
                "start2",
            )

        elif op == "clean":
            sh(
                ["systemctl", "--user", "stop", unit],
                raw,
                "stop",
            )
            (raw / "pre-clean.json").write_text(
                json.dumps(snap(runtime), sort_keys=True) + "\n"
            )
            sh(
                [
                    "systemctl",
                    "--user",
                    "clean",
                    "--what=runtime",
                    unit,
                ],
                raw,
                "clean-runtime",
            )
            (raw / "post-clean.json").write_text(
                json.dumps(snap(runtime), sort_keys=True) + "\n"
            )
            sh(
                ["systemctl", "--user", "start", unit],
                raw,
                "start2",
            )

        else:
            (ctl / "fail.request").write_text("exit=17\n")

        rows = wait_count(ev, 2, 20)

        if rows[0]["invocation_id"] == rows[1]["invocation_id"]:
            raise AssertionError("same invocation")

        expected = EXPECT[case]
        got = rows[1]

        if expected is None:
            assert got["sentinel_state"] == "missing"
            assert got["read_error"] == "FileNotFoundError"
        else:
            assert got["sentinel_state"] == "present"
            assert got["sentinel_text"].encode("ascii") == expected
            assert got["sentinel_sha256"] == hashlib.sha256(
                expected
            ).hexdigest()

        sh(
            [
                "systemctl",
                "--user",
                "show",
                unit,
                "--all",
                "--property=InvocationID,ActiveState,SubState,Result,"
                "ExecMainCode,ExecMainStatus,NRestarts",
            ],
            raw,
            "show-after",
        )

        if case in ("R09", "R10"):
            sh(
                [
                    "journalctl",
                    "--user-unit",
                    unit,
                    "--no-pager",
                    "-o",
                    "short-precise",
                ],
                raw,
                "journal",
            )

        (raw / "assertion.txt").write_text(
            "EXPECTED ORACLE MATCHED BY CONTROLLER CODE; RUN REQUIRED\n"
        )

    finally:
        sh(
            ["systemctl", "--user", "stop", unit],
            raw,
            "final-stop",
            check=False,
        )
        sh(
            [
                "systemctl",
                "--user",
                "clean",
                "--what=runtime",
                unit,
            ],
            raw,
            "final-clean",
            check=False,
        )
        if unitpath.exists():
            unitpath.unlink()
        sh(
            ["systemctl", "--user", "daemon-reload"],
            raw,
            "final-reload",
            check=False,
        )

if name == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("case")
    ap.add_argument("root")
    ap.add_argument("worker")
    args = ap.parse_args()

    main(
        args.case,
        pathlib.Path(args.root).resolve(),
        pathlib.Path(args.worker).resolve(),
    )

The final line written by this source is not evidence that the lab has run; it is merely what a successful future execution would write after assertions. The article’s current disposition remains HOLD.

Compare restart with a completed stop and start

R04 and R05 hold RuntimeDirectoryPreserve=restart constant and change the manager transaction. R04 uses systemctl --user restart. The expected replacement receipt contains exactly RUNTIME_SENTINEL:R04\n. R05 issues a blocking stop, inspects the stopped state, and only then starts again. The expected stopped checkpoint is an absent managed directory, and the replacement receipt is expected to report FileNotFoundError. This distinction follows the documented restart policy: preserve across restart operations, not across an ordinary completed stop.

R03 is the explicit-no stop/start control. It is expected to show the same stopped-directory absence as R05 and a missing sentinel after the later activation. That control matters because it separates “stop/start removes under restart policy” from any accidental artifact of the R05 implementation.

Do not explain the result as a property of shell punctuation such as && or ;. The independent variable is the lifecycle operation seen by the manager. The systemctl manual describes restart as stopping and then starting a unit, but also warns that restart does not necessarily flush every unit resource in the same way as a fully completed stop followed by start. For this article, the resource under test is specifically RuntimeDirectory= and its preservation directive.

Establish the stopped-state inspection barrier

For R03, R05, R07 and R08, use systemctl --user stop <unit> without --no-block. The v257 systemctl documentation notes that, unless --no-block is used, systemctl waits for queued jobs to finish. After stop returns, record ActiveState, SubState, worker termination evidence and the path inspection before any start. A nonzero stop status, an active unit, a competing activation or an unexpected extra receipt invalidates the case and yields HOLD.

Do not use inode numbers as the decisive oracle. An inode may change when a directory is removed and recreated, but the contract being approved is about exact marker presence and bytes at specific lifecycle checkpoints. That is why the controller records directory state while stopped and the next worker reports what it read before any later mutation.

Preserve across stops with an explicit yes policy

R06 and R07 test RuntimeDirectoryPreserve=yes. R06 uses a manual restart and is expected to preserve the seed into generation two. R07 performs a completed stop and, unlike restart, requires the stopped checkpoint itself to contain the managed directory and exact seed. After a later start, generation two is also expected to read the same bytes. The v257 manual defines yes as retaining the directories after the service stops.

That stronger retention transfers more cleanup responsibility to the operator. It does not validate whether stale state is safe for a replacement application instance, and it does not turn a runtime directory into durable storage. The systemd.exec documentation notes that for system services /run/ is tmpfs and runtime directories there are removed on reboot. This playbook does not execute reboot or logout tests and does not extrapolate a user-session survival result from that system-service observation.

If the bytes are irreplaceable business records, a runtime-directory retention switch is the wrong approval boundary. This fixture is intentionally about reconstructible runtime files whose maintenance semantics must be explicit. Durable-storage migration, backup design and crash-consistency are outside scope.

The service owner should therefore write the requirement in operational language before execution. An acceptable statement might be: “A manual restart and automatic failure restart may reuse this synthetic runtime marker, but a deliberate stop followed by start must begin without it.” That maps to restart, not yes. Another service may explicitly require retention across a stop, which maps to yes plus an owned cleanup procedure. The experiment supplies evidence for whichever contract is chosen; it does not choose for the product owner.

Trigger one controlled automatic restart

R09 and R10 establish whether the same retention distinction holds when the worker itself fails. Both use Restart=on-failure, RestartMode=normal and RestartSec=1s; R09 sets RuntimeDirectoryPreserve=restart, while R10 sets no. After first-generation receipt and seed verification, the controller writes one fail.request token outside the runtime directory. The worker atomically consumes that token and exits 17.

The v257 service manual states that Restart=on-failure includes a nonzero exit code, subject to exceptions such as RestartPreventExitStatus= and start-rate limiting. It also states that termination caused by systemd operations such as an operator stop is not itself restarted by Restart=. That is why systemctl stop, systemctl restart and an indiscriminate signal are not substitutes for this case. The failure has to be a controlled main-process exit whose status can be captured.

Use the one-second restart delay only as a laboratory pacing value, and use a bounded 20-second receipt deadline only to prevent a hung test. Neither is a production recovery latency promise. Capture journalctl --user-unit, Result, ExecMainCode, ExecMainStatus, NRestarts and both invocation receipts. The expected replacement in R09 contains the original seed; R10 is expected to report FileNotFoundError. Rate limiting, no recorded exit 17, extra invocations, a missed receipt or deadline exhaustion means HOLD, even if a later process happens to be running.

Keep the failure token outside RuntimeDirectory

If the “fail once” request lived inside the directory being deleted, R10 could erase the state that says failure was already requested. A replacement worker might then see an ambiguous control condition or repeat the failure. Instead, control/fail.request and its consumed rename live in the external case directory. The worker acknowledges consumption by atomically renaming the request before exiting, preserving evidence that generation one deliberately took the failure path.

Require exactly one additional startup receipt after the failure. Preserve the first generation’s raw failure evidence before cleanup. A running replacement alone is insufficient: the acceptance question is whether that replacement inherited the seeded marker under the configured retention policy.

Clean retained runtime files only after stopping

R08 starts fresh with RuntimeDirectoryPreserve=yes. After seeding, stop the unit, verify it is inactive, and prove that both the managed directory and exact marker remain. Then run only:

systemctl --user clean --what=runtime rl-rtdp-<run>-R08.service

The v257 systemctl manual says clean removes selected per-unit resources, requires the specified unit to be stopped, and maps --what=runtime to RuntimeDirectory=. It also documents that omitting --what= uses a broader default that includes cache, runtime and file-descriptor-store resources; clean was added in version 243. This procedure therefore names --what=runtime explicitly. It does not use --what=all, an unspecified default or broad filesystem deletion.

After a zero return, inspect the runtime path and require it to be absent. Confirm that the external evidence directory is still readable. Then start the unit and require generation two to report a missing sentinel in a newly available managed directory. A successful clean is an action on stopped resources; it does not retroactively repair an earlier bad receipt or convert incomplete evidence into a pass.

Keep the unit definition loaded until this cleanup completes. systemctl clean acts on resources associated with a unit’s settings, so removing the unit file first weakens the evidence and cleanup path. If clean fails, retain its stdout, stderr, return code and path snapshot, classify the fixture as RECONCILE, and do not claim the disposable VM is clean.

This is also why the article does not reuse the timer article’s clean --what=state operation. A timer’s persistent timestamp state is a different resource class. Here the authority is the service’s RuntimeDirectory= and only the runtime class is selected.

Reconcile loaded policy, paths and receipts

A valid result joins what the unit files say, what the running manager normalized, what operation was requested and what each generation actually read. Capture both systemctl --user cat <unit> and systemctl --user show <unit>. The v257 manual says cat shows backing files and drop-ins, while show exposes low-level normalized properties and runtime state. Keep FragmentPath, DropInPaths, RuntimeDirectory, RuntimeDirectoryPreserve, Type, Restart, RestartMode, ExecStart, ActiveState, SubState, InvocationID, Result and restart counters relevant to the case.

Hash worker.py, controller.py and every generated unit before execution. After any intentional unit edit, run and capture systemctl --user daemon-reload; otherwise the backing file and manager-loaded configuration may diverge. The evidence ledger should have one row per case containing run token, exact unit, policy, operation, first and replacement invocation IDs, checkpoint state, replacement marker state, expected digest, observed digest, command return codes, unit/source hashes and disposition.

This fixture deliberately closes its sentinel read immediately, so there is no open descriptor that can keep content “alive” independently of the pathname lifecycle. For that different diagnostic problem, see logrotate file-descriptor validation.

Distinguish missing files from failed reads

Only FileNotFoundError supports sentinel_state=missing in this fixture. PermissionError, another I/O error, invalid ASCII, malformed JSON, a wrong runtime path or a receipt that disappears all mean something different and yield HOLD. A missing evidence file is never evidence of a missing sentinel.

Before making a decision, validate: exactly R01–R10 are present once in the ledger; expected receipt counts match the operation; case IDs and unit names agree; first-generation receipts are clean; later invocation IDs differ; present text equals the independently specified bytes; digests agree; and the worker-reported runtime path equals the controller’s expected $XDG_RUNTIME_DIR/<name>. Reject duplicates, unknown generations and out-of-order receipts rather than “fixing” the manifest to match them.

That discipline exposes alternatives to the intended lifecycle: a stale preexisting marker, a worker that rewrote the file, a competing activation, an un-reloaded unit, a read permission failure or a cleanup operation aimed at the wrong resource class. The ledger should make each such failure visible rather than collapsing every anomaly into “file missing.”

Recover without rewriting the evidence

Recovery begins by freezing history, not by making the directory look clean. Copy or archive the original manifest, receipts, unit contents, command stdout/stderr/return codes, journal capture, source hashes and cleanup snapshots before remediation. Never edit a receipt, delete a contradictory row, or reseed the same case to obtain a prettier outcome. A new synthetic seed starts a new case identity.

Stop only the exact fixture units recorded in the created-resource inventory. While their definitions still exist, use systemctl --user clean --what=runtime <exact-unit> for retained runtime resources. Then remove only the owned unit files, run systemctl --user daemon-reload, and verify the recorded runtime paths and unit fragments are gone. Do not use wildcard unit names or wildcard filesystem deletion. If cleanup fails or ownership of a path is uncertain, create a reconciliation record and leave the overall state RECONCILE rather than declaring success.

A missing path can sometimes be caused by an obscuring mount rather than deletion, but mounts are intentionally excluded from this fixture. The separate Docker bind mounts and hidden runtime files article covers that diagnosis boundary; do not add bind mounts to this lifecycle test.

Configuration rollback is a separate action. If a maintenance change moved from restart to no, restoring the previous unit policy can change future lifecycle behavior after reload, but it cannot recreate sentinel.bin bytes that were already removed. REVERT therefore requires an identified previous configuration revision and a fresh validation run. Do not describe rollback as data recovery.

A disposable VM can simplify final teardown, but that does not excuse poor evidence hygiene. The acceptance artifact should remain intelligible even if the VM is later destroyed: manifest, case inventory, manager/client versions, sources, unit definitions, receipts, command records and final decision must be sufficient to explain what was tested.

Apply the acceptance and repair matrix

Use the ledger against case-specific predicates rather than a single “all commands succeeded” flag.

Decision

Predicate

Action

ACCEPT

All required cases executed on the intended manager; loaded policy and operation match the manifest; receipt/checkpoint bytes match the authored oracle; no unexplained generations or read errors

Approve that exact retention policy and maintenance sequence for the tested scope

REPAIR

Evidence is complete and valid, but the observed lifecycle defeats the owner’s declared retention requirement

Change policy or maintenance procedure; preserve old evidence; rerun as new validation

HOLD

User manager unavailable; case not executed; manager/version baseline uncertain; command failed; deadline/rate limit hit; evidence incomplete or contradictory

Do not approve; resolve the evidence gap first

RECONCILE

Retained runtime resources, unit ownership or cleanup state cannot be accounted for

Inventory exact created resources and clean only what is proven owned

REVERT

An intentional policy change has an identified previous revision and the change must be backed out

Restore that revision, reload, then perform a new validation; do not claim deleted bytes returned

A deliberate counterexample can prove the experiment is sensitive without approving the counterexample for production. For example, R05 is expected to demonstrate that RuntimeDirectoryPreserve=restart does not preserve the marker through a fully completed stop followed by a later start. That expected “failure to retain” is a successful control if the declared product requirement is to distinguish restart from stop/start.

The current article has no executed ledger. Therefore no case is ACCEPT, even though the manifest is fully specified and the code contains independent assertions. The overall release disposition is HOLD: EXPECTED / NOT EXECUTED. A syntactically valid script, a zero-returning systemctl command or a documentation-derived expectation is not measured acceptance evidence.

Assign operational ownership and revalidation triggers

Assign three named roles before production approval. The service owner defines what the marker means and whether retained bytes are allowed to influence a replacement process. The administrator owns the exact lifecycle command sequence, loaded unit policy and stopped-unit cleanup procedure. The reviewer verifies that the evidence package is complete, case identities are unique and the observed ledger matches the predeclared oracle.

The handoff should record one compact set of facts:

  1. Approved RuntimeDirectoryPreserve= value, including whether omission is intentional.

  2. Approved maintenance sequence: restart, completed stop then start, or another explicitly validated path.

  3. Exact unit identity and managed runtime-directory name.

  4. Evidence artifact location, source/unit hashes and manager/client version captures.

  5. Cleanup owner and exact systemctl --user clean --what=runtime <unit> procedure where retention can outlive stop.

  6. Previous configuration revision for REVERT and unresolved questions requiring HOLD.

Revalidate after a systemd manager/package change, unit or drop-in change, restart-strategy change, worker initialization change, runtime path change or cleanup-procedure change. A passing synthetic case does not create an untested operating-system or application guarantee; it supports only the lifecycle contract represented by the fixture and recorded environment.

This kind of explicit ownership is part of broader system administration skills and practical projects: operational work joins configuration, command-line execution, troubleshooting and recovery with evidence that another engineer can review. It is more valuable here than memorizing that one directive has three values, because maintenance automation often hides the actual transaction behind a generic word such as “restart.”

Develop stronger Linux operational skills

The same discipline behind this handoff (knowing which manager you are controlling, capturing command evidence, understanding file lifecycle and separating rollback from recovery) depends on solid Linux and systems-administration fundamentals.

Refonte Learning’s System Administration Program currently describes Windows/Linux systems, command-line work, troubleshooting, backup/recovery, networking, security, virtualization, cloud management and a capstone project; its Linux Administration Essentials section specifically mentions file management, user administration and networking. The page also describes labs and practical projects. It lists an educational mentor and a “Potential Internship,” and says successful completion yields a Training Certificate and Certificate of Internship. These descriptions do not guarantee an internship, placement, salary or employment.

The same page currently presents conflicting duration information: its main details say six months and 10–12 hours per week, while a lower System Administration card says three months. It also pairs a top requirement of basic computer/network knowledge with a later admission block requiring the applicant to be working toward a bachelor’s or higher degree. Confirm the duration, eligibility requirements and any specialized systemd coverage with the program team before enrolling.

The practical next step for this article’s reader is narrower: run the ten-case fixture on the intended disposable user-manager VM, preserve the resulting evidence-backed lifecycle decision, and assign an owner to the retention and cleanup contract before changing maintenance automation.