Skip to content

v0.6.1: restart grants a second whole-card lease before a live pinned/training runner observes EOF #354

Open

Description

@spinninghypercube

Restart can grant a second whole-card lease before a live pinned runner notices EOF

Status

Reproduced on the official Linux amd64 v0.6.1 release, SHA256
f2c68deaccc9e198c66de2e6c67b1063641661e463c9197de9a62f779b1c8f4d.
Checked on 2026-11-20: this remains the latest official release.
Upstream main at 13952aa2b16037c2671a1d8ff81a43309d354af9 has no
runner/broker/runs changes relative to that release; main was not built or tested.

This blocks our production integration. No Berth source or installed binary
has been changed. This document records a failing release qualification,
not a recovery fix.

Reproduction and isolation

Linux, AMD backend on an RDNA4 discrete GPU. The broker and both runners
run as the same unprivileged UID, using the same literal socket path,
configuration and private state directory. No containers or socket aliases.
Engine discovery and builtin claims are disabled.

  1. Start an isolated broker and a whole-card berth run --pinned --fail-closed
    whose CPU-only child writes a heartbeat until explicitly released.
  2. SIGSTOP only that runner, leaving its child running. Verify that the
    child's heartbeat advances. This makes delayed EOF processing deterministic.
  3. Terminate or SIGKILL the isolated broker, then start it again with identical
    arguments and state.
  4. Submit a second whole-card pinned run. Its child records whether the first
    child has completed, then stays alive so the leases can be inspected.
  5. Resume the first runner and wait for its successful reattach.
  6. Verify the first child's heartbeat still advances; inspect both leases.
    Release the first child, then let the second exit and clean up the fixture.

The children intentionally allocate no GPU memory. This tests admission
before allocation and cannot cause two GPU workloads to collide. A granted
whole-card lease must protect the loading/pre-allocation phase as well.
The test does not restart the installed broker or send requests to applications.

Results

Mode Broker action Reattach window Result
run --pinned --fail-closed No restart, sequential control 15s PASS: second run waits
run --pinned --fail-closed SIGTERM, restart 15s REJECT: overlapping grants
run --pinned --fail-closed SIGKILL, restart 15s REJECT: overlapping grants
run --pinned --fail-closed SIGKILL, restart 5m REJECT: overlapping grants
train for both runs No restart, sequential control 15s PASS: second training waits
train for both runs SIGKILL, restart 15s REJECT: overlapping training grants

The first runner successfully reattaches. This is not a refused reattach,
an exited runner, expired recovery timeout, insufficient declared memory, or
inability to read another user's recovery records. After reattachment the
status contains two live pinned whole-card leases; the first child is still
making progress and the second has already recorded OVERLAP.

Example timeline from the SIGKILL/15s run:

13:01:52.594 granted qualification-active-1; attached first child
13:01:52.679 replacement berthd up
13:01:52.702 granted qualification-next-2; second child starts
               first runner resumed, reports lost berthd (EOF)
13:01:54.729 reattached qualification-active-3, same first child
               status: two pinned leases; first child not done; OVERLAP
13:01:54.782 first child released after test allows it to finish
13:01:54.800 second child released

Cause and native controls considered

In internal/runner/runner.go, record() is called only after listen()
reports the lost connection. Before the stopped runner notices EOF there is
no unprotected-run record. internal/broker/broker.go populates b.runs from
those records; reattaching() therefore returns zero, and schedule() grants
the contender immediately, inside the configured recovery window.

The training flag extends protection for an existing record, but cannot
protect a record that has not been written. It also deliberately refuses
ordinary requests rather than preserving them as waiters.

Other documented controls do not provide an atomic recovery boundary:

  • A larger --reattach-window does not create the missing record (5m tested).
  • --fail-closed prevents an initial unleased start, but a running child
    intentionally survives broker loss.
  • cordon is cleared on daemon restart. Applying it after startup leaves a
    grant race.
  • Process hold claims are scanned asynchronously and acquire their holds in
    goroutines; they are not a pre-listen recovery barrier.
  • Delaying a systemd restart cannot prove that an arbitrarily delayed runner
    has observed EOF. Waiting for services to exit instead can block indefinitely
    on persistent inference engines.

