Skip to content
Merged
Show file tree
Hide file tree
Changes from 64 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
ae9636d
fix(loop): refuse an action the session budget cannot fit
zoroyihan7 Aug 13, 2026
5d7ac11
fix(executors): stop one sentinel returncode from naming two causes
zoroyihan7 Aug 13, 2026
63ff1ab
fix(executors): hold every unit of work to the session clock
zoroyihan7 Aug 13, 2026
bf80774
fix(loop): cancel the in-flight actions the session cannot wait for
zoroyihan7 Aug 13, 2026
ea95a73
fix(loop): let the wall-clock defences reach an inline action too
zoroyihan7 Aug 13, 2026
180ad5c
fix(loop): declare the time-budget helpers in the module interface
zoroyihan7 Aug 13, 2026
ec558e4
fix(close): give the sequencer a report task it can still run
zoroyihan7 Aug 13, 2026
8291c0c
fix(prelude): stop preparation spending the optimization phases' budget
zoroyihan7 Aug 13, 2026
7b4cb28
fix(executors): carry the session clock into the Ray worker
zoroyihan7 Aug 13, 2026
4d7ecd8
fix(dispatcher): stop the pump cancelling work it does not own
zoroyihan7 Aug 13, 2026
5b784b2
fix(close): wait for a report already running instead of re-running it
zoroyihan7 Aug 13, 2026
7051ebf
fix(state): reserve the closing grace window, not a fixed two minutes
zoroyihan7 Aug 13, 2026
117d74c
fix(loop): read the action cost the catalogue actually carries
zoroyihan7 Aug 13, 2026
402a777
test: stop two doubles asserting the behaviour these fixes removed
zoroyihan7 Aug 13, 2026
3989569
fix(loop): stop the work, not just the coroutine awaiting it
zoroyihan7 Aug 13, 2026
5122e35
baseline/profile: the session budget reaches the arm that motivated it
zoroyihan7 Aug 13, 2026
cd2273f
admission: price an action on this session's baseline, not the catalogue
zoroyihan7 Aug 13, 2026
bd841b8
explore: a variant the run reaped is not a variant that failed
zoroyihan7 Aug 13, 2026
d0cbf87
baseline: a round the run stopped is not a baseline that failed
zoroyihan7 Aug 13, 2026
6cf0967
ray: the cancel reaches the round, not just the coroutine awaiting it
zoroyihan7 Aug 13, 2026
a46eeb4
docs(executors): say what crossing the process boundary actually costs
zoroyihan7 Aug 13, 2026
0d9a8d7
fix(close): bound the wait on a running step by the work, not the budget
zoroyihan7 Aug 13, 2026
2b84b1c
test(budget): record why a warm replay is priced like a baseline round
zoroyihan7 Aug 13, 2026
97943df
fix(policy): the model cannot rewrite the budget its closing reserve …
zoroyihan7 Aug 13, 2026
9bf3afc
integrate: a cancelled gate takes its patch back out of the tree
zoroyihan7 Aug 13, 2026
5748868
framework: the candidate agent has the same blind spot on a cancel
zoroyihan7 Aug 13, 2026
933659d
grid/baseline: every round carries the stop that ended it, not just t…
zoroyihan7 Aug 13, 2026
168eefc
writeback: a revalidation the run reaped is not an enablement that st…
zoroyihan7 Aug 13, 2026
5f9c69d
explore: rolling back a reaped rebench must not delete a prior round'…
zoroyihan7 Aug 13, 2026
a2326c4
cancel: derive the three cooperative-stop windows from what stopping …
zoroyihan7 Aug 13, 2026
2408383
dispatcher/integrate_patch: split the three functions this branch pus…
zoroyihan7 Aug 13, 2026
c744315
cancel: reaping a round's server and dropping its lease are a sequence
zoroyihan7 Aug 14, 2026
8ab077f
executors: a cancel at the post-verdict KB write owes the stash back
zoroyihan7 Aug 14, 2026
ab0f783
enablement: a revalidation window the run stopped stays usable, and free
zoroyihan7 Aug 14, 2026
de7e321
enablement: a build whose launch probe the run stopped is still unprobed
zoroyihan7 Aug 14, 2026
4a9b65a
tests: every pass of a round is asserted to carry the session deadline
zoroyihan7 Aug 13, 2026
5241794
baseline: the multi-node warmup holds the measured round's budget back
zoroyihan7 Aug 13, 2026
4177de8
stop_attribution: say where the returncode side of the distinction lives
zoroyihan7 Aug 14, 2026
8111ba6
tests: one multi-node setup for both benching arms' suites
zoroyihan7 Aug 14, 2026
073e008
tests: the Ray lease is a launch site of its own
zoroyihan7 Aug 14, 2026
9c03b67
baseline: the warmup holds back the measured round's expected runtime…
zoroyihan7 Aug 14, 2026
a81d52b
cancel: a cancelled action's unwind does not stop to observe itself
zoroyihan7 Aug 14, 2026
4c495f8
baseline: a warmup may claim half of what the round has, and a budget…
zoroyihan7 Aug 14, 2026
db8e484
grid_runner: the budget is re-checked after the uncapped server resta…
zoroyihan7 Aug 14, 2026
0b62de6
baseline: no pass of a round is shortened to pay for the next one
zoroyihan7 Aug 14, 2026
603ebca
machine_state: preparation answers to the session clock, not a ledger…
zoroyihan7 Aug 15, 2026
92951f0
baseline: a round the session cannot finish does not boot a server to…
zoroyihan7 Aug 15, 2026
85a08cf
baseline: say what the round's price really is, an over-prediction wi…
zoroyihan7 Aug 15, 2026
e5edb4e
baseline: name the one thing that keeps a warmup's figure as a marked…
zoroyihan7 Aug 15, 2026
7adef31
executors: a round reports what it spent booting apart from what it s…
zoroyihan7 Aug 15, 2026
d4f1062
state: a session carries what its baseline cost in two parts, and whe…
zoroyihan7 Aug 15, 2026
0e8d572
phases, executors: price work by what it spends, and stop when nothin…
zoroyihan7 Aug 15, 2026
60a700c
phases: a session that stopped in CLOSE reopens where a fresh clock c…
zoroyihan7 Aug 15, 2026
5b3c723
executors, phases: measure a round's price rather than rebuild it, an…
zoroyihan7 Aug 15, 2026
225e307
executors, policy: measure the boot on one clock, and let a cold anch…
zoroyihan7 Aug 15, 2026
8c26553
Require the boot duration when stamping server-ready
zoroyihan7 Aug 15, 2026
66a00ae
Record the multi-node successor as a known gap in the PRELUDE gate
zoroyihan7 Aug 16, 2026
0670593
Stop the usable-budget lock test from racing the clock
zoroyihan7 Aug 16, 2026
c86cd69
Stop recover from running after the session budget is spent.
zoroyihan7 Aug 16, 2026
07e23b9
Ignore the EXPLORE hours leave-behind when it covers the whole session.
zoroyihan7 Aug 17, 2026
b2a43f0
Cancel a tick step that outlives the session bound so the run can sti…
zoroyihan7 Aug 17, 2026
c218d3f
Drop the unused await path that CodeQL flagged, and stop requiring a …
zoroyihan7 Aug 17, 2026
6f23e0a
Fix a rebase merge that concatenated two BaselineExecutor methods.
zoroyihan7 Aug 18, 2026
57c7b66
Close SWEEP honestly when conc_sweep cannot fit the session budget.
zoroyihan7 Aug 18, 2026
f2c241c
Remove the leftover rebase duplicate of enable_multi_node and an unus…
zoroyihan7 Aug 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions selfcheck_gates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Throwaway self-review: sweep the real pricing functions for disagreements."""

from __future__ import annotations

from types import SimpleNamespace

from hyperloom.orchestrator.phases import machine_state as ms

BOOT, COLD_BENCH, HOT = 350.0, 550.0, 400.0
COLD_ROUND = BOOT + COLD_BENCH


def state(usable, *, phase="PRELUDE", warm=HOT, post_ready=COLD_BENCH, marked=False, double=True):
return SimpleNamespace(
phase=phase,
max_minutes=180,
baseline_tput=1000.0,
baseline_runtime_sec=COLD_ROUND,
baseline_post_ready_runtime_sec=post_ready,
baseline_warm_runtime_sec=warm,
baseline_measure_round_dropped=marked,
baseline_double_run=double,
session_budget_usable_sec=lambda: usable,
)


def gate1_need(s):
"""What the pre-ignition gate demands, mirroring _round_affordable."""
cold = ms.measured_seconds(s, "baseline_runtime_sec")
rnd = ms.baseline_round_cost_sec(s, double_run=bool(s.baseline_double_run))
if cold is None or rnd is None:
return None
use = (ms.one_more_measurement_sec(s) or cold) if s.phase == "PRELUDE" else 0.0
return rnd + use


def gate2_need(s, *, warmup_sec, warmup_post_ready):
"""What the post-warmup gate demands, mirroring _measure_round_affordable."""
bench = ms.measured_seconds(s, "baseline_warm_runtime_sec")
if bench is None:
bench = warmup_post_ready
if bench is None or warmup_sec is None:
return None
use = (ms.one_more_measurement_sec(s) or warmup_sec) if s.phase == "PRELUDE" else 0.0
return bench + use


def main() -> int:
bad = 0

# 1. The band: is there a budget gate 1 admits and gate 2 then certainly refuses?
# Gate 2 is asked after the warmup has spent a cold pass.
band = []
for usable in range(0, 6001, 10):
s = state(float(usable))
need1 = gate1_need(s)
admitted = need1 is not None and usable >= need1
if not admitted:
continue
after = state(float(usable) - COLD_ROUND)
need2 = gate2_need(after, warmup_sec=COLD_ROUND, warmup_post_ready=COLD_BENCH)
if need2 is not None and (usable - COLD_ROUND) < need2:
band.append(usable)
if band:
bad += 1
print(f"BAND gate 1 admits and gate 2 refuses for usable in {band[0]}..{band[-1]}")
else:
print("ok no budget is admitted before ignition only to be refused after the cold pass")

# 2. Livelock: with the mark set, does every budget either close or admit a retry?
stuck = []
for usable in range(0, 8001, 10):
s = state(float(usable), marked=True)
closes = ms.exit_cold_anchor_prelude(s) is not None
need1 = gate1_need(s)
admits = need1 is not None and usable >= need1
if not closes and not admits:
stuck.append(usable)
if stuck:
bad += 1
print(f"LIVELOCK neither closes nor admits for usable in {stuck[0]}..{stuck[-1]}")
else:
print("ok a marked session always either closes or may retry")

# 3. A session with no split measured (multi-node / scriptable shape).
s = state(3000.0, warm=0.0, post_ready=0.0)
need = gate1_need(s)
if need is None:
bad += 1
print("UNGATED a round with no boot boundary is waved through")
else:
print(f"ok a round with no split is priced at {need:.0f}s (whole cold rounds)")

# 4. A first baseline must never be judged.
first = SimpleNamespace(
phase="PRELUDE",
max_minutes=180,
baseline_tput=0.0,
baseline_runtime_sec=0.0,
baseline_post_ready_runtime_sec=0.0,
baseline_warm_runtime_sec=0.0,
baseline_measure_round_dropped=False,
baseline_double_run=True,
session_budget_usable_sec=lambda: 60.0,
)
if gate1_need(first) is not None:
bad += 1
print("PREDICTED a first baseline was priced from measurements it cannot have")
else:
print("ok a first baseline is not judged")

# 5. Later phases ask only whether the round fits.
later = state(2000.0, phase="EXPLORE")
if gate1_need(later) != ms.baseline_round_cost_sec(later, double_run=True):
bad += 1
print("SCOPED a re-baseline outside PRELUDE was charged for a successor")
else:
print("ok a re-baseline outside PRELUDE pays only for itself")

return bad


if __name__ == "__main__":
raise SystemExit(main())
1 change: 1 addition & 0 deletions src/hyperloom/agents/robustness/role/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ class IntentType(str, Enum):
"start_ts",
"resumed_ts",
"max_minutes",
"closing_grace_sec",
"optimization_stack",
"gain_per_stack_entry",
"schema_version",
Expand Down
9 changes: 6 additions & 3 deletions src/hyperloom/inference_optimizer/actions/roofline.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,11 @@ analysis task.

## Cost / runtime

* `cost_minutes_p50=8` / `cost_minutes_p75=15` — dominated by profile
(Magpie + torch profiler overhead) + trace_analyze (TraceLens
subprocess); `trace_split` inside TraceLens adds < 30s.
* `typical_runtime_min=10` — dominated by profile (Magpie + torch profiler
overhead) + trace_analyze (TraceLens subprocess); `trace_split` inside
TraceLens adds < 30s. The estimate is calibrated on small models: a field
session measured an 81-minute roofline, so the budget guards prefer this
session's own measured baseline round once one exists and fall back to this
number only before that.
* `requires_lanes=[profile_lane]` — same lane as `profile` so we
don't run two profile-class tasks concurrently against the server.
133 changes: 133 additions & 0 deletions src/hyperloom/inference_optimizer/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,43 @@
_bootstrap_kernel_agent_env()


def enable_multi_node(monkeypatch, nodes: int = 2) -> None:
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
"""Put the executors in multi-node mode with a no-op per-round server restart.

