From 9c64771028024b87ef8cf777f697a24b1b55fd77 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:47:32 +0800 Subject: [PATCH] Slim scheduler_hint types and deduplicate timestamp parsing Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../control_plane/scheduler/scheduler_hint.py | 390 +++++++++++------- .../test_scheduler_hint_contract.py | 314 ++++++++++++++ 2 files changed, 563 insertions(+), 141 deletions(-) create mode 100644 tests/control_plane/test_scheduler_hint_contract.py diff --git a/loopx/control_plane/scheduler/scheduler_hint.py b/loopx/control_plane/scheduler/scheduler_hint.py index 184f7e8bb5..d1b54afbd6 100644 --- a/loopx/control_plane/scheduler/scheduler_hint.py +++ b/loopx/control_plane/scheduler/scheduler_hint.py @@ -1,16 +1,21 @@ +"""Read-only scheduler hint projection and bounded native transport adapter.""" from __future__ import annotations import base64 +from collections.abc import Mapping, Sequence +from dataclasses import asdict import json +from typing import TypedDict, cast import zlib -from collections.abc import Mapping -from dataclasses import asdict -from typing import Any -from ...command_invocation import loopx_cli_argv -from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result +from ...command_invocation import loopx_cli_argv as loopx_cli_argv +from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result as effect_runtime_result from ..quota.decision_summary import compact_quota_decision -from ..runtime.time import now_utc, utc_isoformat, parse_timestamp +from ..runtime.time import ( + now_utc as now_utc, + parse_timestamp as parse_timestamp, + utc_isoformat as utc_isoformat, +) from ..todos.frontier_deadline import todo_summary_frontier_deadline from .arbitration import SchedulerArbitration from .execution_context import ( @@ -24,6 +29,20 @@ from .state import APP_AUTOMATION_STATEFUL_BACKOFF_STATE_KEY, CODEX_APP_SURFACE +class SchedulerHostFollowupGoalRef(TypedDict): + """Exact Goal identity scope encoded in transport-only scheduler follow-up args.""" + + goal_id: str + goal_instance_id: str + + +class SchedulerTimestampFact(TypedDict): + """Normalized timestamp observation relative to the current scheduler instant.""" + + iso: str + utc: str + after_seconds: float + SCHEDULER_HOST_FACTS_CHUNK_FLAG = "--scheduler-host-facts-chunk" SCHEDULER_HOST_FACTS_CHUNK_CHARS = 384 SCHEDULER_HOST_FACTS_MAX_ENCODED_CHARS = 1_536 @@ -47,13 +66,34 @@ *SCHEDULER_BASE_IDENTITY_KEYS, "recommended_action", ) +_MONITOR_ITEM_FIELDS = ( + "todo_id", + "target_key", + "action_kind", + "title", + "index", + "cadence", + "next_due_at", + "expires_at", + "last_checked_at", +) +_FOLLOWUP_STRING_FIELDS = ( + "goal_id", + "agent_id", + "automation_id", + "turn_instance_id", + "reset_token", + "identity_signature", + "surface", + "state_key", + "after", +) def _scheduler_host_followup_goal_ref( - goal_ref: Mapping[str, Any] | None, -) -> dict[str, str] | None: + goal_ref: Mapping[str, object] | None, +) -> SchedulerHostFollowupGoalRef | None: """Carry one exact Goal instance as transport data, never as an authority claim.""" - if not isinstance(goal_ref, Mapping): return None goal_id = str(goal_ref.get("goal_id") or "").strip() @@ -64,14 +104,13 @@ def _scheduler_host_followup_goal_ref( def _scheduler_host_followup_transport_args( - scheduler_host_facts: Mapping[str, Any] | None, + scheduler_host_facts: Mapping[str, object] | None, *, - before: Mapping[str, Any] | None, + before: Mapping[str, object] | None, use_current_hint: bool, - goal_ref: Mapping[str, Any] | None = None, + goal_ref: Mapping[str, object] | None = None, ) -> list[str]: """Encode a bounded, transport-only native scheduler follow-up hint.""" - if not isinstance(scheduler_host_facts, Mapping): return [] payload = { @@ -87,15 +126,17 @@ def _scheduler_host_followup_transport_args( sort_keys=True, separators=(",", ":"), ).encode("utf-8") - encoded = base64.b64encode(zlib.compress(raw, level=9)).decode("ascii") - encoded = encoded.rstrip("=") + encoded = base64.b64encode(zlib.compress(raw, level=9)).decode("ascii").rstrip("=") if len(encoded) > SCHEDULER_HOST_FACTS_MAX_ENCODED_CHARS: raise ValueError("scheduler host facts exceed the native CLI transport bound") - result: list[str] = [] - for index in range(0, len(encoded), SCHEDULER_HOST_FACTS_CHUNK_CHARS): - chunk = encoded[index : index + SCHEDULER_HOST_FACTS_CHUNK_CHARS] - result.extend([SCHEDULER_HOST_FACTS_CHUNK_FLAG, chunk]) - return result + return [ + entry + for index in range(0, len(encoded), SCHEDULER_HOST_FACTS_CHUNK_CHARS) + for entry in ( + SCHEDULER_HOST_FACTS_CHUNK_FLAG, + encoded[index : index + SCHEDULER_HOST_FACTS_CHUNK_CHARS], + ) + ] def _bounded_scheduler_followup_cli_args( @@ -116,17 +157,18 @@ def _bounded_scheduler_followup_cli_args( def _encode_followup_args( - packet: dict[str, Any], - before: Mapping[str, Any] | None, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: + packet: dict[str, object], + before: Mapping[str, object] | None, + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: if "cli_args" not in packet: return packet + raw_cli_args = packet["cli_args"] + if not isinstance(raw_cli_args, list): + raise RuntimeError("TypeScript scheduler CLI arguments must be a list") args: list[str] = [] native_args: list[str] = [] - if not isinstance(packet["cli_args"], list): - raise RuntimeError("TypeScript scheduler CLI arguments must be a list") - for argument in packet["cli_args"]: + for argument in raw_cli_args: if isinstance(argument, str): args.append(argument) elif ( @@ -136,9 +178,9 @@ def _encode_followup_args( and type(argument.get("use_current_hint")) is bool ): encoded = _scheduler_host_followup_transport_args( - argument["host_facts"], + cast(Mapping[str, object], argument["host_facts"]), before=before, - use_current_hint=argument["use_current_hint"], + use_current_hint=cast(bool, argument["use_current_hint"]), goal_ref=goal_ref, ) args.extend(encoded) @@ -151,15 +193,17 @@ def _encode_followup_args( return { **packet, **({"cli_bin": route[0]} if len(route) > 1 else {}), - "cli_args": _bounded_scheduler_followup_cli_args(args, native_args=native_args), + "cli_args": _bounded_scheduler_followup_cli_args( + args, native_args=native_args + ), } def _finish_transport( - packet: dict[str, Any], - before: Mapping[str, Any] | None, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: + packet: dict[str, object], + before: Mapping[str, object] | None, + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: completed = _encode_followup_args(packet, before, goal_ref) # Source metadata can also contain cli_args. Only these owned wire slots are executable hints. app = completed.get("app_automation") @@ -169,7 +213,7 @@ def _finish_transport( command = app.get(followup) if isinstance(command, dict): encoded_app[followup] = _encode_followup_args( - command, before, goal_ref + cast(dict[str, object], command), before, goal_ref ) completed["app_automation"] = encoded_app return completed @@ -177,12 +221,12 @@ def _finish_transport( def _project_hint( operation: str, - params: dict[str, Any], - before: Mapping[str, Any] | None = None, + params: Mapping[str, object], + before: Mapping[str, object] | None = None, *, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - request = {"operation": operation, **params} + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: + request: dict[str, object] = {"operation": operation, **params} large_snapshot = ( len(json.dumps(request, ensure_ascii=True).encode("utf-8")) > 64 * 1024 ) @@ -198,25 +242,40 @@ def _project_hint( or not isinstance(projected.get("hint"), dict) ): raise RuntimeError("TypeScript scheduler hint projection shape mismatch") - return _finish_transport(projected["hint"], before, goal_ref) + return _finish_transport( + cast(dict[str, object], projected["hint"]), before, goal_ref + ) -def _identity_json(payload: dict[str, Any]) -> dict[str, str]: - encoded = {} +def _identity_json(payload: Mapping[str, object]) -> dict[str, str]: + encoded: dict[str, str] = {} for path in (*SCHEDULER_IDENTITY_KEYS, *SCHEDULER_FRONTIER_IDENTITY_KEYS): - leaf: Any = payload + leaf: object = payload for part in path.split("."): leaf = leaf.get(part) if isinstance(leaf, dict) else None encoded[path] = json.dumps(leaf, ensure_ascii=True, sort_keys=True, default=str) return encoded -def _timestamp_facts(observations: list[Any], current_time: Any) -> dict[str, Any]: - facts = {} +def _timestamp_facts( + observations: Sequence[object], current_time: object +) -> dict[str, SchedulerTimestampFact]: + from datetime import datetime + + if not isinstance(current_time, datetime): + raise TypeError("current_time must be a datetime") + facts: dict[str, SchedulerTimestampFact] = {} + seen_texts: set[str] = set() for raw in observations: + if not raw: + continue + text = str(raw) + if text in seen_texts: + continue + seen_texts.add(text) parsed = parse_timestamp(raw) if parsed is not None: - facts[str(raw)] = { + facts[text] = { "iso": parsed.isoformat(), "utc": utc_isoformat(parsed), "after_seconds": (parsed - current_time).total_seconds(), @@ -225,31 +284,39 @@ def _timestamp_facts(observations: list[Any], current_time: Any) -> dict[str, An def _timestamp_observations( - facts: dict[str, Any], deadlines: list[Any], state: Any -) -> list[Any]: - summary = facts["agent_todo_summary"] - observations = [ + facts: Mapping[str, object], + deadlines: Sequence[dict[str, object] | None], + state: object, +) -> list[object]: + raw_summary = facts.get("agent_todo_summary") + summary = raw_summary if isinstance(raw_summary, Mapping) else {} + observations: list[object] = [ deadline.get("next_due_at") for deadline in deadlines if isinstance(deadline, dict) ] for lane in ("current_agent_claimed_monitor_items", "monitor_open_items"): - observations.extend( - monitor.get(field) - for monitor in summary[lane] - for field in ("next_due_at", "expires_at", "last_checked_at") - ) + raw_monitors = summary.get(lane) + if isinstance(raw_monitors, Sequence) and not isinstance( + raw_monitors, (str, bytes) + ): + for monitor in raw_monitors: + if isinstance(monitor, Mapping): + for field in ("next_due_at", "expires_at", "last_checked_at"): + observations.append(monitor.get(field)) frontier = summary.get("frontier_deadline") - retry_sources = [ + retry_sources = ( summary.get("blocked_retry_wait"), frontier.get("blocked_retry") if isinstance(frontier, dict) else None, - ] + ) observations.extend( retry.get("due_at") for retry in retry_sources if isinstance(retry, dict) ) if isinstance(state, dict): - failures = state.get("host_update_failures") - failures = list(failures) if isinstance(failures, list) else [] + raw_failures = state.get("host_update_failures") + failures: list[object] = ( + list(raw_failures) if isinstance(raw_failures, list) else [] + ) failures.append(state.get("host_update_failure")) observations.extend( failure.get("failed_at") @@ -259,13 +326,13 @@ def _timestamp_observations( return observations -def _fields(source: Any, names: tuple[str, ...]) -> dict[str, Any]: +def _fields(source: object, names: tuple[str, ...]) -> dict[str, object]: return ( {name: source.get(name) for name in names} if isinstance(source, dict) else {} ) -def _capability_values(source: Any) -> list[str] | None: +def _capability_values(source: object) -> list[str] | None: if source is None: return None return ( @@ -275,89 +342,97 @@ def _capability_values(source: Any) -> list[str] | None: ) -def _projection_facts(payload: dict[str, Any]) -> dict[str, Any]: - facts = _fields( +def _projection_facts(payload: Mapping[str, object]) -> dict[str, object]: + base = _fields( payload, ("goal_id", "effective_action", "decision", "automation_cadence") ) - for key, names in ( - ("agent_identity", ("agent_id",)), - ("heartbeat_recommendation", ("recommended_mode", "spend_policy")), - ("automation_liveness", ("spend_policy",)), - ("execution_obligation", ("spend_policy",)), - ("capability_gate", ("available",)), - ("automation_cadence_readback", ("eligibility",)), - ): - facts[key] = _fields(payload.get(key), names) - facts["goal_id"] = str(facts["goal_id"]) if facts["goal_id"] else None - agent = facts["agent_identity"].get("agent_id") - facts["agent_identity"]["agent_id"] = str(agent) if agent else None - available = facts["capability_gate"].get("available") - facts["capability_gate"]["available"] = ( + goal_id = base.get("goal_id") + agent_identity = _fields(payload.get("agent_identity"), ("agent_id",)) + agent = agent_identity.get("agent_id") + agent_identity["agent_id"] = str(agent) if agent else None + capability_gate = _fields(payload.get("capability_gate"), ("available",)) + available = capability_gate.get("available") + capability_gate["available"] = ( _capability_values(available) if isinstance(available, list) else [] ) contract = _fields(payload.get("interaction_contract"), ("agent_channel",)) - facts["interaction_contract"] = { - "agent_channel": _fields(contract.get("agent_channel"), ("delivery_allowed",)) - } summary = payload.get("agent_todo_summary") projected_summary = _fields(summary, ("blocked_retry_wait", "frontier_deadline")) - monitor_fields = ( - "todo_id", - "target_key", - "action_kind", - "title", - "index", - "cadence", - "next_due_at", - "expires_at", - "last_checked_at", - ) for lane in ("current_agent_claimed_monitor_items", "monitor_open_items"): observations = summary.get(lane) if isinstance(summary, dict) else None projected_summary[lane] = ( [ - _fields(monitor, monitor_fields) + _fields(monitor, _MONITOR_ITEM_FIELDS) for monitor in observations if isinstance(monitor, dict) ] if isinstance(observations, list) else [] ) - facts["agent_todo_summary"] = projected_summary - return facts + return { + "goal_id": str(goal_id) if goal_id else None, + "effective_action": base.get("effective_action"), + "decision": base.get("decision"), + "automation_cadence": base.get("automation_cadence"), + "agent_identity": agent_identity, + "heartbeat_recommendation": _fields( + payload.get("heartbeat_recommendation"), ("recommended_mode", "spend_policy") + ), + "automation_liveness": _fields( + payload.get("automation_liveness"), ("spend_policy",) + ), + "execution_obligation": _fields( + payload.get("execution_obligation"), ("spend_policy",) + ), + "capability_gate": capability_gate, + "automation_cadence_readback": _fields( + payload.get("automation_cadence_readback"), ("eligibility",) + ), + "interaction_contract": { + "agent_channel": _fields( + contract.get("agent_channel"), ("delivery_allowed",) + ) + }, + "agent_todo_summary": projected_summary, + } def build_scheduler_hint( - payload: dict[str, Any], + payload: Mapping[str, object], *, user_action_required: bool = False, arbitration: SchedulerArbitration | None = None, include_detail: bool = False, - codex_app_scheduler_state: dict[str, Any] | None = None, - available_capabilities: Any = None, - codex_app_current_rrule: Any = None, - codex_app_automation_id: Any = None, - scheduler_execution_context: Mapping[str, Any] + codex_app_scheduler_state: Mapping[str, object] | None = None, + available_capabilities: object = None, + codex_app_current_rrule: object = None, + codex_app_automation_id: object = None, + scheduler_execution_context: Mapping[str, object] | SchedulerExecutionContextResolution | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Read-only projection; the typed owner decides the complete scheduler hint.""" + del user_action_required context = resolve_scheduler_execution_context(scheduler_execution_context) current_time = now_utc() # Todo summaries retain their existing source owner. These are observations, # supplied before the one hint request, with no callback or second reduction. - deadlines = [ + deadlines: list[dict[str, object] | None] = [ todo_summary_frontier_deadline(payload.get(key), current_time=current_time) for key in ("agent_todo_summary", "user_todo_summary") ] facts = _projection_facts(payload) - params = { + raw_goal_ref = payload.get("goal_ref") + goal_ref = cast(Mapping[str, object], raw_goal_ref) if isinstance(raw_goal_ref, Mapping) else None + params: dict[str, object] = { "payload": facts, "identity_json": _identity_json(payload), "context": context.projection(), "arbitration": asdict(arbitration) if arbitration is not None else None, "include_detail": bool(include_detail), - "scheduler_state": codex_app_scheduler_state, + "scheduler_state": dict(codex_app_scheduler_state) + if isinstance(codex_app_scheduler_state, Mapping) + else codex_app_scheduler_state, "available_capabilities": _capability_values(available_capabilities), "observed_host_rrule": codex_app_current_rrule, "automation_id": codex_app_automation_id, @@ -369,27 +444,27 @@ def build_scheduler_hint( current_time, ), } - return _project_hint("hint", params, payload, goal_ref=payload.get("goal_ref")) + return _project_hint("hint", params, payload, goal_ref=goal_ref) -def _followup(operation: str, kwargs: dict[str, Any]) -> dict[str, Any]: - before = kwargs.pop("scheduler_before", None) - goal_ref = kwargs.pop("goal_ref", None) +def _followup(operation: str, kwargs: dict[str, object]) -> dict[str, object]: + raw_before = kwargs.pop("scheduler_before", None) + before = ( + cast(Mapping[str, object], raw_before) + if isinstance(raw_before, Mapping) + else None + ) + raw_goal_ref = kwargs.pop("goal_ref", None) + goal_ref = ( + cast(Mapping[str, object], raw_goal_ref) + if isinstance(raw_goal_ref, Mapping) + else None + ) if "available_capabilities" in kwargs: kwargs["available_capabilities"] = _capability_values( kwargs["available_capabilities"] ) - for field in ( - "goal_id", - "agent_id", - "automation_id", - "turn_instance_id", - "reset_token", - "identity_signature", - "surface", - "state_key", - "after", - ): + for field in _FOLLOWUP_STRING_FIELDS: if field in kwargs: kwargs[field] = str(kwargs[field] or "").strip() if "host_match_observed" in kwargs: @@ -399,34 +474,67 @@ def _followup(operation: str, kwargs: dict[str, Any]) -> dict[str, Any]: def build_app_automation_scheduler_ack_hint( *, - goal_id: Any, - agent_id: Any, - applied_rrule: Any, - reset_token: Any, - identity_signature: Any, - available_capabilities: Any = None, + goal_id: object, + agent_id: object, + applied_rrule: object, + reset_token: object, + identity_signature: object, + available_capabilities: object = None, after: str = "automation_update_rrule_success", host_match_observed: bool = False, surface: str = CODEX_APP_SURFACE, state_key: str = APP_AUTOMATION_STATEFUL_BACKOFF_STATE_KEY, - scheduler_host_facts: Mapping[str, Any] | None = None, - scheduler_before: Mapping[str, Any] | None = None, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - return _followup("ack", dict(locals())) + scheduler_host_facts: Mapping[str, object] | None = None, + scheduler_before: Mapping[str, object] | None = None, + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Build the post-success follow-up scheduler hint payload.""" + return _followup( + "ack", + { + "goal_id": goal_id, + "agent_id": agent_id, + "applied_rrule": applied_rrule, + "reset_token": reset_token, + "identity_signature": identity_signature, + "available_capabilities": available_capabilities, + "after": after, + "host_match_observed": host_match_observed, + "surface": surface, + "state_key": state_key, + "scheduler_host_facts": scheduler_host_facts, + "scheduler_before": scheduler_before, + "goal_ref": goal_ref, + }, + ) def build_app_automation_scheduler_failure_hint( *, - goal_id: Any, - agent_id: Any, - failed_rrule: Any, - observed_host_rrule: Any = None, - available_capabilities: Any = None, - scheduler_host_facts: Mapping[str, Any] | None = None, - scheduler_before: Mapping[str, Any] | None = None, + goal_id: object, + agent_id: object, + failed_rrule: object, + observed_host_rrule: object = None, + available_capabilities: object = None, + scheduler_host_facts: Mapping[str, object] | None = None, + scheduler_before: Mapping[str, object] | None = None, surface: str = CODEX_APP_SURFACE, state_key: str = APP_AUTOMATION_STATEFUL_BACKOFF_STATE_KEY, - goal_ref: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - return _followup("failure", dict(locals())) + goal_ref: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Build the failure follow-up scheduler hint payload.""" + return _followup( + "failure", + { + "goal_id": goal_id, + "agent_id": agent_id, + "failed_rrule": failed_rrule, + "observed_host_rrule": observed_host_rrule, + "available_capabilities": available_capabilities, + "scheduler_host_facts": scheduler_host_facts, + "scheduler_before": scheduler_before, + "surface": surface, + "state_key": state_key, + "goal_ref": goal_ref, + }, + ) diff --git a/tests/control_plane/test_scheduler_hint_contract.py b/tests/control_plane/test_scheduler_hint_contract.py new file mode 100644 index 0000000000..9a0b926763 --- /dev/null +++ b/tests/control_plane/test_scheduler_hint_contract.py @@ -0,0 +1,314 @@ +"""Contract, typing, and boundary tests for Work Control scheduler hints.""" + +from __future__ import annotations + +import ast +import base64 +from collections.abc import Mapping +from datetime import UTC, datetime +import hashlib +import io +import json +from pathlib import Path +import tokenize +from types import MappingProxyType +import zlib + +import pytest + +from loopx.control_plane.effect_runtime import EffectRuntimeRejected +from loopx.control_plane.scheduler import scheduler_hint as sh +from loopx.control_plane.scheduler.arbitration import ( + SchedulerArbitration, + SchedulerDisposition, +) +from loopx.control_plane.scheduler.execution_context import ( + scheduler_execution_context_for_runtime_profile, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _any_count(source: str) -> int: + tree = ast.parse(source) + return sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or ( + isinstance(node, ast.ImportFrom) + and any(alias.name == "Any" for alias in node.names) + ) + ) + + +def _comment_type_ignore_count(source: str) -> int: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + return sum( + 1 + for tok in tokens + if tok.type == tokenize.COMMENT and "type: ignore" in tok.string + ) + + +def test_scheduler_hint_static_hygiene_and_exports() -> None: + sh_path = REPO_ROOT / "loopx/control_plane/scheduler/scheduler_hint.py" + test_path = Path(__file__).resolve() + + sh_src = sh_path.read_text(encoding="utf-8") + test_src = test_path.read_text(encoding="utf-8") + + assert len(sh_src.splitlines()) <= 550 + assert len(test_src.splitlines()) < 550 + for src in (sh_src, test_src): + assert _any_count(src) == 0 + assert _comment_type_ignore_count(src) == 0 + + assert sh.SchedulerTimestampFact is not None + assert sh.SchedulerHostFollowupGoalRef is not None + + +def test_timestamp_facts_deduplicates_duplicate_and_empty_observations( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixed_now = datetime(2026, 11, 26, 8, 0, tzinfo=UTC) + monkeypatch.setattr(sh, "now_utc", lambda: fixed_now) + + real_parse = sh.parse_timestamp + parse_calls: list[object] = [] + + def counting_parse(value: object) -> datetime | None: + parse_calls.append(value) + return real_parse(value) + + monkeypatch.setattr(sh, "parse_timestamp", counting_parse) + + shared_ts = "2026-11-26T08:05:00Z" + other_ts = "2026-11-26T08:10:00Z" + payload: dict[str, object] = { + "goal_id": "g-ts", + "agent_identity": {"agent_id": "agent-ts"}, + "heartbeat_recommendation": {"recommended_mode": "quiet_wait"}, + "agent_todo_summary": { + "frontier_deadline": {"next_due_at": shared_ts, "blocked_retry": {"due_at": shared_ts}}, + "blocked_retry_wait": {"due_at": shared_ts}, + "monitor_open_items": [ + { + "todo_id": "t1", + "next_due_at": shared_ts, + "expires_at": None, + "last_checked_at": "", + }, + { + "todo_id": "t2", + "next_due_at": shared_ts, + "expires_at": other_ts, + "last_checked_at": shared_ts, + }, + ], + "current_agent_claimed_monitor_items": [ + {"todo_id": "t1", "next_due_at": shared_ts, "expires_at": other_ts} + ], + }, + } + state: dict[str, object] = { + "host_update_failure": {"failed_at": shared_ts}, + "host_update_failures": [{"failed_at": other_ts}, {"failed_at": None}], + } + captured_params: dict[str, object] = {} + real_effect = sh.effect_runtime_result + + def capture_effect( + method: str, + request: Mapping[str, object], + *, + timeout: float = 30.0, + retry_safe: bool = True, + large_local_snapshot: bool = False, + ) -> object: + captured_params.update(request) + return real_effect( + method, + request, + timeout=timeout, + retry_safe=retry_safe, + large_local_snapshot=large_local_snapshot, + ) + + monkeypatch.setattr(sh, "effect_runtime_result", capture_effect) + sh.build_scheduler_hint( + payload, + arbitration=SchedulerArbitration( + SchedulerDisposition.QUIET_WAIT, "blocked_wait", "quiet_wait" + ), + codex_app_scheduler_state=state, + scheduler_execution_context=scheduler_execution_context_for_runtime_profile( + "codex_app_heartbeat" + ), + ) + + assert parse_calls == [shared_ts, other_ts] + timestamps = captured_params["timestamps"] + assert timestamps == { + shared_ts: {"iso": "2026-11-26T08:05:00+00:00", "utc": shared_ts, "after_seconds": 300.0}, + other_ts: {"iso": "2026-11-26T08:10:00+00:00", "utc": other_ts, "after_seconds": 600.0}, + } + + +def test_transport_args_and_followup_key_presence_and_bounds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Missing cli_args key leaves packet untouched; non-list raises RuntimeError. + untouched = sh._encode_followup_args({"action": "wait"}, before=None) + assert untouched == {"action": "wait"} + with pytest.raises(RuntimeError, match="must be a list"): + sh._encode_followup_args({"cli_args": "bad"}, before=None) + with pytest.raises(RuntimeError, match="shape mismatch"): + sh._encode_followup_args( + { + "cli_args": [ + { + "kind": "scheduler_host_followup", + "host_facts": {}, + "use_current_hint": 1, + } + ] + }, + before=None, + ) + + # None host_facts yields []; empty mapping {} is still Mapping and encodes chunked args. + assert sh._scheduler_host_followup_transport_args(None, before=None, use_current_hint=False) == [] + empty_encoded = sh._scheduler_host_followup_transport_args( + {}, + before={"should_run": True}, + use_current_hint=True, + goal_ref={"goal_id": "g1", "goal_instance_id": "gi1"}, + ) + assert empty_encoded[0] == sh.SCHEDULER_HOST_FACTS_CHUNK_FLAG + raw_b64 = "".join(empty_encoded[1::2]) + decoded = json.loads(zlib.decompress(base64.b64decode(raw_b64 + "=" * (-len(raw_b64) % 4)))) + assert decoded["goal_ref"] == {"goal_id": "g1", "goal_instance_id": "gi1"} + assert decoded["host_facts"] == {} + assert decoded["use_current_hint"] is True + + # Non-native CLI args bypass the native bound; native args over limits fail closed. + long_plain = ["x"] * 70 + assert sh._bounded_scheduler_followup_cli_args(long_plain, native_args=[]) == long_plain + with pytest.raises(ValueError, match="exceed the transport bound"): + sh._bounded_scheduler_followup_cli_args(long_plain, native_args=["--scheduler-host-facts-chunk"]) + with pytest.raises(ValueError, match="exceed the native CLI transport bound"): + incompressible = "".join( + hashlib.sha256(f"{i}".encode()).hexdigest() for i in range(64) + ) + sh._scheduler_host_followup_transport_args( + {"blob": incompressible}, + before=None, + use_current_hint=False, + ) + + monkeypatch.setattr(sh, "loopx_cli_argv", lambda: ["/usr/bin/python3", "-m", "loopx.entrypoint"]) + routed = sh._encode_followup_args({"cli_args": ["quota", "should-run"]}, before=None) + assert routed["cli_bin"] == "/usr/bin/python3" + assert routed["cli_args"] == ["-m", "loopx.entrypoint", "quota", "should-run"] + + monkeypatch.setattr( + sh, + "effect_runtime_result", + lambda *args, **kwargs: (_ for _ in ()).throw(EffectRuntimeRejected("invalid hint")), + ) + with pytest.raises(ValueError, match="invalid hint"): + sh._project_hint("hint", {}) + + monkeypatch.setattr( + sh, + "effect_runtime_result", + lambda *args, **kwargs: {"schema_version": "wrong", "hint": {}}, + ) + with pytest.raises(RuntimeError, match="shape mismatch"): + sh._project_hint("hint", {}) + + +def test_projection_facts_empty_containers_and_ack_failure_hints( + monkeypatch: pytest.MonkeyPatch, +) -> None: + facts = sh._projection_facts( + { + "goal_id": "", + "agent_identity": {"agent_id": ""}, + "capability_gate": {"available": "not-a-list"}, + "interaction_contract": None, + "agent_todo_summary": {"monitor_open_items": "not-a-list"}, + } + ) + assert facts["goal_id"] is None + assert facts["agent_identity"] == {"agent_id": None} + assert facts["capability_gate"] == {"available": []} + assert facts["interaction_contract"] == {"agent_channel": {}} + assert facts["agent_todo_summary"] == { + "blocked_retry_wait": None, + "frontier_deadline": None, + "current_agent_claimed_monitor_items": [], + "monitor_open_items": [], + } + assert sh._capability_values(None) is None + assert sh._capability_values(frozenset({"a"})) == [] + assert sh._capability_values([" cap-a ", ""]) == ["cap-a", ""] + + captured: list[tuple[str, dict[str, object]]] = [] + + def fake_effect( + method: str, request: dict[str, object], **kwargs: object + ) -> dict[str, object]: + del method, kwargs + captured.append((str(request.get("operation")), dict(request))) + return { + "schema_version": "scheduler_hint_projection_v0", + "hint": {"cli_args": ["quota", "apply"], "operation": request.get("operation")}, + } + + monkeypatch.setattr(sh, "effect_runtime_result", fake_effect) + monkeypatch.setattr(sh, "loopx_cli_argv", lambda: ["loopx"]) + + ack = sh.build_app_automation_scheduler_ack_hint( + goal_id=" g1 ", + agent_id=" a1 ", + applied_rrule="FREQ=HOURLY", + reset_token=None, + identity_signature=" sig ", + available_capabilities=["cap"], + host_match_observed=True, + scheduler_host_facts={}, + goal_ref={"goal_id": "g1", "goal_instance_id": "gi1"}, + ) + fail = sh.build_app_automation_scheduler_failure_hint( + goal_id="g1", + agent_id="a1", + failed_rrule="FREQ=MINUTELY", + observed_host_rrule="FREQ=HOURLY", + scheduler_before={"should_run": False}, + ) + assert ack["operation"] == "ack" + assert fail["operation"] == "failure" + assert captured[0][1]["goal_id"] == "g1" + assert captured[0][1]["reset_token"] == "" + assert captured[0][1]["host_match_observed"] is True + assert captured[0][1]["available_capabilities"] == ["cap"] + + +def test_timestamp_facts_rejects_non_datetime_and_supports_mapping_proxy() -> None: + with pytest.raises(TypeError, match="datetime"): + sh._timestamp_facts([], "not-a-datetime") + + context_proxy = MappingProxyType( + scheduler_execution_context_for_runtime_profile("generic_cli").projection() + ) + hint = sh.build_scheduler_hint( + {"goal_id": "g-proxy", "effective_action": "normal_run"}, + arbitration=SchedulerArbitration( + SchedulerDisposition.ACTIVE_WORK, "active_work", "normal_run" + ), + scheduler_execution_context=context_proxy, + ) + assert hint["action"] == "run_now"