Skip to content

Block experiment restart while a saved cleanup failure remains unresolved #1

Closed

Description

@gpu004

Summary

Rerunning an experiment bypasses its saved cleanup warning. The first invocation correctly records cleanup="failed" or "creation_unconfirmed" and stops. The next invocation treats that row as completed work, skips it, and launches the next scheduled attempt without checking whether cleanup was resolved.

The stop is currently an invocation-level check, not a durable experiment-level safety rule.

Affected code and verification

Confirmed against published commit 9cb4499, not just an unpublished refactor:

The same control flow was reproduced in the local refactor, where scheduling lives in scenarios.py and the lifecycle lives in lifecycle.py. Those files are not present at the linked published commit.

Failure path

The bounded TLA+ check names the desired rule RecordedFailureBlocksLaunch: An unresolved saved cleanup warning must block new allocations until its resolution is recorded.

Its shortest counterexample is:

  1. The experiment is ready.
  2. A provider allocates the first box.
  3. Cleanup fails or cannot be confirmed.
  4. The runner saves the warning row to attempts.jsonl.
  5. The runner stops and asks for inspection.
  6. The operator reruns the same command without resolving cleanup.
  7. Startup skips the saved attempt, then allocates the next box.
stateDiagram-v2
    [*] --> Allocated
    Allocated --> WarningSaved: cleanup unresolved, result saved
    WarningSaved --> Stopped: runner raises
    Stopped --> Skipped: same experiment rerun
    Skipped --> NewAllocation: saved key skipped, next attempt launches
Loading

The local fault-injection replay left the first fake box live and observed the next allocation while that box still existed. It confirmed both "failed" and "creation_unconfirmed".

Expected behavior and impact

Before launching any new scheduled work, startup should refuse to proceed if this experiment has an unresolved cleanup warning. An error should identify the affected attempt, provider, known box ID, and recovery action.

A cleanup warning does not prove that a box remains live. It means the runner lacks a confirmed safe outcome. When a box does remain live, continuing can consume quota, incur charges, or affect later measurements through concurrent resource use. This is possible overlap, not a claim of permanent leakage for every provider error.

Proposed solution

1. Add a startup check under the existing experiment lock

Read the saved rows once, inspect unresolved cleanup outcomes, and only then build the completed-attempt set. Perform the check before applying date, workload, or provider scheduling filters. A warning from an earlier block must not disappear merely because today's schedule skips that block.

Illustrative ordering, not a patch ready to apply:

with experiment_lock:
    rows = read_rows(attempts_path)
    resolutions = read_cleanup_resolutions(...)
    unresolved = unresolved_cleanup(rows, resolutions)
    if unresolved:
        raise CleanupNeedsAttention(unresolved)
    done = completed_attempt_keys(rows)
    # Only now select and run new work.

Use one definition of an unresolved outcome for both the existing post-attempt check and startup. Keep setup-error handling explicit rather than accidentally changing it while adding this check. Do not classify unsupported operations or intentionally retained existing boxes as leaked disposable boxes.

A blocking check is the small first fix. It does not require building automated remote cleanup in the same change.

2. Record resolution without rewriting measurement history

Provide a separate durable recovery record keyed to the exact original attempt or allocation. A later resolution must not turn the original failed measurement into a successful one.

An initial explicit recovery command could:

  1. Show the unresolved allocation and verified ownership information.
  2. Retry cleanup of that exact allocation, or verify a provider-supported terminal absence outcome.
  3. Persist the confirmed resolution.
  4. Allow a later run to continue.

Write recovery information separately from measurement rows, or introduce a schema that reports understand. Appending a second ordinary attempt row as a cleanup receipt would duplicate samples in the existing readers.

The recovery state should eventually share the interrupted-allocation journal described in #2. Avoid maintaining two competing definitions of whether an allocation is safe.

3. Keep uncertain recovery blocked

A failed lookup, temporary provider error, or ambiguous match must not count as successful cleanup. A provider returning no match can also be inconclusive after a lost creation response.

Do not delete arbitrary boxes based on a before/after list difference. Do not clear the warning merely because the command was rerun, the error was acknowledged, or an unverified TTL elapsed. An explicit manual-resolution path should retain who resolved the warning, when, what evidence was used, and the exact allocation scope.

Regression tests and acceptance criteria

  • Persist a row with cleanup="failed", rerun the same experiment, and assert zero new provider create calls.
  • Repeat for cleanup="creation_unconfirmed".
  • Verify that the block applies even when the warned row belongs to an earlier day or has a key that the new schedule would skip.
  • Confirm that the original invocation still writes its failure row before stopping.
  • Confirm that successful recorded attempts remain skipped and healthy experiments continue normally.
  • Resolve the exact allocation, persist that resolution, restart again, and confirm that the next eligible attempt can run.
  • Confirm that recovery does not delete another attempt's box or modify the original measurement row.
  • Make resolution persistence fail and confirm that the experiment remains blocked.
  • Keep setup-error and unsupported-operation behavior covered separately.
  • Recheck RecordedFailureBlocksLaunch in the bounded model after adding the startup rule.

Safe, standalone reproducer

Save the script below as reproduce_restart.py outside the checkout, then run from the repository root with the project's Python environment:

python /path/to/reproduce_restart.py --repo "$PWD" --fault failed
python /path/to/reproduce_restart.py --repo "$PWD" --fault unconfirmed
python /path/to/reproduce_restart.py --repo "$PWD" --fault none

On the affected code, the first two commands print CONFIRMED ... rerun allocated a new box with box-1 still live. The healthy control prints PASS. The script also supports --fault kill for the interrupted-allocation path in #2.

The script runs actual scheduling, lifecycle cleanup, locking, and result persistence. Only the external Sandbox adapter is replaced. No credentials, provider CLIs, or remote boxes are used. Fake allocation files survive between child runner processes. The script prints their evidence directory and preserves it for inspection.

The assertions describe the existing bug, not the behavior a regression test should accept after the fix. Once startup correctly refuses to launch, the affected-path reproducer should stop confirming the bug.

Reproducer source, tested on published main and the local refactor
"""Safe reproducer: local fake boxes only; SIGKILL targets only a child runner."""
import argparse
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
from types import SimpleNamespace
from unittest.mock import patch

parser = argparse.ArgumentParser()
parser.add_argument("--repo", type=Path, default=Path.cwd())
parser.add_argument("--fault", choices=["failed", "unconfirmed", "kill", "none"], required=True)
parser.add_argument("--worker", type=Path)
args = parser.parse_args()
repo = args.repo.resolve()
sys.path.insert(0, str(repo))
if (repo / "scenarios.py").exists():
    import scenarios as runner
    import lifecycle as session
else:
    import benchpress as runner
    session = runner


def records(root):
    path = root / "cloud.jsonl"
    return [json.loads(s) for s in path.read_text().splitlines()] if path.exists() else []


