Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 9 additions & 7 deletions loopx/capabilities/native_chat/steward_monitor_pump.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from ...agent_registry import load_goal_from_registry
from ...control_plane.projects.registry_codec import load_registry
from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due
from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due, monitor_todo_next_due_at
from ...registry import registry_goals
from .steward_monitor_turns import (
FOLLOWUP_TARGET_PREFIX,
Expand Down Expand Up @@ -347,9 +347,11 @@ def _report_config_for_goal(controller: StewardControllerProtocol, goal_id: str)
return report_config if isinstance(report_config, Mapping) else {}


def _remaining_due_seconds(next_due_at: str) -> float:
due_dt = datetime.fromisoformat(next_due_at.replace("Z", "+00:00"))
return (due_dt - datetime.now(timezone.utc)).total_seconds()
def _monitor_deadline(todo: StewardTodoRecord) -> datetime:
deadline = monitor_todo_next_due_at(todo)
if deadline is None:
raise ValueError("invalid monitor deadline")
return deadline


def _schedule_soonest_monitor_backoff(
Expand All @@ -364,8 +366,8 @@ def _schedule_soonest_monitor_backoff(
]
if not all_monitors:
return
soonest = min(all_monitors, key=lambda row: datetime.fromisoformat(row["next_due_at"].replace("Z", "+00:00")))
remaining = _remaining_due_seconds(soonest["next_due_at"])
soonest = min(_monitor_deadline(row) for row in all_monitors)
remaining = (soonest - datetime.now(timezone.utc)).total_seconds()
if remaining > 0:
cache[binding_id] = time.monotonic() + min(60, remaining)

Expand Down Expand Up @@ -607,7 +609,7 @@ def _process_managed_session(
if not monitor_todo_is_due(todo):
_clear_failure(cache, failures, watch_fail_key)
if todo.get("status") == "open" and todo.get("next_due_at") and not _any_session_failure_active(cache, session_id, now_mono):
remaining = _remaining_due_seconds(todo["next_due_at"])
remaining = (_monitor_deadline(todo) - datetime.now(timezone.utc)).total_seconds()
cache[key] = time.monotonic() + min(60, max(0, remaining))
return
accepted, created = service.submit(
Expand Down
78 changes: 78 additions & 0 deletions regression/StewardIdleMonitorBackoff.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import Std

/-
Run with Lean 4.22.0: `lean -DwarningAsError=true regression/StewardIdleMonitorBackoff.lean`.

Times are integer microseconds. The model begins with the scheduler parser's
accepted clock and offset fields. An omitted offset means UTC. The portfolio
pump takes the minimum parsed deadline of an already filtered nonempty list.
The managed pump has one deadline. The Python regression exercises parsing,
the idle routes and the monotonic hints without dispatch.
-/

namespace StewardIdleMonitorBackoff

structure Deadline where
localTime : Int
offset : Option Int

def Deadline.utc (stamp : Deadline) : Int :=
stamp.localTime - stamp.offset.getD 0

def earliest (first : Deadline) (rest : List Deadline) : Int :=
(rest.map Deadline.utc).foldl min first.utc

def managedWait (now due : Int) : Int :=
min 60000000 (max 0 (due - now))

def portfolioWait (existing now due : Int) : Int :=
if now < due then min 60000000 (due - now) else existing

theorem earliest_le_every_candidate (first : Deadline) (rest : List Deadline)
(stamp : Deadline) (present : stamp ∈ first :: rest) :
earliest first rest ≤ stamp.utc := by
have foldBound (dates : List Int) (initial : Int) (target : Int)
(bound : initial ≤ target ∨ target ∈ dates) : dates.foldl min initial ≤ target := by
induction dates generalizing initial with
| nil => simp at bound ⊢; omega
| cons next tail ih =>
simp only [List.foldl_cons]
rcases bound with le | inDates
· exact ih _ (Or.inl (by omega))
· rcases List.mem_cons.mp inDates with rfl | inTail
· exact ih _ (Or.inl (by omega))
· exact ih _ (Or.inr inTail)
apply foldBound
rcases List.mem_cons.mp present with rfl | inRest
· exact Or.inl (by omega)
· exact Or.inr (List.mem_map.mpr ⟨stamp, inRest, rfl⟩)

theorem waits_agree_for_future_deadlines (existing now due : Int) (future : now < due) :
portfolioWait existing now due = managedWait now due := by
simp [portfolioWait, future, managedWait]
omega

theorem managed_wait_is_bounded (now due : Int) :
0 ≤ managedWait now due ∧ managedWait now due ≤ 60000000 := by
unfold managedWait
omega

theorem overdue_portfolio_keeps_its_hint (existing now due : Int) (overdue : due ≤ now) :
portfolioWait existing now due = existing := by
simp [portfolioWait, show ¬now < due by omega]

def oldComparable (a b : Deadline) : Bool :=
a.offset.isSome == b.offset.isSome

theorem mixed_formats_have_a_bounded_wait :
oldComparable ⟨250000, none⟩ ⟨-17989750000, some (-18000000000)⟩ = false ∧
managedWait 0 (earliest ⟨250000, none⟩ [⟨-17989750000, some (-18000000000)⟩]) = 250000 := by
decide

#print axioms earliest_le_every_candidate
#print axioms waits_agree_for_future_deadlines
#print axioms managed_wait_is_bounded
#print axioms overdue_portfolio_keeps_its_hint
#print axioms mixed_formats_have_a_bounded_wait

end StewardIdleMonitorBackoff
66 changes: 66 additions & 0 deletions tests/capabilities/test_steward_monitor_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,72 @@ def run_cfg(operation: str, plan_todo: object) -> dict[str, object]:
assert writes == []


@pytest.mark.parametrize(("seconds_until_due", "expected_wait"), [(0.25, 0.25), (60, 60), (90, 60)])
def test_idle_pumps_use_scheduler_deadlines_without_dispatch(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seconds_until_due: float, expected_wait: float,
) -> None:
from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn
from loopx.capabilities.native_chat.steward_turn import StewardTurnHost
from loopx.control_plane.scheduler import monitor_todo

wall_clock = datetime(2030, 1, 1, tzinfo=timezone.utc)

class FixedDateTime(datetime):
@classmethod
def now(cls, tz=None):
return wall_clock.astimezone(tz) if tz is not None else wall_clock.replace(tzinfo=None)

monkeypatch.setattr(steward_monitor_pump, "datetime", FixedDateTime)
monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: 1000.0)
monkeypatch.setattr(monitor_todo, "now_utc", lambda: wall_clock)

controller = _StubController(tmp_path)
session = controller.store.create_session(
goal_id="loopx-manager", agent_id="steward", adapter_kind="codex", upstream_thread_id="fixture",
)
managed = controller.store.create_session(
goal_id="g-managed", agent_id="codex", adapter_kind="codex", upstream_thread_id="fixture-managed",
managed_agent_id="managed", managed_workspace_path=str(tmp_path), channel_id="agent.managed",
)
controller.registry_path.write_text(
json.dumps({"goals": [{"id": "g-managed", "repo": str(tmp_path)}]}), encoding="utf-8",
)
controller.project_contexts.conversation_bindings.bindings_rows = [{
"binding_id": "fixture", "enabled": True,
"managed_actor": {"goal_id": "g-steward", "agent_id": "steward", "session_id": session["session_id"]},
}]
soon = wall_clock + timedelta(seconds=seconds_until_due)
no_offset = soon.replace(tzinfo=None).isoformat()
later_with_offset = (soon + timedelta(seconds=10)).astimezone(timezone(timedelta(hours=-5))).isoformat()
common = {"status": "open", "task_class": "continuous_monitor"}
portfolio_todos = [
{**common, "todo_id": "later", "target_key": "watch-later", "claimed_by": "steward", "next_due_at": later_with_offset},
{**common, "todo_id": "soon", "target_key": "watch-soon", "claimed_by": "steward", "next_due_at": no_offset},
{**common, "todo_id": "other-lane", "target_key": "managed-session-watch.other",
"claimed_by": "steward", "next_due_at": (wall_clock + timedelta(microseconds=1)).isoformat()},
]
managed_todos = [
{**common, "todo_id": "managed-watch", "target_key": f"managed-session-watch.{managed['session_id']}",
"claimed_by": "managed", "next_due_at": no_offset},
]
monkeypatch.setattr(steward_monitor, "list_goal_todos",
lambda *, goal_id, **_: {"todos": managed_todos if goal_id == "g-managed" else portfolio_todos})
monkeypatch.setattr(ManagedSessionTurn, "admit", lambda *_: {})

def unexpected_submit(*_args, **_kwargs):
pytest.fail("a future deadline must not dispatch")

monkeypatch.setattr(StewardTurnHost, "submit", unexpected_submit)
monkeypatch.setattr(ManagedSessionTurn, "submit", unexpected_submit)

assert pump_steward_monitors(_as_controller(controller)) == []
assert getattr(controller, "_steward_monitor_failure_state") == {}
assert getattr(controller, "_steward_monitor_next_check") == {
"fixture": 1000.0 + expected_wait,
f"session.{managed['session_id']}": 1000.0 + expected_wait,
}


def test_steward_pump_failure_backoff_dedup_and_clear(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
Expand Down
Loading