Multi-node is what puts a discarded client-warmup pass in front of a measured
round, so it is the mode in which one round launches more than one benchmark
process -- and the restart between them is the part that needs a cluster.

Args:
monkeypatch: The requesting test's monkeypatch fixture.
nodes: How many nodes to claim, which is what the executors read.
"""
from hyperloom.orchestrator.actions.executors import _multi_node_server_lifecycle as mnl

async def _no_restart(*_args, **_kwargs) -> None:
return None

monkeypatch.setenv("INFERENCE_OPTIMIZER_NODES", str(nodes))
monkeypatch.setattr(mnl, "restart_server_for_round", _no_restart)


def launches_by_round_slot(recorded: list[dict]) -> dict[str, dict]:
"""Index recorded benchmark launches by the output slot each round ran in.

A round is identified by the slot it writes into rather than by its position
in the launch order, so a test can assert on one pass of a round without
encoding how many passes precede it.

Args:
recorded: Launch records, each carrying the ``round_slot`` name the
subprocess doubles stamp on every round they see.

Returns:
dict[str, dict]: The last launch recorded per slot name.
"""
return {launch["round_slot"]: launch for launch in recorded}


def seed_target_analysis_marker(session_dir: Path) -> Path:
"""Write a ``no_target_gpu_configured`` marker JSON at the session dir."""
from hyperloom.inference_optimizer.session.session_paths import target_baseline_json
Expand Down Expand Up @@ -333,3 +370,99 @@

monkeypatch.setenv("INFERENCE_OPTIMIZER_NODES", str(nodes))
monkeypatch.setattr(mnl, "restart_server_for_round", _no_restart)


class _RayDoubleActorClass:
"""The ``@ray.remote`` class: ``.options(...)`` then ``.remote()`` for a handle."""

def __init__(self, cls: type) -> None:
self._cls = cls
self._options: dict = {}

def options(self, **opts):
self._options = dict(opts)
return self

def remote(self, *args, **kwargs) -> "_RayDoubleActorHandle":
return _RayDoubleActorHandle(self._cls(*args, **kwargs), self._options)


class _RayDoubleActorHandle:
"""An actor handle whose methods run in a pool sized like the real actor's.