A separate adapter that recreated the missing durable ownership/recovery
registry would duplicate the scheduler's responsibility. Writing Berth's
internal record files from that adapter would couple it to an internal
interface. Neither is the native-updateable solution sought here.

Expected upstream contract and regression coverage

Recover outstanding authorization before granting new whole-card work,
independently of when a live runner observes EOF. Preserve the running child.
A fix must also account for the grant-to-attach interval, repeated crashes,
and a dead runner whose child is still alive; merely recording after child
startup leaves another interval to consider.

check-recovery.py is the executable reproducer and release gate. For example:

python3 check-recovery.py /path/to/official/berth --pci YOUR_GPU_PCI --stop none
python3 check-recovery.py /path/to/official/berth --pci YOUR_GPU_PCI --stop term
python3 check-recovery.py /path/to/official/berth --pci YOUR_GPU_PCI --stop kill
python3 check-recovery.py /path/to/official/berth --pci YOUR_GPU_PCI --stop kill --reattach-window 5m
python3 check-recovery.py /path/to/official/berth --pci YOUR_GPU_PCI --mode train --stop kill

Run as an ordinary user with AMD sysfs read access. The test exits nonzero
on overlap and always releases its CPU fixtures. qualify.py now checks
the sequential control, graceful restart and crash before hardware scenarios;
it stops at the first failure. The already-tested render/queue path is not
evidence that this release passed the restart gate.

Related upstream discussion: #300 concerns lost-run recovery, but this case
keeps the original runner alive and successfully reattaches it. The new grant
has already occurred by that point.

Standalone check-recovery.py
#!/usr/bin/env python3
"""Release check: contender must not start while an old pinned child is alive.

Run as an ordinary user with read access to AMD sysfs. Own socket, same UID
and paths for all three processes. The workload is a CPU marker, never a
second GPU allocation. No network listener and no production broker restart.
"""
import argparse
import json
import os
from pathlib import Path
import signal
import subprocess as sp
import sys
import tempfile
import time


def until(test, seconds, message):
    end = time.monotonic() + seconds
    while time.monotonic() < end:
        if test():
            return
        time.sleep(0.025)
    raise RuntimeError(message)


