diff --git a/loopx/capabilities/native_chat/steward_monitor.py b/loopx/capabilities/native_chat/steward_monitor.py index 0f51743929..17d41b3e4a 100644 --- a/loopx/capabilities/native_chat/steward_monitor.py +++ b/loopx/capabilities/native_chat/steward_monitor.py @@ -344,9 +344,9 @@ def _native_poll(self, argv: Sequence[str]) -> dict[str, object]: return _coerce_dict(result) def _clear_next_check_hint(self, binding_id: str) -> None: - cache = getattr(self.controller, "_steward_monitor_next_check", None) - if isinstance(cache, dict): - cache.pop(binding_id, None) + from .steward_monitor_pump import clear_steward_monitor_check_hints + + clear_steward_monitor_check_hints(self.controller, binding_id) def configure( self, diff --git a/loopx/capabilities/native_chat/steward_monitor_pump.py b/loopx/capabilities/native_chat/steward_monitor_pump.py index dac7a45eb0..7f2044c8e8 100644 --- a/loopx/capabilities/native_chat/steward_monitor_pump.py +++ b/loopx/capabilities/native_chat/steward_monitor_pump.py @@ -4,12 +4,19 @@ from collections.abc import Mapping, Sequence from datetime import datetime, timezone +import errno +import hashlib +import json import logging +from pathlib import Path +import re import time -from typing import Protocol +from typing import Protocol, TypeVar 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 ...registry import registry_goals from .steward_monitor_turns import ( FOLLOWUP_TARGET_PREFIX, StewardControllerProtocol, @@ -18,9 +25,13 @@ _coerce_dict, monitor_turn_id, resolve_advancement_turn_id, + steward_background_session_id, ) _LOG = logging.getLogger(__name__) +_DEFAULT_POLL_INTERVAL_SECONDS = 60.0 +_MAX_FAILURE_BACKOFF_SECONDS = 3600.0 +_SAFE_ERROR_CODE_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") class _CancelCheck(Protocol): @@ -31,19 +42,19 @@ class _BindingsReaderProtocol(Protocol): def read(self) -> Mapping[str, object]: ... -def _ensure_float_cache( - controller: StewardControllerProtocol, attr: str -) -> dict[str, float]: - cache = getattr(controller, attr, None) - if not isinstance(cache, dict): - cache = {} - setattr(controller, attr, cache) - return cache +class _HashDigest(Protocol): + def update(self, data: bytes, /) -> None: ... -def _ensure_bool_cache( +_WitnessRecord = tuple[str, tuple[Path, ...]] +_StatVersion = tuple[int, int, int, int] +_RegistryCacheEntry = tuple[_StatVersion | None, dict[str, str], str | None] +_V = TypeVar("_V") + + +def _ensure_dict_cache( controller: StewardControllerProtocol, attr: str -) -> dict[str, bool]: +) -> dict[str, _V]: cache = getattr(controller, attr, None) if not isinstance(cache, dict): cache = {} @@ -51,16 +62,288 @@ def _ensure_bool_cache( return cache -def _report_config_for_goal( - controller: StewardControllerProtocol, goal_id: str -) -> Mapping[str, object]: +def _failure_key(lane: str, owner_id: str, item_id: str = "") -> str: + return f"failure.{lane}.{owner_id}.{item_id}" if item_id else f"failure.{lane}.{owner_id}" + + +_SESSION_FAILURE_LANES = ( + "session.admit", + "watch.session", + "calendar.session", + "report.session", +) + + +def _exception_diagnostics(stage: str, exc: BaseException) -> str: + """Build structured, path-free diagnostic metadata from allowlisted fields only.""" + parts = [f"stage={stage}", f"error={type(exc).__name__}"] + if isinstance(exc, OSError) and isinstance(exc.errno, int): + parts.append(f"errno={errno.errorcode.get(exc.errno, str(exc.errno))}") + raw_code = getattr(exc, "error_code", None) + if isinstance(raw_code, str) and _SAFE_ERROR_CODE_RE.fullmatch(raw_code): + parts.append(f"code={raw_code}") + return ", ".join(parts) + + +def _update_path_stat_digest(digest: _HashDigest, label: str, path: object) -> None: + if not isinstance(path, Path): + return + digest.update(label.encode("utf-8")) + try: + st = path.stat() + digest.update(f":{st.st_mtime_ns}:{st.st_ctime_ns}:{st.st_size}:{st.st_ino};".encode("utf-8")) + except OSError: + digest.update(b":missing;") + + +def _canonical_json_bytes(value: object) -> bytes: + return json.dumps( + value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), + default=lambda item: dict(item) if isinstance(item, Mapping) else str(item), + ).encode("utf-8") + + +def _canonical_json_digest(digest: _HashDigest, label: str, value: object) -> None: + digest.update(label.encode("utf-8")) + digest.update(b":") + digest.update(_canonical_json_bytes(value)) + digest.update(b";") + + +def _registry_goal_witness_token( + controller: StewardControllerProtocol, registry_path: Path, goal_id: str +) -> str: + try: + st = registry_path.stat() + stat_version: _StatVersion | None = (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_size) + except FileNotFoundError: + stat_version = None + except OSError as exc: + return f"stat_err:{type(exc).__name__}" + reg_cache: dict[str, _RegistryCacheEntry] = _ensure_dict_cache( + controller, "_steward_monitor_registry_cache" + ) + key = str(registry_path) + cached = reg_cache.get(key) + if cached is not None and cached[0] == stat_version: + _, goal_digests, error_tag = cached + return error_tag if error_tag is not None else goal_digests.get(goal_id, "missing") + if len(reg_cache) >= 8 and key not in reg_cache: + reg_cache.clear() + if stat_version is None: + reg_cache[key] = (None, {}, None) + return "missing" + try: + registry = load_registry(registry_path) + goal_digests = { + str(goal["id"]): hashlib.sha256(_canonical_json_bytes(goal)).hexdigest() + for goal in registry_goals(registry) + if isinstance(goal, Mapping) and goal.get("id") is not None + } + reg_cache[key] = (stat_version, goal_digests, None) + return goal_digests.get(goal_id, "missing") + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + error_tag = f"err:{type(exc).__name__}" + reg_cache[key] = (stat_version, {}, error_tag) + return error_tag + + +def _collect_session_turn_targets( + controller: StewardControllerProtocol, session_ids: Sequence[str], exc: BaseException | None = None +) -> tuple[Path, ...]: + """Capture only active/failing turn paths at failure time (never scan historical turns).""" + sessions_root = getattr(controller.store, "sessions_root", None) + if not isinstance(sessions_root, Path): + return () + targets: set[Path] = set() + failed_map = getattr(controller.store, "_last_read_error_paths", None) + exc_name = getattr(exc, "filename", None) if isinstance(exc, OSError) else None + exc_path = Path(exc_name) if isinstance(exc_name, (str, Path)) else None + for sid in session_ids: + if not sid: + continue + turns_dir = sessions_root / sid / "turns" + failed = failed_map.pop(sid, None) if isinstance(failed_map, dict) else None + if isinstance(failed, Path): + targets.add(failed) + if exc_path is not None and exc_path.parent == turns_dir: + targets.add(exc_path) + try: + raw = json.loads((sessions_root / sid / "session.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + raw = None + if isinstance(raw, Mapping): + active_tid = raw.get("active_turn_id") + if (isinstance(active_tid, str) and active_tid and "/" not in active_tid and "\\" not in active_tid + and Path(active_tid).name == active_tid and active_tid not in {".", ".."}): + targets.add(turns_dir / f"{active_tid}.json") + return tuple(sorted(targets)) + + +def _session_storage_witness( + controller: StewardControllerProtocol, session_ids: Sequence[str], *, + goal_id: str = "", binding: Mapping[str, object] | None = None, turn_targets: Sequence[Path] = (), +) -> str: + """Compute an O(1) target-scoped witness so on-disk repairs invalidate backoff immediately.""" + digest = hashlib.sha256() + sessions_root = getattr(controller.store, "sessions_root", None) + if isinstance(sessions_root, Path): + for sid in session_ids: + if not sid: + continue + sdir = sessions_root / sid + _update_path_stat_digest(digest, f"session:{sid}", sdir / "session.json") + _update_path_stat_digest(digest, f"turns_dir:{sid}", sdir / "turns") + for target in turn_targets: + _update_path_stat_digest(digest, f"turn_target:{target.name}", target) + registry_path = getattr(controller, "registry_path", None) + if isinstance(registry_path, Path) and goal_id: + token = _registry_goal_witness_token(controller, registry_path, goal_id) + digest.update(f"registry_goal:{goal_id}:{token};".encode("utf-8")) + if binding is not None: + _canonical_json_digest(digest, "binding", binding) + coord_root = getattr(controller, "coordination_runtime_root", None) + if isinstance(coord_root, Path) and goal_id: + gdir = coord_root / "goals" / goal_id + for label, target in ( + ("goal_dir", gdir), ("goal_sqlite", gdir / "state.sqlite3"), + ("goal_sqlite_wal", gdir / "state.sqlite3-wal"), ("goal_auth", gdir / "authority.sqlite"), + ("goal_auth_wal", gdir / "authority.sqlite-wal"), + ): + _update_path_stat_digest(digest, label, target) + return digest.hexdigest() + + +def _failure_active(cache: dict[str, float], failure_key: str, now_mono: float) -> bool: + return bool(failure_key) and cache.get(failure_key, 0.0) > now_mono + + +def _witness_backoff_active( + controller: StewardControllerProtocol, cache: dict[str, float], witnesses: dict[str, _WitnessRecord], + failure_key: str, session_ids: Sequence[str], now_mono: float, *, + goal_id: str = "", binding: Mapping[str, object] | None = None, throttle_key: str = "", +) -> bool: + if not _failure_active(cache, failure_key, now_mono): + return False + stored = witnesses.get(failure_key) + if stored is None: + return True + current = ( + _session_storage_witness(controller, session_ids, goal_id=goal_id, binding=binding, turn_targets=stored[1]) + if session_ids or binding is not None else "" + ) + if stored[0] and current != stored[0]: + cache.pop(failure_key, None) + if throttle_key: + cache.pop(throttle_key, None) + witnesses.pop(failure_key, None) + return False + return True + + +def _record_session_failure( + controller: StewardControllerProtocol, cache: dict[str, float], failures: dict[str, tuple[int, str]], + witnesses: dict[str, _WitnessRecord], failure_key: str, base_message: str, exc: BaseException, *, + stage: str, now_mono: float, session_ids: Sequence[str], + goal_id: str = "", binding: Mapping[str, object] | None = None, throttle_key: str = "", +) -> None: + if throttle_key: + cache.pop(throttle_key, None) + targets = _collect_session_turn_targets(controller, session_ids, exc) + witness = ( + _session_storage_witness(controller, session_ids, goal_id=goal_id, binding=binding, turn_targets=targets) + if session_ids or binding is not None else "" + ) + _record_failure( + cache, failures, failure_key, base_message, exc, stage=stage, now_mono=now_mono, + witnesses=witnesses, witness=(witness, targets) if witness else None, + ) + + +def _any_session_failure_active( + cache: dict[str, float], session_id: str, now_mono: float +) -> bool: + return any( + _failure_active(cache, _failure_key(lane, session_id), now_mono) + for lane in _SESSION_FAILURE_LANES + ) + + +def _clear_failure( + cache: dict[str, float], + failures: dict[str, tuple[int, str]], + failure_key: str, + *, + witnesses: dict[str, _WitnessRecord] | None = None, +) -> None: + if not failure_key: + return + cache.pop(failure_key, None) + failures.pop(failure_key, None) + if witnesses is not None: + witnesses.pop(failure_key, None) + + +def _record_failure( + cache: dict[str, float], + failures: dict[str, tuple[int, str]], + failure_key: str, + base_message: str, + exc: BaseException, + *, + stage: str, + now_mono: float, + witnesses: dict[str, _WitnessRecord] | None = None, + witness: _WitnessRecord | None = None, +) -> float: + detail = _exception_diagnostics(stage, exc) + count, prev_sig = failures.get(failure_key, (0, "")) if failure_key else (0, "") + next_count = count + 1 + delay: float = float( + min( + _MAX_FAILURE_BACKOFF_SECONDS, + _DEFAULT_POLL_INTERVAL_SECONDS * (1 << min(6, next_count - 1)), + ) + ) + if failure_key: + failures[failure_key] = (next_count, detail) + cache[failure_key] = max(cache.get(failure_key, 0.0), now_mono + delay) + if witnesses is not None and witness is not None: + witnesses[failure_key] = witness + if detail != prev_sig: + _LOG.warning("%s (%s)", base_message, detail) + else: + _LOG.debug("%s (suppressed repeat #%d: %s)", base_message, next_count, detail) + return delay + + +def clear_steward_monitor_check_hints( + controller: StewardControllerProtocol, owner_key: str +) -> None: + """Reset ephemeral pump throttle and failure-backoff hints for one owner.""" + exact_keys = { + owner_key, + f"session.{owner_key}", + *(_failure_key(lane, owner_key) for lane in ("binding", "report", *_SESSION_FAILURE_LANES)), + } + prefixes = (f"failure.monitor.{owner_key}.", f"failure.advancement.{owner_key}.") + for attr in ( + "_steward_monitor_next_check", + "_steward_monitor_failure_state", + "_steward_monitor_failure_witnesses", + ): + cache = getattr(controller, attr, None) + if not isinstance(cache, dict): + continue + for key in list(cache.keys()): + if key in exact_keys or any(key.startswith(prefix) for prefix in prefixes): + cache.pop(key, None) + + +def _report_config_for_goal(controller: StewardControllerProtocol, goal_id: str) -> Mapping[str, object]: goal = load_goal_from_registry(controller.registry_path, goal_id) control_plane = goal.get("control_plane") if isinstance(goal, Mapping) else None - report_config = ( - control_plane.get("periodic_report") - if isinstance(control_plane, Mapping) - else None - ) + report_config = control_plane.get("periodic_report") if isinstance(control_plane, Mapping) else None return report_config if isinstance(report_config, Mapping) else {} @@ -70,28 +353,18 @@ def _remaining_due_seconds(next_due_at: str) -> float: def _schedule_soonest_monitor_backoff( - cache: dict[str, float], - binding_id: str, - todos: Sequence[StewardTodoRecord], + cache: dict[str, float], binding_id: str, todos: Sequence[StewardTodoRecord] ) -> None: all_monitors = [ - row - for row in todos - if row.get("task_class") == "continuous_monitor" - and row.get("status") == "open" + row for row in todos + if row.get("task_class") == "continuous_monitor" and row.get("status") == "open" and isinstance(row.get("target_key"), str) and not row["target_key"].startswith("managed-session-watch.") - and not row["target_key"].startswith(FOLLOWUP_TARGET_PREFIX) - and row.get("next_due_at") + and not row["target_key"].startswith(FOLLOWUP_TARGET_PREFIX) and row.get("next_due_at") ] if not all_monitors: return - soonest = min( - all_monitors, - key=lambda row: datetime.fromisoformat( - row["next_due_at"].replace("Z", "+00:00") - ), - ) + 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"]) if remaining > 0: cache[binding_id] = time.monotonic() + min(60, remaining) @@ -103,6 +376,7 @@ def _process_steward_binding( binding: Mapping[str, object], *, cache: dict[str, float], + failures: dict[str, tuple[int, str]], fg_checked: dict[str, bool], changed: list[dict[str, object]], ) -> None: @@ -132,24 +406,14 @@ def _process_steward_binding( bg_session_id = StewardTurnHost.background_session_id(binding_id) bg_session = controller.store.load_session(bg_session_id) recover_fn = getattr(controller, "recover_exited_turn", None) - if ( - bg_session is not None - and bg_session.get("active_turn_id") - and callable(recover_fn) - ): + if bg_session is not None and bg_session.get("active_turn_id") and callable(recover_fn): recover_fn(bg_session_id) bg_session = controller.store.load_session(bg_session_id) if bg_session is not None and bg_session.get("status") == "closed": bg_idle = False bg_active = False else: - bg_active = bool( - bg_session is not None - and ( - bg_session.get("active_turn_id") - or controller.store.queued_turns(bg_session_id) - ) - ) + bg_active = bool(bg_session is not None and (bg_session.get("active_turn_id") or controller.store.queued_turns(bg_session_id))) bg_idle = not bg_active # Background monitor polls and foreground native turns share the same # steward Goal's runs/ ledger; serialize them against each other while @@ -168,14 +432,16 @@ def _process_steward_binding( return # An ephemeral wake hint only, never authority. Configuration clears it immediately; # external edits are observed within a minute. Every dispatch rechecks native state. - cache[binding_id] = now_mono + 60 + cache[binding_id] = now_mono + _DEFAULT_POLL_INTERVAL_SECONDS fg_checked[binding_id] = fg_can_dispatch # The existing pump also observes the optional report frontier without adding timers. if fg_can_dispatch: report_config = _report_config_for_goal(controller, str(actor["goal_id"])) + report_fail_key = _failure_key("report", binding_id) if ( report_config.get("enabled") is True and report_config.get("profile_preset") == "portfolio-progress" + and not _failure_active(cache, report_fail_key, now_mono) ): from .steward_reports import StewardReports @@ -183,14 +449,17 @@ def _process_steward_binding( accepted, created = StewardReports(controller).frontier( _coerce_dict(binding) ) + _clear_failure(cache, failures, report_fail_key) if created: changed.append(_coerce_dict(accepted)) if bg_idle: cache.pop(binding_id, None) return - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "An original steward report is unavailable; its window and other work are retained" + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, report_fail_key, + "An original steward report is unavailable; its window and other work are retained", + exc, stage="steward_report", now_mono=now_mono, ) todos = service.todos(actor) if bg_can_dispatch: @@ -198,27 +467,27 @@ def _process_steward_binding( if due: dispatched = False for todo in due: + monitor_fail_key = _failure_key("monitor", binding_id, str(todo["todo_id"])) + if _failure_active(cache, monitor_fail_key, now_mono): + continue try: accepted, created = StewardTurnHost(controller).submit( - binding_id, - turn_instance_id=monitor_turn_id(todo), - todo_id=todo["todo_id"], - work_kind="monitor", - monitor_deadline=todo["next_due_at"], + binding_id, turn_instance_id=monitor_turn_id(todo), todo_id=todo["todo_id"], + work_kind="monitor", monitor_deadline=todo["next_due_at"], ) - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "A native steward monitor is unavailable; original work retained" + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, monitor_fail_key, + "A native steward monitor is unavailable; original work retained", + exc, stage="steward_monitor", now_mono=now_mono, ) continue + _clear_failure(cache, failures, monitor_fail_key) if created: changed.append(_coerce_dict(accepted)) dispatched = True break - if isinstance(accepted, dict) and accepted.get("status") in { - "queued", - "running", - }: + if isinstance(accepted, dict) and accepted.get("status") in {"queued", "running"}: dispatched = True break if dispatched: @@ -228,17 +497,24 @@ def _process_steward_binding( advancement_dispatched = False if fg_can_dispatch: for adv in service.runnable_advancement_todos(actor, todos=todos): - turn_id_token = resolve_advancement_turn_id( - controller.store, actor, adv - ) + turn_id_token = resolve_advancement_turn_id(controller.store, actor, adv) if turn_id_token is None: continue - accepted, created = StewardTurnHost(controller).submit( - binding_id, - turn_instance_id=turn_id_token, - todo_id=adv["todo_id"], - work_kind="native_turn", - ) + adv_fail_key = _failure_key("advancement", binding_id, str(adv["todo_id"])) + if _failure_active(cache, adv_fail_key, now_mono): + continue + try: + accepted, created = StewardTurnHost(controller).submit( + binding_id, turn_instance_id=turn_id_token, todo_id=adv["todo_id"], work_kind="native_turn", + ) + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, adv_fail_key, + "A native steward monitor is unavailable; original work retained", + exc, stage="steward_advancement", now_mono=now_mono, + ) + continue + _clear_failure(cache, failures, adv_fail_key) if created: changed.append(_coerce_dict(accepted)) advancement_dispatched = True @@ -253,6 +529,7 @@ def _process_managed_session( session: Mapping[str, object], *, cache: dict[str, float], + failures: dict[str, tuple[int, str]], changed: list[dict[str, object]], ) -> None: from .steward_managed_mode import ManagedSessionTurn @@ -266,19 +543,22 @@ def _process_managed_session( or controller.store.queued_turns(session_id) ): return + now_mono = time.monotonic() key = "session." + session_id - if cache.get(key, 0) > time.monotonic(): + if cache.get(key, 0) > now_mono: return - cache[key] = time.monotonic() + 60 + cache[key] = now_mono + _DEFAULT_POLL_INTERVAL_SECONDS service = ManagedSessionTurn(controller) request = service._request(session_id, str(managed_agent_id), "preview") service.admit(request) report_config = _report_config_for_goal(controller, str(session["goal_id"])) route_ref = "managed-session:" + session_id + calendar_fail_key = _failure_key("calendar.session", session_id) if ( report_config.get("enabled") is True and report_config.get("profile_preset") == "session-task" and report_config.get("route_ref") == route_ref + and not _failure_active(cache, calendar_fail_key, now_mono) ): from .session_calendar_tasks import SessionCalendarTasks from .steward_reports import ManagedSessionReports @@ -286,53 +566,63 @@ def _process_managed_session( try: calendar_tasks: ManagedSessionReports = SessionCalendarTasks(controller) accepted, created = calendar_tasks.frontier(session_id) + _clear_failure(cache, failures, calendar_fail_key) if created: changed.append(_coerce_dict(accepted)) return - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "A managed calendar task is unavailable; its original window and work are retained" + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, calendar_fail_key, + "A managed calendar task is unavailable; its original window and work are retained", + exc, stage="managed_calendar", now_mono=now_mono, ) - if ( - report_config.get("enabled") is True - and report_config.get("profile_preset") == "weekly-progress" - and report_config.get("route_ref") == route_ref - ): + report_fail_key = _failure_key("report.session", session_id) + if (report_config.get("enabled") is True and report_config.get("profile_preset") == "weekly-progress" + and report_config.get("route_ref") == route_ref and not _failure_active(cache, report_fail_key, now_mono)): from .steward_reports import ManagedSessionReports try: accepted, created = ManagedSessionReports(controller).frontier(session_id) + _clear_failure(cache, failures, report_fail_key) if created: changed.append(_coerce_dict(accepted)) return - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "A managed Session report is unavailable; its original window and other work are retained" + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, report_fail_key, + "A managed Session report is unavailable; its original window and other work are retained", + exc, stage="managed_report", now_mono=now_mono, ) - rows = [ - row - for row in monitor.todos(request["actor"]) - if row.get("target_key") == "managed-session-watch." + session_id - ] - if len(rows) != 1: - if rows: - raise ValueError("the original managed Session watch is ambiguous") + watch_fail_key = _failure_key("watch.session", session_id) + if _failure_active(cache, watch_fail_key, now_mono): return - todo = rows[0] - if not monitor_todo_is_due(todo): - if todo.get("status") == "open" and todo.get("next_due_at"): - remaining = _remaining_due_seconds(todo["next_due_at"]) - cache[key] = time.monotonic() + min(60, max(0, remaining)) - return - accepted, created = service.submit( - session_id, - agent_id=str(managed_agent_id), - operation_id=monitor_turn_id(todo), - todo_id=todo["todo_id"], - monitor_deadline=todo["next_due_at"], - ) - if created: - changed.append(_coerce_dict(accepted)) + try: + rows = [row for row in monitor.todos(request["actor"]) if row.get("target_key") == "managed-session-watch." + session_id] + if len(rows) != 1: + if rows: + raise ValueError("the original managed Session watch is ambiguous") + _clear_failure(cache, failures, watch_fail_key) + return + todo = rows[0] + 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"]) + cache[key] = time.monotonic() + min(60, max(0, remaining)) + return + accepted, created = service.submit( + session_id, agent_id=str(managed_agent_id), operation_id=monitor_turn_id(todo), + todo_id=todo["todo_id"], monitor_deadline=todo["next_due_at"], + ) + _clear_failure(cache, failures, watch_fail_key) + if created: + changed.append(_coerce_dict(accepted)) + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_failure( + cache, failures, watch_fail_key, + "A managed Session watch is unavailable; its original task and deadline are retained", + exc, stage="managed_session_watch", now_mono=now_mono, + ) def pump_steward_monitors( @@ -350,8 +640,16 @@ def pump_steward_monitors( return [] service = StewardMonitor(controller) changed: list[dict[str, object]] = [] - cache = _ensure_float_cache(controller, "_steward_monitor_next_check") - fg_checked = _ensure_bool_cache(controller, "_steward_monitor_fg_idle_checked") + cache: dict[str, float] = _ensure_dict_cache(controller, "_steward_monitor_next_check") + failures: dict[str, tuple[int, str]] = _ensure_dict_cache( + controller, "_steward_monitor_failure_state" + ) + witnesses: dict[str, _WitnessRecord] = _ensure_dict_cache( + controller, "_steward_monitor_failure_witnesses" + ) + fg_checked: dict[str, bool] = _ensure_dict_cache( + controller, "_steward_monitor_fg_idle_checked" + ) raw_bindings = bindings.read().get("bindings") if bindings is not None else [] binding_rows = ( raw_bindings @@ -364,19 +662,39 @@ def pump_steward_monitors( break if not isinstance(binding, Mapping): continue + raw_binding_id = binding.get("binding_id") + binding_fail_key = ( + _failure_key("binding", raw_binding_id) + if isinstance(raw_binding_id, str) and raw_binding_id + else "" + ) + actor = binding.get("managed_actor") + session_ids = ( + [str(actor.get("session_id") or ""), steward_background_session_id(raw_binding_id)] + if isinstance(actor, Mapping) and isinstance(raw_binding_id, str) and raw_binding_id + else [] + ) + goal_id = str(actor.get("goal_id") or "") if isinstance(actor, Mapping) else "" + throttle_key = raw_binding_id if isinstance(raw_binding_id, str) else "" + now_mono = time.monotonic() + if _witness_backoff_active( + controller, cache, witnesses, binding_fail_key, session_ids, now_mono, + goal_id=goal_id, binding=binding, throttle_key=throttle_key, + ): + continue try: _process_steward_binding( - controller, - service, - binding, - cache=cache, - fg_checked=fg_checked, - changed=changed, + controller, service, binding, + cache=cache, failures=failures, fg_checked=fg_checked, changed=changed, ) - except (OSError, ValueError, KeyError, TypeError, RuntimeError): + _clear_failure(cache, failures, binding_fail_key, witnesses=witnesses) + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: # One unreadable conversation or unavailable provider must not starve other monitors. - _LOG.warning( - "A native steward monitor is unavailable; original work retained" + _record_session_failure( + controller, cache, failures, witnesses, binding_fail_key, + "A native steward monitor is unavailable; original work retained", + exc, stage="steward_binding", now_mono=now_mono, + session_ids=session_ids, goal_id=goal_id, binding=binding, throttle_key=throttle_key, ) return changed + pump_managed_session_monitors(controller, cancelled=cancelled) @@ -391,16 +709,39 @@ def pump_managed_session_monitors( changed: list[dict[str, object]] = [] monitor = StewardMonitor(controller) - cache = _ensure_float_cache(controller, "_steward_monitor_next_check") + cache: dict[str, float] = _ensure_dict_cache(controller, "_steward_monitor_next_check") + failures: dict[str, tuple[int, str]] = _ensure_dict_cache( + controller, "_steward_monitor_failure_state" + ) + witnesses: dict[str, _WitnessRecord] = _ensure_dict_cache( + controller, "_steward_monitor_failure_witnesses" + ) for session in controller.store.list_sessions(): if cancelled(): break + raw_session_id = session.get("session_id") if isinstance(session, Mapping) else None + raw_goal_id = session.get("goal_id") if isinstance(session, Mapping) else None + session_id = raw_session_id if isinstance(raw_session_id, str) else "" + goal_id = raw_goal_id if isinstance(raw_goal_id, str) else "" + session_ids = [session_id] if session_id else [] + admit_fail_key = _failure_key("session.admit", session_id) if session_id else "" + session_throttle_key = f"session.{session_id}" if session_id else "" + now_mono = time.monotonic() + if _witness_backoff_active( + controller, cache, witnesses, admit_fail_key, session_ids, now_mono, + goal_id=goal_id, throttle_key=session_throttle_key, + ): + continue try: _process_managed_session( - controller, monitor, session, cache=cache, changed=changed + controller, monitor, session, cache=cache, failures=failures, changed=changed ) - except (OSError, ValueError, KeyError, TypeError, RuntimeError): - _LOG.warning( - "A managed Session watch is unavailable; its original task and deadline are retained" + _clear_failure(cache, failures, admit_fail_key, witnesses=witnesses) + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + _record_session_failure( + controller, cache, failures, witnesses, admit_fail_key, + "A managed Session watch is unavailable; its original task and deadline are retained", + exc, stage="managed_session_admit", now_mono=now_mono, + session_ids=session_ids, goal_id=goal_id, throttle_key=session_throttle_key, ) return changed diff --git a/loopx/capabilities/native_chat/steward_reports.py b/loopx/capabilities/native_chat/steward_reports.py index 95ffb2c08b..13426d2992 100644 --- a/loopx/capabilities/native_chat/steward_reports.py +++ b/loopx/capabilities/native_chat/steward_reports.py @@ -290,7 +290,9 @@ def configure(self, binding_id: str, *, operation: str, schedule: dict[str, Any] raise ValueError("native report configuration readback changed") if plan["retires_failed_window"]: self._cancel_failed_window(actor, journal["window"], failure) - getattr(self.controller, "_steward_monitor_next_check", {}).pop(binding_id, None) + from .steward_monitor_pump import clear_steward_monitor_check_hints + + clear_steward_monitor_check_hints(self.controller, binding_id) receipt = {"ok": True, "applied": True, "plan": plan, "report": self.health(binding_id), "model_invoked": False, "external_writes_performed": False} if operation == "cancel": diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index dd036ae051..93d87abd92 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -559,9 +559,7 @@ def report_selection_recovery(self, original: dict[str, Any], *, or (attempt_directory(reports.root, window) / "private-generation.json").exists()} if probe_turn is not None: from ...control_plane.turn_driver.executor import inspect_loopx_turn_journal - from ...control_plane.turn_driver.journal_store import ( - load_turn_journal, turn_journal_path, - ) + from ...control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path actor = request["actor"] keys = {row["payload"].get("resume_turn_key") for row in self.store.events_after(actor["session_id"], probe_turn["turn_id"], None) @@ -570,15 +568,17 @@ def report_selection_recovery(self, original: dict[str, Any], *, return None key = keys.pop() from ...control_plane.effect_runtime import source_number_tokens - journal = load_turn_journal(turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=key)) - current_guard = None - if (journal.get("status") == "failed" - and journal.get("result_kind") == "validation_failed" + if not isinstance(journal, Mapping): + return None + current_guard, journal_status = None, journal.get("status") + if (journal_status == "failed" and journal.get("result_kind") == "validation_failed" and journal.get("validation_stage") == "host_result_contract"): current_guard = self._cleared_replan_guard(actor) if current_guard is None: return None + elif journal_status != "stopped": + return None # Transport canonical observations to the shared typed admission # owner. proof["probe"] = {"turn": probe_turn, diff --git a/loopx/chat/ingress.py b/loopx/chat/ingress.py index 4ff50b8909..4d1540691d 100644 --- a/loopx/chat/ingress.py +++ b/loopx/chat/ingress.py @@ -175,11 +175,22 @@ def terminal(path: Path, payload: dict[str, Any]) -> dict[str, Any] | None: } return None + failed = getattr(self, "_last_read_error_paths", None) + if isinstance(failed, dict): + failed.pop(session_id, None) paths = (path for path in turns_dir.glob("*.json") if not path.name.endswith(".events.json")) fresh: dict[Path, dict[str, Any]] = {} def read_current(path: Path) -> dict[str, Any]: - payload = read(path) + try: + payload = read(path) + except Exception: + failed_map = getattr(self, "_last_read_error_paths", None) + if not isinstance(failed_map, dict): + failed_map = {} + setattr(self, "_last_read_error_paths", failed_map) + failed_map[session_id] = path + raise fresh[path] = payload return payload diff --git a/loopx/chat_server.py b/loopx/chat_server.py index 17a585fe0a..05a0776775 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -10,7 +10,7 @@ from collections.abc import Callable, Mapping import webbrowser from functools import partial -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from http.server import BaseHTTPRequestHandler from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast from urllib.parse import parse_qs, urlparse @@ -117,8 +117,11 @@ from .status_server import ( DEFAULT_EXTENSION_PRESENTATION_SURFACES_PATH, DEFAULT_EXTENSION_PROJECTION_PATH, + DisconnectSafeHTTPServer, + is_client_disconnect_error, is_loopback_host, parse_strict_json_object, + send_http_response, ) @@ -262,7 +265,7 @@ def resolve_lark_cli_for_runtime( ) -class ChatHTTPServer(background_api.BackgroundServicesServerMixin, ThreadingHTTPServer): +class ChatHTTPServer(background_api.BackgroundServicesServerMixin, DisconnectSafeHTTPServer): allow_reuse_address = True registry_path: Path @@ -356,8 +359,7 @@ def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None: self.send_header("X-Content-Type-Options", "nosniff") for key, value in chat_cors_response_headers(self._cors_origin).items(): self.send_header(key, value) - self.end_headers() - self.wfile.write(body) + send_http_response(self, body) def _send_error( self, @@ -454,8 +456,7 @@ def _serve_asset(self, path: str) -> None: self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-cache") self.send_header("X-Content-Type-Options", "nosniff") - self.end_headers() - self.wfile.write(body) + send_http_response(self, body) def _create_session(self) -> None: try: @@ -762,9 +763,10 @@ def _session_snapshot(self, session_id: str) -> None: self._send_error("chat session was not found", status=404) except ValueError as exc: self._send_error(str(exc), status=400) - except (BrokenPipeError, ConnectionResetError): - return - except OSError: + except OSError as exc: + if is_client_disconnect_error(exc): + self.close_connection = True + return self._send_error("Chat history is temporarily unavailable", status=503) def _list_sessions(self) -> None: @@ -856,7 +858,8 @@ def _turn_events(self, session_id: str, turn_id: str) -> None: self.send_header("X-Accel-Buffering", "no") for key, value in chat_cors_response_headers(self._cors_origin).items(): self.send_header(key, value) - self.end_headers() + if not send_http_response(self): + return cursor = str(last_event_id or "0") heartbeat_at = time.monotonic() try: @@ -880,8 +883,11 @@ def _turn_events(self, session_id: str, turn_id: str) -> None: self.wfile.flush() heartbeat_at = time.monotonic() time.sleep(0.05) - except (BrokenPipeError, ConnectionResetError): - return + except OSError as exc: + if is_client_disconnect_error(exc): + self.close_connection = True + return + raise def _steer_turn(self, session_id: str, turn_id: str) -> None: try: @@ -1499,7 +1505,8 @@ def do_GET(self) -> None: if path == "/": self.send_response(302) self.send_header("Location", DEFAULT_CHAT_PATH) - return self.end_headers() + send_http_response(self) + return if path == "/chat" or path.startswith("/chat/"): return self._serve_asset(path) self._send_error("unknown path", status=404) @@ -1576,7 +1583,7 @@ def do_OPTIONS(self) -> None: self.send_response(204) for key, value in chat_cors_response_headers(self._cors_origin).items(): self.send_header(key, value) - self.end_headers() + send_http_response(self) def do_DELETE(self) -> None: if not self._require_loopback_origin(): diff --git a/loopx/status_server.py b/loopx/status_server.py index 1bf9cd449d..746168c587 100644 --- a/loopx/status_server.py +++ b/loopx/status_server.py @@ -1,8 +1,10 @@ from __future__ import annotations +import errno import hashlib import json import math +import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any @@ -219,7 +221,50 @@ def configure_goal_preview_id(payload: dict[str, Any]) -> str: return hashlib.sha256(stable.encode("utf-8")).hexdigest()[:24] -class StatusHTTPServer(ThreadingHTTPServer): +_DISCONNECT_ERRNOS = frozenset({ + errno.EPIPE, + errno.ECONNRESET, + errno.ECONNABORTED, + errno.ESHUTDOWN, +}) +_HTTP_RESPONSE_CHUNK_BYTES = 65536 + + +def is_client_disconnect_error(exc: BaseException | None) -> bool: + """Return True when exc represents a peer closing its HTTP socket early.""" + if isinstance(exc, (BrokenPipeError, ConnectionResetError, ConnectionAbortedError)): + return True + return isinstance(exc, OSError) and exc.errno in _DISCONNECT_ERRNOS + + +def send_http_response(handler: BaseHTTPRequestHandler, body: bytes | None = None) -> bool: + """Flush response headers and write body chunks, absorbing peer disconnects cleanly.""" + try: + handler.end_headers() + if body: + for offset in range(0, len(body), _HTTP_RESPONSE_CHUNK_BYTES): + handler.wfile.write(body[offset : offset + _HTTP_RESPONSE_CHUNK_BYTES]) + flush = getattr(handler.wfile, "flush", None) + if callable(flush): + flush() + except OSError as exc: + if is_client_disconnect_error(exc): + handler.close_connection = True + return False + raise + return True + + +class DisconnectSafeHTTPServer(ThreadingHTTPServer): + """ThreadingHTTPServer that suppresses tracebacks for benign client disconnects.""" + + def handle_error(self, request: Any, client_address: Any) -> None: + if is_client_disconnect_error(sys.exc_info()[1]): + return + super().handle_error(request, client_address) + + +class StatusHTTPServer(DisconnectSafeHTTPServer): allow_reuse_address = True registry_path: Path @@ -370,14 +415,13 @@ def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None: self.send_header("Cache-Control", "no-store") for key, value in cors_response_headers(self.headers.get("Origin")).items(): self.send_header(key, value) - self.end_headers() - self.wfile.write(body) + send_http_response(self, body) def do_OPTIONS(self) -> None: self.send_response(204) for key, value in cors_response_headers(self.headers.get("Origin")).items(): self.send_header(key, value) - self.end_headers() + send_http_response(self) def _read_json_body(self) -> dict[str, Any]: content_length = int(self.headers.get("Content-Length") or "0") diff --git a/tests/capabilities/test_steward_monitor_contract.py b/tests/capabilities/test_steward_monitor_contract.py index 92164c0f43..8553ba3f38 100644 --- a/tests/capabilities/test_steward_monitor_contract.py +++ b/tests/capabilities/test_steward_monitor_contract.py @@ -6,7 +6,9 @@ from collections.abc import Mapping, Sequence from contextlib import AbstractContextManager, nullcontext from datetime import datetime, timedelta, timezone +import hashlib import json +import os from pathlib import Path import re from types import MappingProxyType @@ -679,3 +681,721 @@ def run_cfg(operation: str, plan_todo: object) -> dict[str, object]: none_pause = run_cfg("pause", None) assert none_pause == {"ok": True, "applied": True, "plan": {"plan_id": "plan-1", "todo": None}} assert writes == [] + + +def test_steward_pump_failure_backoff_dedup_and_clear( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + import errno + import logging + from loopx.capabilities.native_chat import steward_reports as reports_mod + + clock = {"now": 1000.0} + monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: clock["now"]) + base_utc = datetime(2026, 1, 1, 0, 0, 0, tzinfo=timezone.utc) + + class _FakeDateTime: + @staticmethod + def now(tz: timezone | None = None) -> datetime: + dt = base_utc + timedelta(seconds=clock["now"] - 1000.0) + return dt if tz is not None else dt.replace(tzinfo=None) + + @staticmethod + def fromisoformat(value: str) -> datetime: + return datetime.fromisoformat(value) + + monkeypatch.setattr(steward_monitor_pump, "datetime", _FakeDateTime) + + store = ChatSessionStore(tmp_path / "chat") + session = store.create_session( + goal_id="steward-agent-b-backoff", + agent_id="steward", + adapter_kind="codex-app-server", + upstream_thread_id="th-backoff", + ) + binding = { + "binding_id": "b-backoff", + "enabled": True, + "managed_actor": {"goal_id": "steward-agent-b-backoff", "agent_id": "steward", "session_id": session["session_id"]}, + } + bindings = _StubBindings(tmp_path / "bindings.json", bindings_rows=[binding]) + controller = _StubController(tmp_path, bindings=bindings) + controller.store = store + + monkeypatch.setattr( + steward_monitor_pump, + "_report_config_for_goal", + lambda _ctrl, _gid: {"enabled": True, "profile_preset": "portfolio-progress"}, + ) + + frontier_calls: list[float] = [] + report_mode: dict[str, object] = { + "exc": PermissionError( + errno.EACCES, + "Permission denied", + "/Users/alice/dir with spaces/secret file.json", + ), + } + + class FakeReports: + def __init__(self, _ctrl: object) -> None: + pass + + def frontier(self, _binding: Mapping[str, object]) -> tuple[dict[str, object] | None, bool]: + frontier_calls.append(clock["now"]) + exc = report_mode["exc"] + if isinstance(exc, BaseException): + raise exc + return None, False + + monkeypatch.setattr(reports_mod, "StewardReports", FakeReports) + soon_due = (base_utc + timedelta(seconds=15)).isoformat() + todo_row: StewardTodoRecord = { + "todo_id": "todo-soon", + "task_class": "continuous_monitor", + "status": "open", + "target_key": TARGET, + "next_due_at": soon_due, + } + monkeypatch.setattr(StewardMonitor, "todos", lambda _self, _actor: [todo_row]) + monkeypatch.setattr(StewardMonitor, "due_monitors", lambda _self, _actor, *, todos=None: []) + monkeypatch.setattr(StewardMonitor, "runnable_advancement_todos", lambda _self, _actor, *, todos=None: []) + + caplog.set_level(logging.WARNING, logger=steward_monitor_pump.__name__) + # First failure at t=1000 logs once with allowlisted diagnostics (no path text even with spaces) + # and sets 60s report backoff (until 1060). + # _schedule_soonest_monitor_backoff sets binding next-check to t=1015 (15s remaining). + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0] + assert len(caplog.records) == 1 + msg0 = caplog.records[0].getMessage() + assert "An original steward report is unavailable" in msg0 + assert "stage=steward_report" in msg0 + assert "error=PermissionError" in msg0 + assert "errno=EACCES" in msg0 + for leaked in ("Users", "alice", "dir with spaces", "secret", "Permission denied", "/"): + assert leaked not in msg0 + + # Simulate human busy -> idle flip (`fg_checked=False`) at t=1010 AND soon-due wake at t=1020: + # foreground fast-path and _schedule_soonest_monitor_backoff must NOT bypass report failure backoff. + controller._steward_monitor_fg_idle_checked["b-backoff"] = False # type: ignore[attr-defined] + clock["now"] = 1010.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + clock["now"] = 1020.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0] + assert len(caplog.records) == 1 + + # At t=1081 (past binding check 1020+60 and report 60s backoff), frontier retries -> backs off 120s (until 1201), + # and identical exception signature emits zero duplicate WARNING logs. + clock["now"] = 1081.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0, 1081.0] + assert len(caplog.records) == 1 + + # Even with fg_checked=False flip inside 120s window (t=1150 -> binding check 1210), frontier stays backed off. + clock["now"] = 1150.0 + controller._steward_monitor_fg_idle_checked["b-backoff"] = False # type: ignore[attr-defined] + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0, 1081.0] + + # At t=1211 (past 120s backoff 1201 and binding check 1210), a different exception emits one transition warning (240s -> 1451). + report_mode["exc"] = RuntimeError("sensitive text /tmp/never logged/here") + clock["now"] = 1211.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0, 1081.0, 1211.0] + assert len(caplog.records) == 2 + msg1 = caplog.records[1].getMessage() + assert "stage=steward_report, error=RuntimeError" in msg1 + assert "sensitive text" not in msg1 + assert "never logged" not in msg1 + + clock["now"] = 1440.0 + controller._steward_monitor_fg_idle_checked["b-backoff"] = False # type: ignore[attr-defined] + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0, 1081.0, 1211.0] + + # Explicit clear resets backoff & dedup signature; recovery also clears for next transition. + steward_monitor_pump.clear_steward_monitor_check_hints(_as_controller(controller), "b-backoff") + report_mode["exc"] = None + clock["now"] = 1441.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert frontier_calls == [1000.0, 1081.0, 1211.0, 1441.0] + + report_mode["exc"] = ValueError("provider verification failed at /Users/alice/.loopx/private-state") + steward_monitor_pump.clear_steward_monitor_check_hints(_as_controller(controller), "b-backoff") + clock["now"] = 1442.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert len(caplog.records) == 3 + + +def test_steward_pump_monitor_outer_and_managed_session_backoff( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + import logging + from loopx.capabilities.native_chat import ( + session_calendar_tasks as cal_mod, + steward_managed_mode as managed_mod, + steward_reports as reports_mod, + steward_turn as turn_mod, + ) + + clock = {"now": 2000.0} + monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: clock["now"]) + + store = ChatSessionStore(tmp_path / "chat") + s_bad = store.create_session( + goal_id="steward-agent-b-bad", agent_id="steward", adapter_kind="codex-app-server", upstream_thread_id="th-bad" + ) + s_good = store.create_session( + goal_id="steward-agent-b-good", agent_id="steward", adapter_kind="codex-app-server", upstream_thread_id="th-good" + ) + s_managed = store.create_session( + goal_id="goal-managed-1", agent_id="codex", adapter_kind="codex-app-server", + upstream_thread_id="th-managed", + ) + monkeypatch.setattr( + store, + "list_sessions", + lambda: [s_bad, s_good, {**s_managed, "managed_agent_id": "agent-1"}], + ) + bindings = _StubBindings( + tmp_path / "bindings.json", + bindings_rows=[ + {"binding_id": "b-bad", "enabled": True, "managed_actor": {"goal_id": "steward-agent-b-bad", "agent_id": "steward", "session_id": s_bad["session_id"]}}, + {"binding_id": "b-good", "enabled": True, "managed_actor": {"goal_id": "steward-agent-b-good", "agent_id": "steward", "session_id": s_good["session_id"]}}, + ], + ) + controller = _StubController(tmp_path, bindings=bindings) + controller.store = store + + due_fail: StewardTodoRecord = { + "todo_id": "m-fail", "task_class": "continuous_monitor", "status": "open", + "target_key": TARGET, "next_due_at": "2020-01-01T00:00:00Z", + } + due_ok: StewardTodoRecord = { + "todo_id": "m-ok", "task_class": "continuous_monitor", "status": "open", + "target_key": TARGET, "next_due_at": "2020-01-01T00:00:00Z", + } + managed_soon = (datetime.now(timezone.utc) + timedelta(seconds=5)).isoformat() + managed_watch: StewardTodoRecord = { + "todo_id": "w-1", "task_class": "continuous_monitor", "status": "open", + "target_key": f"managed-session-watch.{s_managed['session_id']}", "next_due_at": managed_soon, + } + + todo_calls_bad: list[float] = [] + + def fake_todos(_self: object, actor: Mapping[str, object]) -> list[StewardTodoRecord]: + gid = str(actor.get("goal_id") or "") + if gid == "steward-agent-b-bad": + todo_calls_bad.append(clock["now"]) + raise RuntimeError("CanonicalAuthorityRequired: migrate goal") + if gid == "goal-managed-1": + return [managed_watch] + return [due_fail, due_ok] + + submit_calls: list[str] = [] + + class FakeHost: + def __init__(self, _ctrl: object) -> None: + pass + + @staticmethod + def background_session_id(bid: str) -> str: + return f"steward.background.{bid}" + + def submit(self, _bid: str, *, todo_id: str, **_kw: object) -> tuple[dict[str, object], bool]: + submit_calls.append(todo_id) + if todo_id == "m-fail": + raise ValueError("monitor identity unavailable at /tmp/private/sub") + return {"turn_id": f"turn-{todo_id}", "status": "queued"}, True + + monkeypatch.setattr(StewardMonitor, "todos", fake_todos) + monkeypatch.setattr(StewardMonitor, "due_monitors", lambda _self, _actor, *, todos=None: [due_fail, due_ok]) + monkeypatch.setattr(StewardMonitor, "runnable_advancement_todos", lambda _self, _actor, *, todos=None: []) + monkeypatch.setattr(turn_mod, "StewardTurnHost", FakeHost) + + monkeypatch.setattr( + steward_monitor_pump, + "_report_config_for_goal", + lambda _ctrl, gid: ( + {"enabled": True, "profile_preset": "weekly-progress", "route_ref": f"managed-session:{s_managed['session_id']}"} + if gid == "goal-managed-1" else {} + ), + ) + + class FakeManagedTurn: + def __init__(self, _ctrl: object) -> None: + pass + + def _request(self, sid: str, aid: str, _op: str) -> dict[str, object]: + return {"actor": {"goal_id": "goal-managed-1", "agent_id": aid, "session_id": sid}} + + def admit(self, _req: Mapping[str, object]) -> None: + return None + + managed_report_calls: list[float] = [] + + class FakeManagedReports: + def __init__(self, _ctrl: object) -> None: + pass + + def frontier(self, _sid: str) -> tuple[dict[str, object] | None, bool]: + managed_report_calls.append(clock["now"]) + raise ValueError("managed session report auth expired") + + monkeypatch.setattr(managed_mod, "ManagedSessionTurn", FakeManagedTurn) + monkeypatch.setattr(reports_mod, "ManagedSessionReports", FakeManagedReports) + monkeypatch.setattr(cal_mod, "SessionCalendarTasks", FakeManagedReports) + monkeypatch.setattr(steward_monitor_pump, "monitor_todo_is_due", lambda _todo: False) + + caplog.set_level(logging.WARNING, logger=steward_monitor_pump.__name__) + out = steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + # Healthy second binding's second due monitor still ran even though b-bad & m-fail failed! + assert [row["turn_id"] for row in out] == ["turn-m-ok"] + assert todo_calls_bad == [2000.0] + assert submit_calls == ["m-fail", "m-ok"] + assert managed_report_calls == [2000.0] + assert len(caplog.records) == 3 + + # Clear b-good's normal check cache at t=2006s and simulate b-good background now idle, plus check b-bad/m-fail/managed backoff: + # Even at t=2006s (past the 5s managed watch remaining window), managed_report_calls stays blocked for 60s! + controller._steward_monitor_next_check.pop("b-good", None) # type: ignore[attr-defined] + clock["now"] = 2006.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert todo_calls_bad == [2000.0] + assert submit_calls == ["m-fail", "m-ok", "m-ok"] + assert managed_report_calls == [2000.0] + assert len(caplog.records) == 3 + + # After 60s backoff expires (t=2062), failing lanes retry once without duplicate warnings, doubling to 120s. + controller._steward_monitor_next_check.pop("b-good", None) # type: ignore[attr-defined] + clock["now"] = 2062.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(controller)) + assert todo_calls_bad == [2000.0, 2062.0] + assert submit_calls == ["m-fail", "m-ok", "m-ok", "m-fail", "m-ok"] + assert managed_report_calls == [2000.0, 2062.0] + assert len(caplog.records) == 3 + + +def test_managed_session_watch_failure_does_not_starve_report_and_witness_recovers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + import logging + from loopx.capabilities.native_chat import ( + steward_managed_mode as managed_mod, + steward_reports as reports_mod, + ) + + clock = {"now": 1000.0} + monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: clock["now"]) + + store = ChatSessionStore(tmp_path / "chat") + s_managed = store.create_session( + goal_id="goal-managed-watch", agent_id="codex", adapter_kind="codex-app-server", + upstream_thread_id="th-watch", + ) + monkeypatch.setattr( + store, + "list_sessions", + lambda: [{**s_managed, "managed_agent_id": "agent-1"}], + ) + bindings = _StubBindings(tmp_path / "bindings.json", bindings_rows=[]) + controller = _StubController(tmp_path, bindings=bindings) + controller.store = store + + monkeypatch.setattr( + steward_monitor_pump, + "_report_config_for_goal", + lambda _ctrl, _gid: { + "enabled": True, + "profile_preset": "weekly-progress", + "route_ref": f"managed-session:{s_managed['session_id']}", + }, + ) + + watch_todo: StewardTodoRecord = { + "todo_id": "w-due", "task_class": "continuous_monitor", "status": "open", + "target_key": f"managed-session-watch.{s_managed['session_id']}", + "next_due_at": "2020-01-01T00:00:00Z", + } + monkeypatch.setattr(StewardMonitor, "todos", lambda _self, _actor: [watch_todo]) + monkeypatch.setattr(steward_monitor_pump, "monitor_todo_is_due", lambda _todo: True) + + watch_calls: list[float] = [] + report_calls: list[float] = [] + report_ready = {"created": False} + + class FakeManagedTurn: + def __init__(self, _ctrl: object) -> None: + pass + + def _request(self, sid: str, aid: str, _op: str) -> dict[str, object]: + return {"actor": {"goal_id": "goal-managed-watch", "agent_id": aid, "session_id": sid}} + + def admit(self, _req: Mapping[str, object]) -> None: + return None + + def submit(self, _sid: str, **_kw: object) -> tuple[dict[str, object], bool]: + watch_calls.append(clock["now"]) + raise RuntimeError("watch submission unavailable /Users/private/dir with spaces") + + class FakeManagedReports: + def __init__(self, _ctrl: object) -> None: + pass + + def frontier(self, _sid: str) -> tuple[dict[str, object] | None, bool]: + report_calls.append(clock["now"]) + if report_ready["created"]: + return {"turn_id": "report-turn-1122"}, True + return None, False + + monkeypatch.setattr(managed_mod, "ManagedSessionTurn", FakeManagedTurn) + monkeypatch.setattr(reports_mod, "ManagedSessionReports", FakeManagedReports) + + caplog.set_level(logging.WARNING, logger=steward_monitor_pump.__name__) + # t=1000: watch fails -> 60s watch backoff (until 1060). + assert steward_monitor_pump.pump_managed_session_monitors(_as_controller(controller)) == [] + assert watch_calls == [1000.0] + assert report_calls == [1000.0] + assert len(caplog.records) == 1 + assert "stage=managed_session_watch, error=RuntimeError" in caplog.records[0].getMessage() + assert "dir with spaces" not in caplog.records[0].getMessage() + + # t=1061: watch retries and fails -> 120s watch backoff (until 1181), while session normal check is +60s (1121). + clock["now"] = 1061.0 + assert steward_monitor_pump.pump_managed_session_monitors(_as_controller(controller)) == [] + assert watch_calls == [1000.0, 1061.0] + assert report_calls == [1000.0, 1061.0] + assert len(caplog.records) == 1 + + # t=1122: healthy weekly-progress report becomes ready inside watch's 120s backoff and MUST still submit! + report_ready["created"] = True + clock["now"] = 1122.0 + out = steward_monitor_pump.pump_managed_session_monitors(_as_controller(controller)) + assert [row["turn_id"] for row in out] == ["report-turn-1122"] + assert watch_calls == [1000.0, 1061.0] + assert report_calls == [1000.0, 1061.0, 1122.0] + + # Verify outer binding storage witness: corrupted session stays backed off while untouched, + # then recovers immediately on repair without clearing _steward_monitor_next_check. + session_path = store._session_path(s_managed["session_id"]) + original_bytes = session_path.read_bytes() + b_sid = store.create_session( + goal_id="steward-agent-b-witness", agent_id="steward", adapter_kind="codex-app-server", + upstream_thread_id="th-witness", + ) + b_path = store._session_path(b_sid["session_id"]) + b_original = b_path.read_bytes() + b_bindings = _StubBindings( + tmp_path / "b-bindings.json", + bindings_rows=[{ + "binding_id": "b-witness", + "enabled": True, + "managed_actor": {"goal_id": "steward-agent-b-witness", "agent_id": "steward", "session_id": b_sid["session_id"]}, + }], + ) + b_ctrl = _StubController(tmp_path, bindings=b_bindings) + b_ctrl.store = store + monkeypatch.setattr(store, "list_sessions", lambda: []) + b_path.write_bytes(b"\xff") + load_calls: list[str] = [] + orig_load = store.load_session + + def tracked_load(sid: str) -> dict[str, object] | None: + load_calls.append(sid) + return orig_load(sid) + + monkeypatch.setattr(store, "load_session", tracked_load) + monkeypatch.setattr(StewardMonitor, "todos", lambda _self, _actor: []) + monkeypatch.setattr(StewardMonitor, "due_monitors", lambda _self, _actor, *, todos=None: []) + monkeypatch.setattr(StewardMonitor, "runnable_advancement_todos", lambda _self, _actor, *, todos=None: []) + + clock["now"] = 2000.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(b_ctrl)) + assert load_calls == [b_sid["session_id"]] + # Same tick/unchanged corrupted file at t=2003 stays backed off without re-reading disk JSON. + clock["now"] = 2003.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(b_ctrl)) + assert load_calls == [b_sid["session_id"]] + # Repairing the file on disk invalidates the witness immediately at t=2004 without waiting 60s. + b_path.write_bytes(b_original) + clock["now"] = 2004.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(b_ctrl)) + assert len(load_calls) >= 2 + assert session_path.read_bytes() == original_bytes + + +def test_witness_backoff_stat_count_stays_o1_across_historical_turns( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = {"now": 1000.0} + monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: clock["now"]) + orig_stat = Path.stat + orig_scandir = os.scandir + + turn_dir_stat_counts: list[int] = [] + total_stat_counts: list[int] = [] + for history_count in (32, 128, 512): + clock["now"] += 100.0 + root = tmp_path / f"hist-{history_count}" + bindings = _StubBindings(root / "bindings.json", bindings_rows=[]) + ctrl = _StubController(root, bindings=bindings) + store = ctrl.store + created = store.create_session( + goal_id="steward-goal-o1", agent_id="steward", adapter_kind="codex-app-server", + upstream_thread_id=f"th-{history_count}", + ) + sid = str(created["session_id"]) + turns_dir = store._session_dir(sid) / "turns" + turns_dir.mkdir(parents=True, exist_ok=True) + for idx in range(history_count): + tid = f"turn-hist-{idx:04d}" + (turns_dir / f"{tid}.json").write_text( + json.dumps({ + "schema_version": "loopx_chat_turn_state_v1", + "session_id": sid, "turn_id": tid, "status": "completed", + }), + encoding="utf-8", + ) + (turns_dir / f"{tid}.events.json").write_text("[]", encoding="utf-8") + + queued, _ = store.create_queued_turn( + sid, client_turn_id=f"q-{history_count}", message="keep queued", origin="web" + ) + q_path = store._turn_path(sid, str(queued["turn_id"])) + orig_q_bytes = q_path.read_bytes() + q_path.write_bytes(b"\xff") + + bindings.bindings_rows = [{ + "binding_id": f"b-o1-{history_count}", "enabled": True, + "managed_actor": {"goal_id": "steward-goal-o1", "agent_id": "steward", "session_id": sid}, + }] + monkeypatch.setattr(store, "list_sessions", lambda: []) + monkeypatch.setattr(StewardMonitor, "todos", lambda _self, _actor: []) + monkeypatch.setattr(StewardMonitor, "due_monitors", lambda _self, _actor, *, todos=None: []) + monkeypatch.setattr(StewardMonitor, "runnable_advancement_todos", lambda _self, _actor, *, todos=None: []) + + load_calls: list[str] = [] + orig_load = store.load_session + + def tracked_load(target_sid: str) -> dict[str, object] | None: + load_calls.append(target_sid) + return cast("dict[str, object] | None", orig_load(target_sid)) + + monkeypatch.setattr(store, "load_session", tracked_load) + + # Initial failure populates O(1) witness (no scandir of historical turns). + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + initial_loads = len(load_calls) + assert initial_loads >= 1 + + stat_paths: list[Path] = [] + scandir_targets: list[object] = [] + + def tracked_stat(self: Path, *, follow_symlinks: bool = True) -> os.stat_result: + stat_paths.append(self) + return orig_stat(self, follow_symlinks=follow_symlinks) + + def tracked_scandir(path: str | bytes | os.PathLike[str] | os.PathLike[bytes] = ".") -> object: + scandir_targets.append(path) + return orig_scandir(path) + + with monkeypatch.context() as mc: + mc.setattr(Path, "stat", tracked_stat) + mc.setattr(os, "scandir", tracked_scandir) + clock["now"] += 3.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + + assert len(load_calls) == initial_loads + assert scandir_targets == [] + turn_stats = [p for p in stat_paths if p == turns_dir or p.parent == turns_dir] + assert q_path in turn_stats + assert not any(p.name.startswith("turn-hist-") for p in turn_stats) + turn_dir_stat_counts.append(len(turn_stats)) + total_stat_counts.append(len(stat_paths)) + + # In-place repair of ONLY the broken queued turn clears backoff immediately. + q_path.write_bytes(orig_q_bytes) + clock["now"] += 1.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert len(load_calls) > initial_loads + + assert len(set(turn_dir_stat_counts)) == 1 + assert len(set(total_stat_counts)) == 1 + + +def _write_test_registry_envelope(path: Path, goals: list[dict[str, object]]) -> None: + payload: dict[str, object] = {"goals": goals} + canonical = json.dumps(payload, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + envelope: list[object] = [ + { + "schema_version": "loopx_project_registry_envelope_v1", + "minimum_writer_protocol": "goal_instance_v1", + "payload_sha256": "sha256:" + hashlib.sha256(canonical).hexdigest(), + }, + payload, + ] + path.write_text(json.dumps(envelope, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def test_witness_backoff_ignores_unrelated_goal_and_binding_edits( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = {"now": 1000.0} + monkeypatch.setattr(steward_monitor_pump.time, "monotonic", lambda: clock["now"]) + + store = ChatSessionStore(tmp_path / "chat") + created = store.create_session( + goal_id="steward-goal-target", agent_id="steward", adapter_kind="codex-app-server", + upstream_thread_id="th-target", + ) + sid = str(created["session_id"]) + monkeypatch.setattr(store, "list_sessions", lambda: []) + + target_goal: dict[str, object] = {"id": "steward-goal-target", "description": "target-v1"} + unrelated_goal: dict[str, object] = {"id": "steward-goal-other", "description": "other-v1"} + b_bad: dict[str, object] = { + "binding_id": "b-bad", "enabled": True, + "managed_actor": {"goal_id": "steward-goal-target", "agent_id": "steward", "session_id": sid}, + } + b_other: dict[str, object] = { + "binding_id": "b-other", "enabled": False, + "managed_actor": {"goal_id": "steward-goal-other", "agent_id": "steward", "session_id": "s-other"}, + } + bindings = _StubBindings(tmp_path / "bindings.json", bindings_rows=[b_bad, b_other]) + ctrl = _StubController(tmp_path, bindings=bindings) + ctrl.store = store + _write_test_registry_envelope(ctrl.registry_path, [target_goal, unrelated_goal]) + + todos_calls: list[float] = [] + + def failing_todos(_self: StewardMonitor, _actor: Mapping[str, object]) -> list[StewardTodoRecord]: + todos_calls.append(clock["now"]) + raise RuntimeError("transient-store-err") + + monkeypatch.setattr(StewardMonitor, "todos", failing_todos) + + # t=1000: failure enters 60s backoff until t=1060. + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert todos_calls == [1000.0] + + # t=1003: edit an unrelated Goal in registry.json AND an unrelated binding -> backoff MUST remain active. + unrelated_goal["description"] = "other-v2" + _write_test_registry_envelope(ctrl.registry_path, [target_goal, unrelated_goal]) + b_other["notes"] = "unrelated-binding-edited" + clock["now"] = 1003.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert todos_calls == [1000.0] + + # t=1004: edit ONLY the target Goal in registry.json -> witness invalidates backoff immediately. + target_goal["description"] = "target-v2" + _write_test_registry_envelope(ctrl.registry_path, [target_goal, unrelated_goal]) + clock["now"] = 1004.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert todos_calls == [1000.0, 1004.0] + + # t=1005: another unrelated binding edit stays ignored. + b_other["notes"] = "unrelated-binding-edited-again" + clock["now"] = 1005.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert todos_calls == [1000.0, 1004.0] + + # t=1006: editing the target binding itself invalidates backoff immediately. + b_bad["notes"] = "target-binding-updated" + clock["now"] = 1006.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert todos_calls == [1000.0, 1004.0, 1006.0] + + +def test_registry_goal_witness_cache_reuses_snapshot_across_four_bindings( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import time + + clock = {"now": 1000.0} + monkeypatch.setattr(time, "monotonic", lambda: clock["now"]) + + bindings = _StubBindings(tmp_path / "bindings.json", bindings_rows=[]) + ctrl = _StubController(tmp_path, bindings=bindings) + store = ctrl.store + monkeypatch.setattr(store, "list_sessions", lambda: []) + + target_goals: list[dict[str, object]] = [] + unrelated_goals: list[dict[str, object]] = [ + {"id": f"goal-extra-{idx:03d}", "description": f"extra-{idx}"} + for idx in range(64) + ] + corrupt_sids: list[str] = [] + for idx in range(4): + gid = f"goal-target-{idx}" + target_goals.append({"id": gid, "description": f"target-{idx}-v1"}) + created = store.create_session( + goal_id=gid, agent_id="steward", adapter_kind="codex-app-server", + upstream_thread_id=f"th-r4-{idx}", + ) + sid = str(created["session_id"]) + corrupt_sids.append(sid) + store._session_path(sid).write_bytes(b"\xff") + bindings.bindings_rows.append({ + "binding_id": f"b-r4-{idx}", + "enabled": True, + "managed_actor": {"goal_id": gid, "agent_id": "steward", "session_id": sid}, + }) + + _write_test_registry_envelope(ctrl.registry_path, [*target_goals, *unrelated_goals]) + + load_calls: list[str] = [] + orig_load = store.load_session + + def tracked_load(target_sid: str) -> dict[str, object] | None: + load_calls.append(target_sid) + return cast("dict[str, object] | None", orig_load(target_sid)) + + monkeypatch.setattr(store, "load_session", tracked_load) + + reg_read_bytes: list[int] = [] + orig_read_bytes = Path.read_bytes + + def tracked_read_bytes(self: Path) -> bytes: + data = orig_read_bytes(self) + if self == ctrl.registry_path: + reg_read_bytes.append(len(data)) + return data + + monkeypatch.setattr(Path, "read_bytes", tracked_read_bytes) + + # Initial failing tick across 4 corrupt sessions reads registry.json at most once. + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert load_calls == corrupt_sids + assert len(reg_read_bytes) == 1 + + # Over 4 unchanged idle ticks, registry.json is read 0 times (0 bytes) with 0 premature retries. + reg_read_bytes.clear() + before_idle = len(load_calls) + for _ in range(4): + clock["now"] += 3.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert reg_read_bytes == [] + assert len(load_calls) == before_idle + + # Mutating an unrelated Goal reloads registry.json at most once and preserves all 4 active backoffs. + unrelated_goals[0]["description"] = "extra-0-edited" + _write_test_registry_envelope(ctrl.registry_path, [*target_goals, *unrelated_goals]) + clock["now"] += 3.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert len(reg_read_bytes) == 1 + assert len(load_calls) == before_idle + clock["now"] += 3.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert len(reg_read_bytes) == 1 + assert len(load_calls) == before_idle + + # Mutating target Goal #2 reloads once and immediately invalidates ONLY binding #2's witness. + reg_read_bytes.clear() + target_goals[2]["description"] = "target-2-edited" + _write_test_registry_envelope(ctrl.registry_path, [*target_goals, *unrelated_goals]) + clock["now"] += 3.0 + steward_monitor_pump.pump_steward_monitors(_as_controller(ctrl)) + assert len(reg_read_bytes) == 1 + assert load_calls[before_idle:] == [corrupt_sids[2]] diff --git a/tests/test_native_steward_reports.py b/tests/test_native_steward_reports.py index 1bccd8622b..ca7ecc9014 100644 --- a/tests/test_native_steward_reports.py +++ b/tests/test_native_steward_reports.py @@ -2735,3 +2735,117 @@ def now(cls, tz=None): else: assert frozen["reporting"] == expected_default assert "360" in frozen["reporting"] and "https://github.com/example-org/example-repo/pull/123" in frozen["reporting"] + + +def test_report_selection_recovery_fails_closed_for_task_postcondition_probe_without_looping( + steward, tmp_path, monkeypatch, caplog +): + import logging + from datetime import timezone + from loopx.capabilities.native_chat.steward_monitor import StewardMonitor + from loopx.capabilities.native_chat.steward_turn import StewardTurnHost + from loopx.capabilities.periodic_report import cadence_runtime + from loopx.configure_goal import configure_goal + from loopx.control_plane.turn_driver.journal_store import load_turn_journal, turn_journal_path + import loopx.capabilities.native_chat.steward_reports as report_host + + store, runtime, _, transport, binding, capture, _ = steward + point = datetime.now(timezone.utc).replace(hour=9, minute=1, second=0, microsecond=0) - timedelta(days=2) + + class CalendarClock(datetime): + @classmethod + def now(cls, tz=None): + return point.astimezone(tz) if tz else point.replace(tzinfo=None) + + monkeypatch.setattr(report_host, "datetime", CalendarClock) + monkeypatch.setattr(cadence_runtime, "datetime", CalendarClock) + sid, actor, reports, _ = configured(steward, tmp_path, monkeypatch, "sqlite") + owner = binding["binding_id"] + assert configure_goal( + registry_path=runtime.registry_path, goal_id=actor["goal_id"], + execution_replan_after_turns=1, execute=True, + )["ok"] + install_model(steward, tmp_path, sid) + assert finish(runtime, pump_steward_monitors(runtime)[0])["response"]["native_loopx"]["status"] == "committed" + assert transport.steward_reports.reconcile() == 1 + + point += timedelta(days=1) + runtime._steward_monitor_next_check.clear() + rejected = finish(runtime, pump_steward_monitors(runtime)[0]) + assert rejected["response"]["native_loopx"]["error_code"] == "turn_todo_selection_deferred" + + bad_vision = { + "schema_version": "goal_vision_replan_contract_v0", + "state": "active", + "vision_patch": {"vision_summary": "Keep reporting.", "acceptance_summary": "Validate full report."}, + "path_delta": { + "outcome": "replan", + "prior_assumption": "Old assumption", + "observed_reality": "Reality", + "retained": ["Same report route"], + "changed": ["Updated baseline"], + "evidence_refs": ["fixture:evidence"], + }, + } + bad_outcome = { + "result_kind": "replan_required", + "classification": "outcome_gap_without_blocked_fields", + "delivery_batch_scale": "implementation", + "delivery_outcome": "outcome_gap", + "work_evidence": ["Observed gap"], + "validation_evidence": ["Validated check"], + "path_delta_mode": "material_replan", + "agent_vision_json": json.dumps(bad_vision), + "summary": "Trigger failed validation probe.", + "next_action": "Retain safely.", + } + helper = tmp_path / "report_model.py" + helper.write_text( + _REPORT_MODEL_SOURCE.replace("def fake_report_model(", "def report_only(") + + "\ndef fake_report_model(params):\n" + + " import json\n" + + " prompt = '\\n'.join(row.get('text', '') for row in params.get('input', []) if isinstance(row, dict))\n" + + " request = json.JSONDecoder().raw_decode(prompt.split('Turn request:', 1)[1].lstrip())[0]\n" + + " if request.get('detail_ref', {}).get('replan_action_packet'):\n" + + " return " + repr(json.dumps(bad_outcome)) + "\n" + + " return report_only(params)\n" + ) + runtime._steward_monitor_next_check.clear() + retry_turn = finish(runtime, pump_steward_monitors(runtime)[0]) + replan_events = [ + row["payload"] for row in store.events_after(sid, retry_turn["turn_id"], None) + if row["kind"] == "native_loopx.replan_result" + ] + assert len(replan_events) == 1 + turn_key = replan_events[0]["resume_turn_key"] + jpath = turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=turn_key) + journal = load_turn_journal(jpath) + journal["validation_stage"] = "task_postcondition" + jpath.write_text(json.dumps(journal), encoding="utf-8") + + assert configure_goal( + registry_path=runtime.registry_path, goal_id=actor["goal_id"], + execution_replan_after_turns=6, execute=True, + )["ok"] + host = StewardTurnHost(runtime) + assert host.report_selection_recovery(rejected, probe_turn=retry_turn) is None + + caplog.set_level(logging.WARNING, logger="loopx.capabilities.native_chat.steward_monitor_pump") + calls = capture.read_bytes() + runtime._steward_monitor_next_check.clear() + assert not pump_steward_monitors(runtime) + runtime._steward_monitor_next_check.clear() + assert not pump_steward_monitors(runtime) + current_binding = next( + row for row in runtime.project_contexts.conversation_bindings.read()["bindings"] + if row["binding_id"] == owner + ) + accepted, created = reports.frontier(dict(current_binding)) + assert created is False and accepted["turn_id"] == retry_turn["turn_id"] + assert not caplog.records + assert capture.read_bytes() == calls + _, window = reports.current_window(owner) + assert window is not None and any( + row["target_key"] == window["window_id"] and row["status"] == "open" + for row in StewardMonitor(runtime).todos(actor) + ) diff --git a/tests/test_status_server_cors.py b/tests/test_status_server_cors.py index 6f7f8eed63..a2f43288d5 100644 --- a/tests/test_status_server_cors.py +++ b/tests/test_status_server_cors.py @@ -168,3 +168,121 @@ def test_strict_json_accepts_nested_finite_exponents() -> None: assert parse_strict_json_object(b'{"values":[1e308,{"small":-1e-308}]}') == { "values": [1e308, {"small": -1e-308}] } + + +@pytest.mark.parametrize( + "disconnect_exc", + [ + BrokenPipeError(32, "Broken pipe"), + ConnectionResetError(54, "Connection reset by peer"), + ConnectionAbortedError(53, "Software caused connection abort"), + ], +) +@pytest.mark.parametrize("fail_during", ["headers", "chunk", "flush"]) +def test_send_http_response_absorbs_client_disconnects_and_closes_connection( + disconnect_exc: OSError, fail_during: str +) -> None: + from types import SimpleNamespace + from loopx.status_server import send_http_response + + writes: list[bytes] = [] + + class BrokenWriter: + def write(self, data: bytes) -> int: + writes.append(data) + if fail_during == "chunk" and len(writes) >= 2: + raise disconnect_exc + return len(data) + + def flush(self) -> None: + if fail_during == "flush": + raise disconnect_exc + + handler = SimpleNamespace( + close_connection=False, + wfile=BrokenWriter(), + end_headers=lambda: (_ for _ in ()).throw(disconnect_exc) if fail_during == "headers" else None, + ) + large_body = b"x" * 150_000 + assert send_http_response(handler, large_body) is False # type: ignore[arg-type] + assert handler.close_connection is True + if fail_during == "chunk": + assert len(writes) == 2 + + +def test_send_http_response_re_raises_non_disconnect_oserror() -> None: + import errno + from types import SimpleNamespace + from loopx.status_server import send_http_response + + class FailingWriter: + def write(self, _data: bytes) -> int: + raise OSError(errno.EIO, "Input/output error") + + def flush(self) -> None: + pass + + handler = SimpleNamespace(close_connection=False, wfile=FailingWriter(), end_headers=lambda: None) + with pytest.raises(OSError, match="Input/output error"): + send_http_response(handler, b"{}") # type: ignore[arg-type] + assert handler.close_connection is False + + +def test_status_server_absorbs_live_early_client_disconnect_without_stderr_traceback( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + import socket + from loopx import status_server + + started = threading.Event() + proceed = threading.Event() + orig_send_http_response = status_server.send_http_response + + def gated_send(handler, body=None): + started.set() + proceed.wait(timeout=5) + return orig_send_http_response(handler, body) + + monkeypatch.setattr(status_server, "send_http_response", gated_send) + server, thread = _start_server() + try: + sock = socket.create_connection(("127.0.0.1", server.server_address[1]), timeout=5) + sock.sendall(b"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") + assert started.wait(timeout=5) + # Close peer socket cleanly with RST/FIN before server finishes writing response. + sock.close() + proceed.set() + # Server remains healthy for subsequent requests and logs zero disconnect tracebacks. + resp = _get(server.server_address[1], origin=None) + assert resp.status == 200 + assert resp.read().endswith(b"}") + finally: + server.shutdown() + thread.join(timeout=5) + + captured = capsys.readouterr() + assert "BrokenPipeError" not in captured.err + assert "ConnectionResetError" not in captured.err + assert "Traceback" not in captured.err + + +def test_disconnect_safe_http_server_suppresses_handle_error_for_disconnects_only( + capsys: pytest.CaptureFixture[str], +) -> None: + from loopx.status_server import DisconnectSafeHTTPServer + + server = DisconnectSafeHTTPServer(("127.0.0.1", 0), StatusRequestHandler) + try: + try: + raise ConnectionResetError(54, "Connection reset by peer") + except ConnectionResetError: + server.handle_error(None, ("127.0.0.1", 1234)) + assert capsys.readouterr().err == "" + + try: + raise ValueError("unexpected bug") + except ValueError: + server.handle_error(None, ("127.0.0.1", 1234)) + assert "unexpected bug" in capsys.readouterr().err + finally: + server.server_close()