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
11 changes: 4 additions & 7 deletions loopx/capabilities/native_chat/steward_monitor_turns.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import json
from pathlib import Path
import re
import time
from typing import Literal, NoReturn, Protocol, overload

from ...chat_store import ChatSessionStore, _atomic_write_json
from ...control_plane.effect_runtime import effect_runtime_result
from ...control_plane.runtime.time import timestamp_age_at_least

TARGET = "steward-portfolio-watch"
FOLLOWUP_TARGET_PREFIX = "steward-monitor-followup:"
Expand Down Expand Up @@ -432,12 +432,9 @@ def advancement_turn_id(todo: Mapping[str, object]) -> str:

def _past_precommit_cooldown(turn: Mapping[str, object], now: float | None) -> bool:
"""Return True when a finished turn has passed the precommit retry cooldown."""
from .steward_turn import _iso_timestamp_seconds

completed_ts = _iso_timestamp_seconds(turn.get("completed_at"))
if completed_ts is None:
return False
return (time.time() if now is None else now) - completed_ts >= ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS
return timestamp_age_at_least(
turn.get("completed_at"), ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS, now=now,
)


def _zero_write_advancement_response(
Expand Down
2 changes: 0 additions & 2 deletions loopx/capabilities/native_chat/steward_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
as_mapping,
as_optional_dict,
as_optional_str,
iso_timestamp_seconds,
is_zero_effect_replan_selection_deferral as _is_zero_effect_replan_selection_deferral,
monitor_store_for,
native_steward_client_id as native_steward_client_id,
Expand Down Expand Up @@ -89,7 +88,6 @@
stopped_report_candidate_recovery,
)

_iso_timestamp_seconds = iso_timestamp_seconds
_append_bounded_ellipsis = append_bounded_ellipsis
_split_bounded_evidence_items = split_bounded_evidence_items
_split_evidence_text_chunks = split_evidence_text_chunks
Expand Down
14 changes: 0 additions & 14 deletions loopx/capabilities/native_chat/steward_turn_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from collections.abc import Callable, Mapping, Sequence
from contextlib import AbstractContextManager
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
Expand Down Expand Up @@ -400,19 +399,6 @@ def as_int(value: object, default: int = 0) -> int:
return value if isinstance(value, int) and not isinstance(value, bool) else default


def iso_timestamp_seconds(value: object) -> float | None:
"""Parse an ISO-8601 timestamp into UTC epoch seconds, or None."""
if not isinstance(value, str) or not value.strip():
return None
try:
parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
except ValueError:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.timestamp()