def check(binary, pci, directory, *, stop="term", mode="run", window="15s"):
    cards = list((Path("/sys/bus/pci/devices") / pci / "drm").glob("card[0-9]*"))
    if len(cards) != 1:
        raise RuntimeError("expected exactly one DRM card at " + pci)
    d = Path(directory)
    config = d / "check.toml"
    socket = str(d / "check.sock")
    config.write_text('[engines]\ndiscover=false\n[claims]\nbuiltin=false\n'
                      '[priority]\njuggle_window="-1s"\n[update]\ncheck=false\n')
    env = {**os.environ, "HOME": directory, "XDG_STATE_HOME": directory,
           "XDG_CONFIG_HOME": directory}
    common = ["--socket", socket, "--config", str(config)]
    def daemon():
        return sp.Popen([binary, "daemon", *common, "--gpu-backend", "amd",
                         "--gpu", cards[0].name[4:], "--devices", "", "--schedule", "",
                         "--poll", "250ms", "--reattach-window", window], env=env)
    def status():
        r = sp.run([binary, "status", "--socket", socket, "--format", "json"],
                   env=env, capture_output=True, check=True, timeout=3)
        return json.loads(r.stdout)
    def ready():
        return sp.run([binary, "status", "--socket", socket, "--format", "json"],
                      env=env, capture_output=True, timeout=3).returncode == 0
    def runner(name, code):
        flags = ["--fail-closed", "--pinned", "--wait", "30s"] if mode == "run" else []
        return sp.Popen([binary, mode, *common, "--as", name, *flags,
                         "--", sys.executable, "-c", code],
                         env=env, cwd=directory)
    broker = daemon()
    first = second = None
    marker = d / "marker"
    release = d / "release"
    release_second = d / "release-second"
    done = d / "done"
    heartbeat = d / "heartbeat"
    try:
        until(ready, 10, "fixture broker did not start")
        first = runner("qualification-active",
                       "import pathlib,time\np=pathlib.Path\np('started').touch()\n"
                       "while not p('release').exists():\n"
                       " p('heartbeat').write_text(str(time.monotonic_ns()))\n"
                       " time.sleep(.02)\np('done').touch()")
        until((d / "started").exists, 10, "first worker did not start")
        until(heartbeat.exists, 3, "first worker has no heartbeat")
        # A live worker can continue while its launcher has not yet observed
        # EOF from the old broker. Make that ordering deterministic.
        if stop != "none":
            first.send_signal(signal.SIGSTOP)
            before = heartbeat.stat().st_mtime_ns
            until(lambda: heartbeat.stat().st_mtime_ns > before, 3,
                  "stopping the launcher also stopped the child")
            broker.send_signal(signal.SIGTERM if stop == "term" else signal.SIGKILL)
            broker.wait(timeout=8)
            broker = daemon()
            until(ready, 10, "fixture broker did not restart")
        second = runner("qualification-next",
                        "from pathlib import Path as P\nimport time\n"
                        "P('marker').write_text('after' if P('done').exists() else 'OVERLAP')\n"
                        "while not P('release-second').exists():time.sleep(.02)")
        def waiting_or_started():
            state = status()
            if any(x["engine"] == "qualification-next" for x in state["leases"] or []):
                until(marker.exists, 5, "granted contender never started")
            return marker.exists() or any(x["engine"] == "qualification-next"
                                          for x in state["waiting"] or [])
        until(waiting_or_started, 10, "contender did not reach broker")
        if stop != "none":
            first.send_signal(signal.SIGCONT)
        def reconciled_or_overlapped():
            state = status()
            return (any(x["engine"] == "qualification-active" for x in state["leases"] or [])
                    and (marker.exists() or any(x["engine"] == "qualification-next"
                                                for x in state["waiting"] or [])))
        until(reconciled_or_overlapped, 20, "incumbent did not reattach with the contender waiting")
        before = heartbeat.stat().st_mtime_ns
        until(lambda: heartbeat.stat().st_mtime_ns > before, 3, "incumbent stopped making progress")
        state = status()
        print(json.dumps({"mode": mode, "stop": stop, "reattach_window": window,
                          "child_progress": True, "done": done.exists(),
                          "marker": marker.read_text() if marker.exists() else None,
                          "leases": [{"engine": x["engine"], "pinned": x.get("pinned"),
                                      "training": x.get("training", False)}
                                     for x in state["leases"] or []],
                          "waiting": [x["engine"] for x in state["waiting"] or []]}), flush=True)
        release.touch()
        first_code = first.wait(timeout=15)
        release_second.touch()
        second_code = second.wait(timeout=35)
        if first_code or second_code:
            raise RuntimeError("one of the test runners failed")
        if not done.exists() or marker.read_text() != "after":
            raise RuntimeError("REJECT: new lease started before the existing pinned child completed")
    finally:
        release.touch()
        release_second.touch()
        if first is not None and first.poll() is None:
            first.send_signal(signal.SIGCONT)
        for proc in (first, second, broker):
            if proc is not None and proc.poll() is None:
                proc.terminate()
                try:
                    proc.wait(timeout=8)
                except sp.TimeoutExpired:
                    proc.kill()
                    proc.wait()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("binary", type=lambda p: str(Path(p).resolve(strict=True)))
    parser.add_argument("--pci", default="0000:05:00.0")
    parser.add_argument("--stop", choices=["term", "kill", "none"], default="term",
                        help="restart via SIGTERM/SIGKILL, or sequential control without restart")
    parser.add_argument("--mode", choices=["run", "train"], default="run")
    parser.add_argument("--reattach-window", default="15s")
    args = parser.parse_args()
    if os.geteuid() == 0:
        sys.exit("run under the unprivileged broker user")
    with tempfile.TemporaryDirectory(prefix="berth-recovery-") as tmp:
        try:
            check(args.binary, args.pci, tmp, stop=args.stop, mode=args.mode,
                  window=args.reattach_window)
        except (OSError, RuntimeError, sp.SubprocessError) as exc:
            sys.exit(str(exc))
    print("PASS: pinned child finished before contender started")