def worker(root):
    class FakeBox:
        version = "local-fake"

        def __init__(self, provider, config, name, **kwargs):
            self.id = None
            self.name = name
            self.provider = provider

        def launch(self, timeout):
            self.number = len(records(root)) + 1
            self.remote_id = f"box-{self.number}"
            previous = sorted(p.name for p in root.glob("box-*"))
            (root / self.remote_id).write_text(self.name)
            with (root / "cloud.jsonl").open("a") as stream:
                stream.write(json.dumps({"box": self.remote_id, "name": self.name,
                    "provider": self.provider, "previous_live": previous}) + "\n")
                stream.flush()
                os.fsync(stream.fileno())
            if self.number == 1 and args.fault == "kill":
                os.kill(os.getpid(), signal.SIGKILL)
            if self.number == 1 and args.fault == "unconfirmed":
                raise TimeoutError("fake create succeeded but its response was lost")
            self.id = self.remote_id

        def payload(self, filename, *values):
            return [filename, *values]

        def exec(self, argv, timeout):
            if argv[0] == "machine.mjs":
                return "BENCHPRESS_MACHINE {}"
            if any("BENCHPRESS_PING" in str(value) for value in argv):
                return f"BENCHPRESS_PING {argv[-1]}"
            workload, token = argv[-2:]
            result = {"workload": workload, "token": token, "node": session.NODE}
            if workload in ("one", "ten"):
                result.update(bytes=32 * 1024**2,
                    records=524288 * (10 if workload == "ten" else 1),
                    checksum=session.CHECKSUMS[workload], read_ms=1, compute_ms=1)
            return "BENCHPRESS_RESULT " + json.dumps(result)

        def placement(self):
            return {}

        def close(self):
            if self.number == 1 and args.fault == "failed":
                raise OSError("fake delete failed; the allocation remains live")
            if self.number == 1 and args.fault == "unconfirmed":
                return "creation_unconfirmed"
            (root / self.remote_id).unlink()
            return "removed"

    options = SimpleNamespace(out=root / "experiment", pilot=True, start_date=None,
        client_region="us-east", providers=["modal", "namespace"], seed=7256,
        mode="standard", workloads=["token"], variant="default")
    config = {"modal": {"app": "fake-app", "image": "fake-image"},
              "namespace": {"image": "fake-image", "size": "s"}}
    try:
        with patch.object(session, "Sandbox", FakeBox):
            runner.run_series(options, config)
    except RuntimeError as error:
        print(error, file=sys.stderr)
        return 23
    return 0


def invoke(root):
    return subprocess.run([sys.executable, str(Path(__file__).resolve()),
        "--repo", str(repo), "--fault", args.fault, "--worker", str(root)],
        cwd=repo, capture_output=True, text=True, timeout=30)


def reproduce():
    root = Path(tempfile.mkdtemp(prefix="benchpress-restart-"))
    print(f"Evidence directory: {root}")
    first = invoke(root)
    rows_path = root / "experiment/attempts.jsonl"
    before = runner.read_rows(rows_path)
    assert len(records(root)) >= 1
    if args.fault == "kill":
        assert first.returncode == -signal.SIGKILL, (first.returncode, first.stderr)
        assert before == [], before
    elif args.fault != "none":
        assert first.returncode == 23, (first.returncode, first.stderr)
        expected = "failed" if args.fault == "failed" else "creation_unconfirmed"
        assert len(before) == 1 and before[0]["cleanup"] == expected, before
    else:
        assert first.returncode == 0, first.stderr
    count_before_restart = len(records(root))
    second = invoke(root)
    assert second.returncode == 0, (second.returncode, second.stderr)
    allocations = records(root)
    if args.fault == "none":
        assert len(allocations) == count_before_restart
        assert all(not item["previous_live"] for item in allocations)
        assert not list(root.glob("box-*"))
        print("PASS: healthy cleanup and saved-attempt skipping")
    else:
        assert allocations[1]["previous_live"] == [allocations[0]["box"]], allocations
        assert (root / allocations[0]["box"]).exists()
        if args.fault == "kill":
            assert allocations[1]["name"] != allocations[0]["name"]
            assert allocations[0]["name"] not in rows_path.read_text()
        else:
            assert runner.read_rows(rows_path)[0] == before[0]
        print(f"CONFIRMED {args.fault}: rerun allocated a new box with box-1 still live")
    print(json.dumps(allocations[:2], indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(worker(args.worker) if args.worker else reproduce())

Verification limits

The original bounded model explored 19 states and 24 steps with one possible restart. The reproducer independently confirms the real scheduler behavior on the published commit. The fake provider deliberately selects an allowed failure outcome in which the allocation survives.

Provider expiry, actual network timing, manual remediation, and concurrent burst behavior were not established by these replays. This issue concerns an already-recorded warning. A startup scan alone cannot recover an allocation whose attempt was never recorded; #2 covers that missing-row case.

Activity

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions