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
3 changes: 2 additions & 1 deletion loopx/capabilities/native_chat/steward_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from collections.abc import Mapping, Sequence
import subprocess as subprocess

from ...control_plane.runtime.time import chronology_key
from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due
from ...control_plane.todos.list_readback import list_goal_todos
from ...file_lock import exclusive_file_lock
Expand Down Expand Up @@ -131,7 +132,7 @@ def due_monitors(
]
return sorted(
rows,
key=lambda row: (str(row.get("next_due_at") or ""), str(row["todo_id"])),
key=lambda row: (chronology_key(row.get("next_due_at")), str(row["todo_id"])),
)

def runnable_advancement_todos(
Expand Down
74 changes: 74 additions & 0 deletions regression/StewardDueMonitorOrder.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Std

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

Eligible rows have deadlines parsed to UTC microseconds. The raw deadline
and Todo ID ranks represent the two Python string tie breakers. An independent
predicate represents the pump skipping a row before its first attempt. The
Python regression covers the actual filters, parser, and dispatch arguments.
-/

namespace StewardDueMonitorOrder

structure Monitor where
eligible : Bool
deadline : Int
rawRank : Nat
idRank : Nat

def beforeOrAt (a b : Monitor) : Bool :=
decide (a.deadline < b.deadline ∨ (a.deadline = b.deadline ∧
(a.rawRank < b.rawRank ∨ (a.rawRank = b.rawRank ∧ a.idRank ≤ b.idRank))))

def due (rows : List Monitor) : List Monitor :=
(rows.filter Monitor.eligible).mergeSort beforeOrAt

def attempts (rows : List Monitor) (ready : Monitor → Bool) : List Monitor :=
(due rows).filter ready

theorem due_keeps_exactly_the_eligible_rows (rows : List Monitor) :
(due rows).Perm (rows.filter Monitor.eligible) :=
List.mergeSort_perm _ _

theorem due_is_ordered (rows : List Monitor) :
(due rows).Pairwise (fun a b => beforeOrAt a b = true) := by
unfold due
apply List.sorted_mergeSort
· intro a b c ab bc
simp only [beforeOrAt, decide_eq_true_eq] at *
omega
· intro a b
simp only [beforeOrAt, Bool.or_eq_true, decide_eq_true_eq]
omega

theorem first_attempt_has_earliest_ready_deadline
(rows : List Monitor) (ready : Monitor → Bool) (first other : Monitor)
(picked : (attempts rows ready).head? = some first)
(present : other ∈ rows) (eligible : other.eligible = true) (canRun : ready other = true) :
first.deadline ≤ other.deadline := by
have dueMember := (due_keeps_exactly_the_eligible_rows rows).mem_iff.mpr
(List.mem_filter.mpr ⟨present, eligible⟩)
have member : other ∈ attempts rows ready := List.mem_filter.mpr ⟨dueMember, canRun⟩
have sorted : (attempts rows ready).Pairwise (fun a b => beforeOrAt a b = true) :=
(due_is_ordered rows).filter _
cases found : attempts rows ready with
| nil => simp [found] at picked
| cons head tail =>
have same : head = first := by simpa [found] using picked
rw [found, same] at member sorted
rcases List.mem_cons.mp member with equal | inTail
· simp [equal]
· have ordered := (List.pairwise_cons.mp sorted).1 other inTail
simp only [beforeOrAt, decide_eq_true_eq] at ordered
omega

theorem text_sort_can_attempt_a_later_deadline_first :
"2000-02-03T10:00:00.000001Z" < "2000-02-03T10:00:00Z" ∧
beforeOrAt ⟨true, 0, 1, 0⟩ ⟨true, 1, 0, 1⟩ = true := by decide

#print axioms due_keeps_exactly_the_eligible_rows
#print axioms first_attempt_has_earliest_ready_deadline
#print axioms text_sort_can_attempt_a_later_deadline_first

end StewardDueMonitorOrder
52 changes: 52 additions & 0 deletions tests/capabilities/test_steward_monitor_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,58 @@ def _record(token: str, completed_at: str, response: dict[str, object]) -> None:
assert loaded is not None and loaded["turn_id"] == found["turn_id"]


def test_due_monitor_pump_tries_earliest_utc_deadline_and_preserves_original_text(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
from loopx.capabilities.native_chat.steward_turn import StewardTurnHost

controller = _StubController(tmp_path)
ctrl_proto = _as_controller(controller)
session = controller.store.create_session(
goal_id="loopx-manager", agent_id="steward",
adapter_kind="codex", upstream_thread_id="fixture-thread",
)
actor = {"goal_id": "steward-agent-b-order", "agent_id": "steward", "session_id": session["session_id"]}
controller.project_contexts.conversation_bindings.bindings_rows = [{
"binding_id": "b-order", "enabled": True, "managed_actor": actor,
}]
earliest = "2000-02-03T10:00:00Z"
todos: list[StewardTodoRecord] = [
{"todo_id": name, "task_class": "continuous_monitor", "status": "open",
"claimed_by": "steward", "target_key": "watch-" + name, "next_due_at": stamp}
for name, stamp in [
("earlier-z", earliest),
("later", "2000-02-03T10:00:00.000001Z"),
("equal-offset", "2000-02-03T18:00:00+08:00"),
("earlier-a", earliest),
("future", "2999-01-01T00:00:00Z"),
]
]
first_due = todos[3]
todos.extend([
{**first_due, "todo_id": "expired", "target_key": "watch-expired", "expires_at": "2000-02-04T00:00:00Z"},
{**first_due, "todo_id": "foreign", "target_key": "watch-foreign", "claimed_by": "peer"},
{**first_due, "todo_id": "managed", "target_key": "managed-session-watch.fixture"},
{**first_due, "todo_id": "followup", "target_key": FOLLOWUP_TARGET_PREFIX + "fixture"},
])
attempts: list[tuple[str, str, str, str, str]] = []

def capture_submit(_host, binding_id, *, turn_instance_id, todo_id, work_kind, monitor_deadline):
attempts.append((binding_id, turn_instance_id, todo_id, work_kind, monitor_deadline))
return {"todo_id": todo_id, "status": "queued"}, True

monkeypatch.setattr(steward_monitor, "list_goal_todos", lambda **_: {"todos": todos})
monkeypatch.setattr(StewardTurnHost, "submit", capture_submit)
ordered = StewardMonitor(ctrl_proto).due_monitors(actor, todos=todos)
queued = pump_steward_monitors(ctrl_proto)

assert ([row["todo_id"] for row in ordered], attempts) == (
["earlier-a", "earlier-z", "equal-offset", "later"],
[("b-order", monitor_turn_id(first_due), "earlier-a", "monitor", earliest)],
)
assert queued == [{"todo_id": "earlier-a", "status": "queued"}]


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