def same_report_validator_command(frozen_cmd: object, request_cmd: object) -> bool:
"""Allow report validation commands whose only drift is the host Python path."""
return (
Expand Down
10 changes: 3 additions & 7 deletions loopx/capabilities/native_chat/steward_turn_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import time
from typing import Protocol, cast

from ...control_plane.runtime.time import timestamp_age_at_least
from ...file_lock import LOCK_ACQUIRE_TIMEOUT_ERROR_CODE, exclusive_file_lock
from .steward_monitor import (
actor_steward_binding_id,
Expand All @@ -26,7 +27,6 @@
as_mapping,
as_optional_dict,
as_optional_str,
iso_timestamp_seconds,
monitor_store_for,
native_steward_client_id,
steward_monitor_for,
Expand Down Expand Up @@ -198,12 +198,8 @@ def monitor_restart_request(
or (isinstance(msg, str) and _FILE_LOCK_TIMEOUT_ERROR_RE.fullmatch(msg) is not None)
)
)
completed_ts = iso_timestamp_seconds(original.get("completed_at"))
current_ts = time.time() if now is None else now
if (
not post_context_error
or completed_ts is None
or current_ts - completed_ts < MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS
if not post_context_error or not timestamp_age_at_least(
original.get("completed_at"), MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS, now=now,
):
return None
return {**prior, "monitor_restart_recovery": {"original_turn_id": original["turn_id"]}}
Expand Down
20 changes: 19 additions & 1 deletion loopx/control_plane/runtime/time.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from math import isfinite
import re
import time
from typing import Any


Expand Down Expand Up @@ -85,6 +87,22 @@ def parse_timestamp(value: Any) -> datetime | None:
return None


def timestamp_age_at_least(value: object, duration_seconds: int, *, now: float | None) -> bool:
"""Compare a retained timestamp with the wall clock without rounding it up."""
started = parse_timestamp(value) if isinstance(value, str) else None
if started is None:
return False
if now is None:
observed_us = time.time_ns() // 1_000
elif isfinite(now):
numerator, denominator = now.as_integer_ratio()
observed_us = numerator * 1_000_000 // denominator
else:
return False
started_us = (started - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(microseconds=1)
return observed_us - started_us >= duration_seconds * 1_000_000


def chronology_key(value: Any) -> tuple[int, datetime, str]:
"""Order timestamps by UTC instant with deterministic legacy fallbacks."""

Expand Down
50 changes: 50 additions & 0 deletions regression/StewardRetainedCompletionCooldown.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Std

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

The model starts after parsing. Times are integer microseconds and the existing
non-time retry checks supply the eligibility flag. Python tests exercise the
actual timestamp parser, floating point boundary comparisons near the fixture's
epoch, and both callers' retained receipt checks.
-/

namespace StewardRetainedCompletionCooldown

def retryDue (eligible : Bool) (now cooldown : Int) (completed : Option Int) : Bool :=
match completed with
| none => false
| some instant => eligible && decide (cooldown ≤ now - instant)

theorem equal_completion_instants_agree (eligible : Bool) (now cooldown : Int)
(upper lower : Option Int) (same : upper = lower) :
retryDue eligible now cooldown upper = retryDue eligible now cooldown lower := by
rw [same]

theorem before_cutoff_withholds_retry (eligible : Bool) (now cooldown completed : Int)
(before : now < completed + cooldown) :
retryDue eligible now cooldown (some completed) = false := by
have short : ¬ cooldown ≤ now - completed := by omega
simp [retryDue, short]

theorem at_or_after_cutoff_preserves_eligibility (eligible : Bool) (now cooldown completed : Int)
(elapsed : completed + cooldown ≤ now) :
retryDue eligible now cooldown (some completed) = eligible := by
have ready : cooldown ≤ now - completed := by omega
simp [retryDue, ready]

theorem unreadable_completion_cannot_retry (eligible : Bool) (now cooldown : Int) :
retryDue eligible now cooldown none = false := rfl

-- The old parser supplied no instant for the lowercase UTC fixture.
theorem old_lowercase_rejection_changed_the_decision :
retryDue true 60250000 60000000 (some 250000) = true ∧
retryDue true 60250000 60000000 none = false := by decide

#print axioms equal_completion_instants_agree
#print axioms before_cutoff_withholds_retry
#print axioms at_or_after_cutoff_preserves_eligibility
#print axioms unreadable_completion_cannot_retry
#print axioms old_lowercase_rejection_changed_the_decision

end StewardRetainedCompletionCooldown
58 changes: 58 additions & 0 deletions regression/StewardRetryCooldownPrecision.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import Std

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

The model assumes a parsed completion instant in UTC microseconds. It checks
the calendar-independent comparison used by both Python retry callers. The
native clock yields integer nanoseconds. A supplied finite clock value has
the exact numerator and positive denominator returned by the runtime.
-/

namespace StewardRetryCooldownPrecision

def dueUs (completedUs cooldownSeconds : Int) : Int :=
completedUs + cooldownSeconds * 1000000

def nativeElapsed (completedUs cooldownSeconds clockNs : Int) : Prop :=
dueUs completedUs cooldownSeconds ≤ clockNs / 1000

def overrideElapsed (completedUs cooldownSeconds numerator denominator : Int) : Prop :=
dueUs completedUs cooldownSeconds ≤ (numerator * 1000000) / denominator

theorem native_elapsed_iff_exact_deadline (completedUs cooldownSeconds clockNs : Int) :
nativeElapsed completedUs cooldownSeconds clockNs ↔
dueUs completedUs cooldownSeconds * 1000 ≤ clockNs :=
Int.le_ediv_iff_mul_le (by decide)

theorem override_elapsed_iff_exact_deadline
(completedUs cooldownSeconds numerator denominator : Int) (positive : 0 < denominator) :
overrideElapsed completedUs cooldownSeconds numerator denominator ↔
dueUs completedUs cooldownSeconds * denominator ≤ numerator * 1000000 :=
Int.le_ediv_iff_mul_le positive

theorem last_nanosecond_still_waits (completedUs cooldownSeconds : Int) :
¬nativeElapsed completedUs cooldownSeconds (dueUs completedUs cooldownSeconds * 1000 - 1) := by
unfold nativeElapsed
omega

theorem exact_cutoff_is_inclusive (completedUs cooldownSeconds : Int) :
nativeElapsed completedUs cooldownSeconds (dueUs completedUs cooldownSeconds * 1000) := by
rw [native_elapsed_iff_exact_deadline]
omega

-- The retained completion is one microsecond after this whole second.
theorem rounding_can_open_the_far_future_gate_early :
let wholeUs := 253402300200 * 1000000
nativeElapsed wholeUs 60 ((wholeUs + 60000000) * 1000) ∧
¬nativeElapsed (wholeUs + 1) 60 ((wholeUs + 60000000) * 1000) := by
dsimp only [nativeElapsed, dueUs]
decide

#print axioms native_elapsed_iff_exact_deadline
#print axioms override_elapsed_iff_exact_deadline
#print axioms last_nanosecond_still_waits
#print axioms exact_cutoff_is_inclusive
#print axioms rounding_can_open_the_far_future_gate_early

end StewardRetryCooldownPrecision
89 changes: 89 additions & 0 deletions tests/capabilities/test_steward_monitor_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,95 @@ def test_background_session_and_immutable_scope_parity(tmp_path: Path) -> None:
assert _github_repo_slug("https://github.com/owner/repo") is None


@pytest.mark.parametrize(("completed_at", "valid"), [
("2000-01-01T00:00:00.250000Z", True),
("2000-01-01T00:00:00.250000z", True),
("2000-01-01T08:00:00.250000+08:00", True),
("2000-01-01T00:00:00.250000", True),
("invalid", False),
])
def test_steward_retry_cooldowns_use_the_retained_completion_instant(
tmp_path: Path, completed_at: str, valid: bool,
) -> None:
from loopx.capabilities.native_chat.steward_turn import MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS, StewardTurnHost

completed = datetime(2000, 1, 1, microsecond=250000, tzinfo=timezone.utc).timestamp()
store = ChatSessionStore(tmp_path / "chat")
proto_store = cast(StewardSessionStoreProtocol, _CountingTurnLookupStore(store))
session = store.create_session(
goal_id="loopx-manager", agent_id="steward", adapter_kind="codex", upstream_thread_id="fixture",
)
sid = str(session["session_id"])
actor = {"goal_id": "steward-goal", "agent_id": "steward", "session_id": sid}
todo = {"todo_id": "adv-1", "updated_at": "2000-01-01T00:01:00Z"}
token = advancement_turn_id(todo)
turn, _ = store.create_turn(sid, client_turn_id=native_steward_client_id(actor, token), message="follow up")
native_failure = {
"ok": False, "status": "failed", "result_kind": "host_failure",
"effects": {"state_written": False, "quota_spent": False, "scheduler_acknowledged": False},
}
store.update_turn(sid, str(turn["turn_id"]), status="completed", completed_at=completed_at,
response={"native_loopx": native_failure})
monitor = {
"status": "failed", "error_code": "runtime_unavailable", "completed_at": completed_at,
"turn_id": "retained-monitor", "loopx_request": {
"work_kind": "monitor", "monitor_restart_recovery": {"original_turn_id": "prior-monitor"},
},
}
advancement_due = completed + ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS
monitor_due = completed + MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS
retry = token + ADVANCEMENT_PRECOMMIT_RETRY_SUFFIX
recovery = {**monitor["loopx_request"], "monitor_restart_recovery": {"original_turn_id": "retained-monitor"}}

for offset in (-0.000001, 0.0, 0.000001):
elapsed = valid and offset >= 0
assert (
resolve_advancement_turn_id(proto_store, actor, todo, now=advancement_due + offset),
StewardTurnHost.monitor_restart_request(monitor, now=monitor_due + offset),
) == (
(retry, recovery) if elapsed else (None, None)
)

native_failure["effects"]["state_written"] = True
store.update_turn(sid, str(turn["turn_id"]), response={"native_loopx": native_failure})
assert resolve_advancement_turn_id(proto_store, actor, todo, now=advancement_due) is None
assert StewardTurnHost.monitor_restart_request({**monitor, "error_code": "unrelated"}, now=monitor_due) is None


def test_both_retry_cooldowns_preserve_far_future_microseconds(monkeypatch: pytest.MonkeyPatch) -> None:
from math import inf, nextafter
import time

from loopx.capabilities.native_chat import steward_turn

completed_second = int(datetime(9999, 12, 31, 23, 50, tzinfo=timezone.utc).timestamp())
completed = {"completed_at": "9999-12-31T23:50:00.000001Z"}
original = {
**completed, "status": "failed", "error_code": "runtime_unavailable", "turn_id": "retained-monitor",
"loopx_request": {"work_kind": "monitor", "monitor_restart_recovery": {"original_turn_id": "prior"}},
}
advancement_second = completed_second + ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS
monitor_second = completed_second + steward_turn.MONITOR_RECOVERY_RETRY_COOLDOWN_SECONDS
clock_ns = 0
monkeypatch.setattr(time, "time_ns", lambda: clock_ns)
monkeypatch.setattr(time, "time", lambda: clock_ns / 1_000_000_000)

for offset in (-1_000, -1, 0, 1_000):
clock_ns = advancement_second * 1_000_000_000 + 1_000 + offset
followup_due = steward_monitor_turns._past_precommit_cooldown(completed, None)
clock_ns = monitor_second * 1_000_000_000 + 1_000 + offset
recovery_due = steward_turn.StewardTurnHost.monitor_restart_request(original) is not None
assert (followup_due, recovery_due) == (offset >= 0, offset >= 0)

assert not steward_monitor_turns._past_precommit_cooldown(completed, float(advancement_second))
assert steward_turn.StewardTurnHost.monitor_restart_request(original, now=float(monitor_second)) is None
assert steward_monitor_turns._past_precommit_cooldown(completed, nextafter(advancement_second, inf))
assert steward_turn.StewardTurnHost.monitor_restart_request(original, now=nextafter(monitor_second, inf)) is not None
for invalid_now in (inf, -inf, float("nan")):
assert not steward_monitor_turns._past_precommit_cooldown(completed, invalid_now)
assert steward_turn.StewardTurnHost.monitor_restart_request(original, now=invalid_now) is None


def test_advancement_retry_exhaustion_and_lookup_cache_efficiency(tmp_path: Path) -> None:
store = ChatSessionStore(tmp_path / "chat")
counting_store = _CountingTurnLookupStore(store)
Expand Down
Loading