``max_concurrency`` is read from the options the production code passed, not
assumed: an actor left at Ray's single method slot gets a single-worker pool
here too, so a method that has to reach a call already running blocks behind
it exactly as it would on a real cluster.
"""

def __init__(self, obj, options: dict) -> None:
from concurrent.futures import ThreadPoolExecutor

self._obj = obj
self._pool = ThreadPoolExecutor(max_workers=int(options.get("max_concurrency", 1) or 1))
self.killed = False

def __getattr__(self, name: str):
from types import SimpleNamespace

method = getattr(self._obj, name)
return SimpleNamespace(remote=lambda *a, **kw: self._pool.submit(method, *a, **kw))


class RayDouble:
"""A ``ray`` module stand-in that runs actor methods in real threads.

Ray is not a test dependency, and what these tests are about is what a lease
and its actor do to each other while work is in flight. So the transport is
the only thing faked: the actor is the real class, running real subprocesses,
and an ``ObjectRef`` is a :class:`~concurrent.futures.Future`.
"""

class exceptions: # noqa: N801 — mirrors the ray.exceptions namespace
class RayActorError(Exception):
pass

class RayTaskError(Exception):
pass

class GetTimeoutError(Exception):
pass

def __init__(self) -> None:
self.killed: list = []

def remote(self, cls: type) -> _RayDoubleActorClass:
return _RayDoubleActorClass(cls)

def cluster_resources(self) -> dict:
return {"CPU": 8.0, "GPU": 8.0, "serving_slot": 1.0}

def get(self, ref, timeout: float | None = None):
return ref.result(timeout)

def wait(self, refs: list, *, num_returns: int = 1, timeout: float | None = None):
from concurrent.futures import FIRST_COMPLETED
from concurrent.futures import wait as futures_wait

done, not_done = futures_wait(refs, timeout=timeout, return_when=FIRST_COMPLETED)
return list(done)[:num_returns], list(not_done)

def kill(self, actor) -> None:
actor.killed = True
self.killed.append(actor)


@pytest.fixture
def serving_lease_on_a_ray_double(monkeypatch):
"""A real :class:`ServingLease` over :class:`RayDouble`, closed on teardown."""
import sys
from types import SimpleNamespace

from hyperloom.orchestrator.actions.executors import _ray_backend as rb
from hyperloom.orchestrator.actions.executors import _ray_serving as rs

monkeypatch.setitem(sys.modules, "ray", RayDouble())
monkeypatch.setattr(rb, "get_ray_backend", lambda: SimpleNamespace(ensure=lambda **_kw: None))
with rs.ServingLease(num_gpus=1) as lease:
yield lease
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,16 @@ def test_gate_update_state_cannot_move_the_resume_boundary(gate):
assert exc.value.rule == "state_field"


def test_the_model_cannot_rewrite_the_budget_the_closing_reserve_leaves_it(gate):
"""The reserve decides how much of ``max_minutes`` is spendable, so it is budget too."""
with pytest.raises(PolicyDenied) as exc:
gate.validate_intent(
"orchestration",
Intent(type=IntentType.UPDATE_STATE, payload={"changes": {"closing_grace_sec": 0.0}}),
)
assert exc.value.rule == "state_field"


def test_gate_update_state_cannot_move_a_session_end_time(gate):
# stop_ts is the timestamp half of stop_reason, written by the same setter:
# locking only the reason lets a model post-date the session's end.
Expand All @@ -726,6 +736,21 @@ def test_gate_update_state_cannot_move_a_session_end_time(gate):
assert exc.value.rule == "state_field"


def test_a_forged_closing_reserve_would_have_spent_the_session_outright():
"""Names what the lock prevents: one field, and the run has no usable time left."""
state = SharedState(session_id="s", max_minutes=100)
# Freeze elapsed time: two live ``session_budget_usable_sec`` reads race
# the clock by tens of microseconds, which is enough for ``==`` to fail.
state.elapsed_minutes = lambda **_kw: 90.0 # type: ignore[method-assign]
honest = state.session_budget_usable_sec()

applied = state.apply_changes({"closing_grace_sec": 1e9}, allow_core=False)

assert applied == {}
assert honest > 0.0
assert state.session_budget_usable_sec() == honest


def test_core_state_fields_synced_with_robustness_envelope():
# gate.CORE_STATE_FIELDS and the robustness
# envelope copy must stay byte-identical. This direct assertion never skips
Expand Down
Loading
Loading