Activity

  1. T-Crypt commented on Nov 20, 2026

    @T-Crypt
    Owner

    Thanks for the reproducer and for isolating it to the gap between the lost daemon and the wrapper noticing.

    You found the right cause. berth run wrote its unprotected-run record only after listen() reported the lost connection. A wrapper stopped with SIGSTOP never got there, so the new daemon had no record, reattaching() returned zero, and schedule() granted at once. The re-attach then succeeded because a re-attach has no fit check, which is why the run looked healthy while two pinned leases were live.

    #355 changes the record so it covers the whole life of the engine. The wrapper writes it when the child starts, rewrites it with the reason when the daemon goes away, clears the reason after a successful re-attach, and removes it when the child exits. berthd counts every live record it has no lease for as due back, so a wrapper that is stopped or slow cannot hide its engine. A training record still holds with no timer, and a keep-up record holds nothing because that drain freed the card on purpose.

    The tests that were red before the change:

    • TestLiveRunHoldsTheCardUntilItReattaches writes your state directly: a record with no reason, no lease, and a whole-card contender. It was granted before, and now waits with berthd restarted.
    • TestTrainingLocksTheCardUntilItReattaches now covers both record shapes, one that has noticed the lost daemon and one that has not.
    • TestReattachAfterDaemonRestart now asserts the record exists before the daemon stops, not only after the wrapper sees EOF.

    One interval is still open, and I want to be clear about it. If berthd dies between the grant and the child start, no process exists yet, so no runner record can describe it, and a contender can still be granted. Closing that needs a grant record written by berthd before it replies, which is a different change. It is not what your reproducer hits, because the SIGSTOP happens after the first child is alive.

    The other bound is the re-attach window itself. A wrapper stopped for the whole window, and then resumed after a contender was granted, would still overlap. Training has no such bound. Your 5 m case resumes the first runner within seconds, so it passes with the record in place.

    The fix is on main (5ab7466) and next (066f2b4) but not in a tagged release yet. If you build from main, or wait for the next pre-release, check-recovery.py should pass every row of your table. I'd like your rerun on real RDNA4 hardware before I call this closed.

  2. spinninghypercube commented on Nov 21, 2026

    @spinninghypercube
    Author

    RDNA4 rerun of #354 against #355 — 2026-11-21

    Thanks for the fix and the precise description of its remaining bounds.
    Confirmed on the real RDNA4 host: every row of the original table passes on
    5ab7466054bd93e76353b070fdf3fd1828fafde4, three repetitions per row (18/18).

    I also reran the same unchanged reproducer against official v0.6.1 on the
    same host: both no-restart controls pass, and all four restart cases still
    reproduce overlapping whole-card grants.

    Environment and exact artifact

    • AMD Radeon AI PRO R9700, RDNA4/gfx1201, PCI ID 1002:7551,
      address 0000:05:00.0; real AMD backend/sysfs, not a mock.
    • Linux 7.0.14-30-pve, linux/amd64.
    • Clean upstream checkout at the exact merge commit above; no source changes.
    • Built with Go 1.27.1:
      go build -trimpath -o /tmp/opencode/berth-5ab7466 ./cmd/berth.
    • go version -m confirms that revision and vcs.modified=false.
      Reported version: 0.6.2-0.20261120205857-5ab7466054bd.
    • Built binary SHA256:
      6cd0ad61bc5ea8f0840d2a26d6307536ab09621cfbe9b0c0009e2c7d96f2a0e1.
    • Official v0.6.1 control SHA256:
      f2c68deaccc9e198c66de2e6c67b1063641661e463c9197de9a62f779b1c8f4d.
    • Original, unchanged check-recovery.py SHA256:
      c46cf2cfe90c7f6ff5b767b9910cfbba31728370ce67e87a59c60208a58a435b.

    Each invocation used a fresh private state directory. The broker and both
    wrappers ran as the same unprivileged UID 997, with the same literal socket
    path. Discovery and built-in claims were disabled, juggle_window="-1s",
    AMD polling was 250 ms. Only the first wrapper was SIGSTOPped; its original
    child kept advancing its heartbeat.

    As in the original report, the children are CPU markers, with no GPU memory
    allocation
    . This is the same pre-allocation admission reproducer running
    against the physical AMD backend, not an inference/render or VRAM stress test.

    Results

    Mode Broker action Reattach window Official v0.6.1, fresh control 5ab7466
    run --pinned --fail-closed No restart 15s PASS PASS 3/3
    run --pinned --fail-closed SIGTERM/restart 15s OVERLAP PASS 3/3
    run --pinned --fail-closed SIGKILL/restart 15s OVERLAP PASS 3/3
    run --pinned --fail-closed SIGKILL/restart 5m OVERLAP PASS 3/3
    train for both runs No restart 15s PASS PASS 3/3
    train for both runs SIGKILL/restart 15s OVERLAP PASS 3/3

    For every fixed restart case, the contender remained queued before the first
    wrapper noticed EOF. The original child continued running, then reattached
    successfully; the observed state had exactly one pinned incumbent lease and
    one waiting contender. The contender's child started only after the original
    child completed (marker="after", never OVERLAP); both wrappers exited 0.

    Representative SIGKILL/15s timeline from the fixed build (host time UTC+01:00):

    21:05:33.151 granted qualification-active-1
    21:05:33.152 attached original child pid=2736696
    21:05:33.237 replacement berthd up
    21:05:33.261 acquire qualification-next-2
                 waiting: berthd restarted; waiting up to 15s for 1 running engine(s) to re-attach
                 UNPROTECTED: lost berthd (EOF); qualification-active keeps running
    21:05:35.293 reattached qualification-active-3, same child pid=2736696
                 contender waiting: held by qualification-active [interactive, pinned, active]
    21:05:35.361 incumbent released, after the test allowed its child to complete
    21:05:35.493 incumbent lease freed
    21:05:35.493 contender granted (waited=2.231s)
    

    Reproduce

    Run as the unprivileged user; B is the built binary:

    python3 check-recovery.py "$B" --pci 0000:05:00.0 --stop none
    python3 check-recovery.py "$B" --pci 0000:05:00.0 --stop term
    python3 check-recovery.py "$B" --pci 0000:05:00.0 --stop kill
    python3 check-recovery.py "$B" --pci 0000:05:00.0 --stop kill --reattach-window 5m
    python3 check-recovery.py "$B" --pci 0000:05:00.0 --mode train --stop none
    python3 check-recovery.py "$B" --pci 0000:05:00.0 --mode train --stop kill

    I additionally ran the four focused upstream regressions on the build host;
    all passed:

    • TestLiveRunHoldsTheCardUntilItReattaches
    • TestRecordForALeasedRunHoldsNothing
    • TestTrainingLocksTheCardUntilItReattaches, both record-shape subtests
    • TestReattachAfterDaemonRestart

    This confirms the original live-child/delayed-EOF race is fixed in this
    commit. It does not cover a crash between grant and child start, or resuming an
    ordinary wrapper after the entire reattach window has expired. In the 5m test,
    reattachment occurred within seconds, as in the original report. I did not
    independently build/test the next cherry-pick.

    The production binary, broker and Harbor were untouched: checksum, service PIDs,
    restart counters and activation timestamps were identical before/after.
    All fixture processes were cleaned up; production remained idle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions