From 8734f11c3bbc5891fb457344e9e3bacee906ad4a Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:38:27 +0800 Subject: [PATCH 1/3] refactor(explore): slim harness_runtime and remove Any typing Split loopx/capabilities/explore/harness_runtime.py into focused modules (harness_queue.py, harness_frontier.py) and replace all Any annotations with TypedDict/Protocol/object contracts. Eliminate redundant per-family catalog reads via VariantCatalog.pending_snapshot() and per-sort _frontier_gain recomputations while preserving baseline semantics. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../capabilities/explore/harness_frontier.py | 505 +++++++ loopx/capabilities/explore/harness_queue.py | 555 +++++++ loopx/capabilities/explore/harness_runtime.py | 1331 +++++------------ .../test_explore_harness_runtime_contract.py | 564 +++++++ 4 files changed, 2032 insertions(+), 923 deletions(-) create mode 100644 loopx/capabilities/explore/harness_frontier.py create mode 100644 loopx/capabilities/explore/harness_queue.py create mode 100644 tests/capabilities/test_explore_harness_runtime_contract.py diff --git a/loopx/capabilities/explore/harness_frontier.py b/loopx/capabilities/explore/harness_frontier.py new file mode 100644 index 0000000000..390ea36f82 --- /dev/null +++ b/loopx/capabilities/explore/harness_frontier.py @@ -0,0 +1,505 @@ +"""Novelty ledger, variant catalog scheduling, and frontier planning.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +import hashlib +from pathlib import Path +from typing import cast + +from .episode_runtime import build_router_probes +from .harness_queue import ( + DEFAULT_OBSERVATION_WEIGHT, + HarnessLaneRecord, + _as_float, + _collection_or_empty, + _mapping_or_empty, + _read_json, + _write_json, +) +from .router_state import advance_epoch, initial_router_state, observe_epoch +from .worker_branch_plan import build_explore_worker_branch_plan + +VARIANT_CATALOG_SCHEMA_VERSION = "loopx_explore_variant_catalog_v0" +FRONTIER_REQUESTS_SCHEMA_VERSION = "loopx_explore_frontier_requests_v0" + + +class NoveltyLedger: + """First-seen ledger: raw observation keys global, flags family-scoped. + + Raw keys are ledgered globally so relabeling an item under a different + family can never re-mint an already-seen key; weighted flags are + family-scoped facts. Weights come from the record itself (adapter-owned). + """ + + def __init__(self) -> None: + self.seen: set[str] = set() + + def raw_value(self, record: Mapping[str, object]) -> float: + keys = _collection_or_empty( + record.get("observation_keys"), field_name="observation_keys" + ) + flags = _mapping_or_empty( + record.get("weighted_flags"), field_name="weighted_flags" + ) + return DEFAULT_OBSERVATION_WEIGHT * len(keys) + sum( + _as_float(weight) for weight in flags.values() + ) + + def credit(self, record: Mapping[str, object]) -> dict[str, float]: + family = str(record.get("family") or "general") + novel_value = 0.0 + novel_keys = 0 + keys = _collection_or_empty( + record.get("observation_keys"), field_name="observation_keys" + ) + flags = _mapping_or_empty( + record.get("weighted_flags"), field_name="weighted_flags" + ) + for raw_key in keys: + key = str(raw_key) + if key not in self.seen: + self.seen.add(key) + novel_value += DEFAULT_OBSERVATION_WEIGHT + novel_keys += 1 + for flag, weight in flags.items(): + pseudo = f"flag:{family}:{flag}" + if pseudo not in self.seen: + self.seen.add(pseudo) + novel_value += _as_float(weight) + return {"novel_value": novel_value, "novel_observation_keys": novel_keys} + + +def _frontier_gain( + router_state: Mapping[str, object] | None, + family: str, + *, + epoch: int, +) -> float: + """Expected value of spending a speculative slot near this family. + + Generic signals only: whether the base loop has probed the family yet, + its residual novelty pressure, and a small age bonus. Field names track + the router_state family schema; the lookup accepts both the raw family + id and adapter-prefixed forms (e.g. 'scope:artifacts/'). + """ + + stats: Mapping[object, object] = {} + families = ( + router_state.get("families") if isinstance(router_state, Mapping) else None + ) + if isinstance(families, Mapping): + exact = families.get(family) + if isinstance(exact, Mapping): + stats = exact + else: + suffix = "/" + str(family) + for key, value in families.items(): + if isinstance(value, Mapping) and str(key).endswith(suffix): + stats = value + break + score = 1.0 + runs = _as_float(stats.get("runs") or 0.0) + if runs <= 0: + score += 1.25 + else: + novelty_rate = stats.get("novelty_rate") + if novelty_rate is not None: + score += min(1.25, max(0.0, _as_float(novelty_rate)) * 1.25) + accept_rate = stats.get("accept_rate_ema") + if accept_rate is not None and _as_float(accept_rate) <= 0.5: + score += 0.25 + score += min(0.5, max(0, int(epoch) - 1) * 0.03) + return round(score, 4) + + +class VariantCatalog: + """Agent-authored variant specs + per-arm consumption bookkeeping. + + Catalog file schema (written by the experiment agent, never by code): + ``{"schema_version": ..., "specs": [{"spec_id", "seed_family", + "intent", "ops": [...adapter-defined...], "key_prefix", + "seed_item_id"?, "priority"?}]}``. The harness treats ``ops`` as opaque. + """ + + def __init__(self, catalog_path: Path, consumption_path: Path) -> None: + self.catalog_path = Path(catalog_path) + self.consumption_path = Path(consumption_path) + consumed = _read_json(self.consumption_path) + items = _collection_or_empty(consumed, field_name="variant_consumption") + self.consumed: set[str] = {str(item) for item in items} + + def _specs(self) -> list[dict[str, object]]: + payload = _read_json(self.catalog_path) + specs = payload.get("specs") if isinstance(payload, Mapping) else None + raw_specs = _collection_or_empty(specs, field_name="variant_catalog.specs") + return [ + dict(spec) + for spec in raw_specs + if isinstance(spec, Mapping) and spec.get("spec_id") + ] + + def pending_snapshot(self) -> tuple[dict[str, list[dict[str, object]]], int]: + """Read ``catalog_path`` once and index pending specs by ``seed_family``.""" + + by_family: dict[str, list[dict[str, object]]] = {} + total_pending = 0 + for spec in self._specs(): + if str(spec.get("spec_id")) in self.consumed: + continue + total_pending += 1 + by_family.setdefault(str(spec.get("seed_family") or ""), []).append(spec) + return by_family, total_pending + + def pending_for(self, family: str) -> list[dict[str, object]]: + return [ + spec + for spec in self._specs() + if str(spec.get("seed_family") or "") == str(family) + and str(spec.get("spec_id")) not in self.consumed + ] + + def pending_count(self) -> int: + return len( + [s for s in self._specs() if str(s.get("spec_id")) not in self.consumed] + ) + + def consume(self, spec_id: str) -> None: + self.consumed.add(str(spec_id)) + _write_json(self.consumption_path, sorted(self.consumed)) + + def restore_consumed(self, spec_ids: Sequence[object]) -> None: + self.consumed = {str(spec_id) for spec_id in spec_ids if str(spec_id).strip()} + _write_json(self.consumption_path, sorted(self.consumed)) + + +def _catalog_pending_index( + catalog: VariantCatalog, + families: Sequence[str], +) -> tuple[dict[str, list[dict[str, object]]], int]: + """Use single-read ``pending_snapshot`` when available; fall back for mocks.""" + + snapshot_fn = getattr(catalog, "pending_snapshot", None) + if callable(snapshot_fn): + typed_snapshot = cast( + Callable[[], tuple[dict[str, list[dict[str, object]]], int]], + snapshot_fn, + ) + return typed_snapshot() + by_family = {family: catalog.pending_for(family) for family in families} + return by_family, catalog.pending_count() + + +def select_frontier_work( + seed_items: Sequence[Mapping[str, object]], + *, + catalog: VariantCatalog, + adapter: object, + router_state: Mapping[str, object] | None, + epoch: int, + max_lanes: int, +) -> tuple[list[dict[str, object]], dict[str, object]]: + """Pick up to ``max_lanes`` agent-authored variant specs to execute. + + Seeds are ranked by the generic frontier gain with an epoch-rotating + tie-break (multiplicative permutation over a prime modulus) so equal + gains spread across families over epochs instead of freezing on an + alphabetical prefix. Spec choice within a family follows the agent's + ``priority`` then catalog order. The harness only ever schedules specs; + it cannot invent them. + """ + + def _hash(value: str) -> int: + return int(hashlib.sha1(value.encode("utf-8")).hexdigest()[:8], 16) + + by_family: dict[str, Mapping[str, object]] = {} + for item in seed_items: + family = str(item.get("family") or "") + if family and family not in by_family: + by_family[family] = item + gain_by_family = { + family: _frontier_gain(router_state, family, epoch=epoch) + for family in by_family + } + ranked = sorted( + by_family.items(), + key=lambda pair: ( + -gain_by_family[pair[0]], + (_hash(pair[0]) * (2 * int(epoch) + 1)) % 1_000_003, + pair[0], + ), + ) + pending_by_family, catalog_pending_total = _catalog_pending_index( + catalog, [family for family, _ in ranked] + ) + selected: list[dict[str, object]] = [] + audit_specs: list[dict[str, object]] = [] + compile_variant_raw = getattr(adapter, "compile_variant", None) + for family, seed in ranked: + if len(selected) >= max(0, int(max_lanes)): + break + pending = sorted( + pending_by_family.get(family, ()), + key=lambda spec: ( + -_as_float(spec.get("priority") or 0.0), + str(spec.get("spec_id")), + ), + ) + if not pending: + continue + spec = pending[0] + if not callable(compile_variant_raw): + raise AttributeError( + f"{type(adapter).__name__!r} object has no attribute 'compile_variant'" + ) + compile_fn = cast( + Callable[[dict[str, object], dict[str, object]], Mapping[str, object]], + compile_variant_raw, + ) + compiled = dict(compile_fn(spec, dict(seed))) + compiled.setdefault("is_variant", True) + compiled.setdefault("variant_spec", spec) + compiled.setdefault("family", family) + compiled.setdefault("seed_item_id", seed.get("item_id")) + compiled.setdefault( + "concurrency_key", f"{family}:variant:{spec.get('spec_id')}" + ) + catalog.consume(str(spec.get("spec_id"))) + selected.append(compiled) + audit_specs.append( + { + "spec_id": spec.get("spec_id"), + "seed_family": family, + "intent": spec.get("intent"), + "gain": gain_by_family[family], + } + ) + pending_after = ( + max(0, catalog_pending_total - len(selected)) + if callable(getattr(catalog, "pending_snapshot", None)) + else catalog.pending_count() + ) + audit: dict[str, object] = { + "requested_lanes": int(max_lanes), + "admitted": len(selected), + "catalog_pending_after": pending_after, + "specs": audit_specs, + } + return selected, audit + + +def emit_frontier_requests( + path: Path, + *, + arm_key: str, + epoch: int, + seed_items: Sequence[Mapping[str, object]], + ledger: NoveltyLedger, + catalog: VariantCatalog, + router_state: Mapping[str, object] | None, + per_family_key_cap: int = 24, +) -> None: + """Publish what the harness NEEDS from the experiment agent. + + The agent (a Claude/Codex session driving the experiment) reads this + packet -- seed text plus a digest of already-seen observation keys and + exhausted specs -- and appends new specs to the variant catalog. This is + the LoopX interaction pattern: packet out, decision in, no LLM calls + from code. + """ + + first_seed_by_family: dict[str, Mapping[str, object]] = {} + for item in seed_items: + family = str(item.get("family") or "") + if family and family not in first_seed_by_family: + first_seed_by_family[family] = item + pending_by_family, catalog_pending_total = _catalog_pending_index( + catalog, list(first_seed_by_family) + ) + families: list[dict[str, object]] = [] + for family, item in first_seed_by_family.items(): + seen_for_family = sorted( + key + for key in ledger.seen + if not key.startswith("flag:") or key.startswith(f"flag:{family}:") + )[: max(1, per_family_key_cap)] + families.append( + { + "family": family, + "seed_item_id": item.get("item_id"), + "seed_text": item.get("text"), + "pending_spec_count": len(pending_by_family.get(family, ())), + "frontier_gain": _frontier_gain(router_state, family, epoch=epoch), + "seen_keys_sample": seen_for_family, + } + ) + _write_json( + path, + { + "schema_version": FRONTIER_REQUESTS_SCHEMA_VERSION, + "arm": arm_key, + "epoch": int(epoch), + "total_seen_keys": len(ledger.seen), + "catalog_pending_total": catalog_pending_total, + "families": sorted( + families, key=lambda entry: -_as_float(entry["frontier_gain"]) + ), + "how_to_respond": ( + "Append specs to the variant catalog file: {spec_id, seed_family, " + "intent, ops (adapter-defined), key_prefix, priority}. The harness " + "schedules them by frontier gain; it never invents specs." + ), + }, + ) + + +def plan_round_robin( + seed_items: Sequence[Mapping[str, object]], **_: object +) -> list[dict[str, object]]: + """Baseline planner: every seed, catalog untouched, no ordering signal.""" + + return [dict(item) for item in seed_items] + + +def plan_router_no_prune( + seed_items: Sequence[Mapping[str, object]], + *, + goal_id: str, + agent_id: str, + worker_count: int, + router_state: Mapping[str, object] | None, + load_profile: Mapping[str, object] | None, + harness_profile: str = "moe-router", + branch_fill_policy: str = "confident-prefix", +) -> list[dict[str, object]]: + """Router-ordered no-prune planner over generic seed items. + + Uses the LoopX worker-branch planner for VALUE ORDERING only, then + appends every unselected seed as a ranked tail -- sorting without + pruning: an executable seed never loses its slot to low confidence. + """ + + by_id: dict[str, dict[str, object]] = {} + duplicate_items: list[dict[str, object]] = [] + for item in seed_items: + item_id = str(item.get("item_id")) + if item_id in by_id: + duplicate_items.append(dict(item)) + else: + by_id[item_id] = dict(item) + todos = [ + { + "todo_id": item_id, + "text": str(item.get("text") or item.get("item_id")), + "status": "open", + "task_class": "advancement_task", + "required_write_scopes": [f"artifacts/{item.get('family')}/**"], + "index": index, + } + for index, (item_id, item) in enumerate(by_id.items()) + ] + plan = build_explore_worker_branch_plan( + goal_id=goal_id, + todos=todos, + agent_id=agent_id, + # This standalone benchmark arm opts in explicitly and consumes value + # ordering only; spawn stays disallowed, so the plan carries no + # suggested claim/lease commands. + orchestration={"explore_harness": {"enabled": True}}, + worker_width=worker_count, + harness_profile=harness_profile, + branch_fill_policy=branch_fill_policy, + router_state=router_state, + load_profile=load_profile, + ) + ordered: list[dict[str, object]] = [] + used: set[str] = set() + for lane_key in ("selected_worker_branches", "rejected_worker_branches"): + raw_branches = plan.get(lane_key) + if not isinstance(raw_branches, Sequence) or isinstance( + raw_branches, (str, bytes, bytearray) + ): + continue + for branch in raw_branches: + if not isinstance(branch, Mapping): + continue + raw_todo_ids = branch.get("todo_ids") + if not isinstance(raw_todo_ids, Sequence) or isinstance( + raw_todo_ids, (str, bytes, bytearray) + ): + continue + for raw_todo_id in raw_todo_ids: + todo_id = str(raw_todo_id) + if todo_id in by_id and todo_id not in used: + ordered.append(by_id[todo_id]) + used.add(todo_id) + for item_id, item in by_id.items(): + if item_id not in used: + ordered.append(item) + used.add(item_id) + # Preserve malformed duplicates for the episode grouping boundary. The + # planner still reasons over unique ids, but no-prune means it must not + # silently erase an input that record/fatal policy needs to classify. + ordered.extend(duplicate_items) + return ordered + + +def initial_arm_router_state() -> dict[str, object]: + """Return a mutable initial router state dictionary for one harness arm.""" + + return dict(initial_router_state()) + + +def update_router_epoch_feedback( + *, + current_router_state: Mapping[str, object] | None, + records: Sequence[Mapping[str, object]], + seed_items: Sequence[Mapping[str, object]], + lanes: Sequence[HarnessLaneRecord], + episode_mode: str | None, + epoch: int, + epoch_wall: float, + run_root: Path, + arm_key: str, +) -> tuple[dict[str, object], dict[str, object]]: + """Observe completed epoch probes, persist updated router state, and compute load profile.""" + + if episode_mode is not None: + probes: list[Mapping[str, object]] = list(build_router_probes(records)) + else: + probes = [ + { + "family": str(record.get("family") or "general"), + "duration_minutes": record.get("duration_minutes"), + "observation_keys": record.get("observation_keys") or [], + "weighted_flags": record.get("weighted_flags") or {}, + "accepted": bool(record.get("accepted")), + "retryable_infra_error": bool(record.get("retryable_infra_error")), + } + for record in records + ] + current_router = ( + dict(current_router_state) + if current_router_state is not None + else initial_arm_router_state() + ) + observed = observe_epoch(current_router, epoch=epoch, probes=probes) + next_router = dict( + advance_epoch( + observed, + epoch=epoch, + eligible_families=sorted( + {str(item.get("family")) for item in seed_items if item.get("family")} + ), + ) + ) + _write_json(run_root / f"router_state_{arm_key}.json", next_router) + max_lane_wall = max( + (_as_float(lane.get("wall_minutes") or 0.0) for lane in lanes), default=0.0 + ) + load_profile: dict[str, object] = { + "source": f"observed_epoch_{epoch:02d}_{arm_key}", + "parallel_wall_minutes": epoch_wall, + "max_branch_minutes": max_lane_wall, + "branch_count": len(lanes), + } + return next_router, load_profile diff --git a/loopx/capabilities/explore/harness_queue.py b/loopx/capabilities/explore/harness_queue.py new file mode 100644 index 0000000000..4eaa8be6d4 --- /dev/null +++ b/loopx/capabilities/explore/harness_queue.py @@ -0,0 +1,555 @@ +"""Execution queue, shared JSON/coercion helpers, and scoring for Explore harness.""" +from __future__ import annotations + +from collections.abc import Callable, Collection, Mapping, Sequence +import concurrent.futures +from enum import Enum +import json +from pathlib import Path +import threading +import time +from typing import Protocol, TypedDict, cast + +from .episode_runtime import item_concurrency_keys + +HARNESS_ARM_SCHEMA_VERSION = "loopx_explore_harness_arm_v0" +HARNESS_RUNTIME_POLICY_SCHEMA_VERSION = "loopx_explore_harness_runtime_policy_v0" + +DEFAULT_OBSERVATION_WEIGHT = 1.0 +_MIN_DURATION_MINUTES = 0.05 + + +class ItemFailurePolicy(str, Enum): + """Policy controlling how per-item execution exceptions are handled.""" + + RECORD = "record" + FATAL = "fatal" + + +ITEM_FAILURE_POLICY_RECORD = ItemFailurePolicy.RECORD.value +ITEM_FAILURE_POLICY_FATAL = ItemFailurePolicy.FATAL.value +ITEM_FAILURE_POLICIES = {policy.value for policy in ItemFailurePolicy} + + +class SeedAdapter(Protocol): + """Minimum adapter interface required by ``run_budget_arm``.""" + + def list_seed_items(self) -> Sequence[Mapping[str, object]]: ... + + +class HarnessLaneRecord(TypedDict): + """Execution records and timing for one concurrent queue worker lane.""" + + branch_id: str + launch_index: int + wall_minutes: float + item_ids: list[object] + families: list[object] + results: list[dict[str, object]] + + +class HarnessCheckpointPoint(TypedDict): + """Cumulative anytime curve sample emitted after each epoch.""" + + epoch: int + elapsed_minutes: float + raw_value_cum: float + novel_value_cum: float + coverage_count_cum: int + variant_records_cum: int + requested_worker_minutes_cum: float + execution_metrics_cum: dict[str, object] + + +class HarnessEpochRecord(TypedDict): + """One completed epoch's execution summary and lane payloads.""" + + schema_version: str + epoch: int + epoch_wall_minutes: float + queue_size: int + execution_unit_count: int + execution_metrics: dict[str, object] + frontier: dict[str, object] | None + lanes: list[HarnessLaneRecord] + + +class HarnessResumeSummary(TypedDict): + """Restart and checkpoint metadata attached to an arm result.""" + + schema_version: str + enabled: bool + resumed: bool + checkpoint_schema_version: str + checkpoint_path: str | None + restored_epoch_count: int + + +class HarnessEpisodePolicy(TypedDict): + """Episode grouping capability mode reported in ``runtime_policy``.""" + + mode: str + adapter_owned_restore: bool + + +class HarnessRuntimePolicy(TypedDict): + """Runtime policy and execution mode metadata for one budget arm.""" + + schema_version: str + item_failure_policy: str + item_exception_isolation: bool + episode_execution: HarnessEpisodePolicy + planner_guidance: dict[str, dict[str, object]] + + +class HarnessArmResult(TypedDict): + """Full structured payload returned by ``run_budget_arm``.""" + + schema_version: str + arm_key: str + budget_minutes: float + elapsed_minutes: float + stop_reason: str + epoch_count: int + raw_value_total: float + novel_value_total: float + variant_records_total: int + execution_metrics: dict[str, object] + coverage_count: int + coverage_first_seen_minutes: dict[str, float] + checkpoints: list[HarnessCheckpointPoint] + epochs: list[HarnessEpochRecord] + resume: HarnessResumeSummary + runtime_policy: HarnessRuntimePolicy + + +class HarnessArmSummary(TypedDict): + """Aggregated summary row for one arm in ``aggregate_arms``.""" + + novel_value_endpoint: object + novel_value_auc: float + raw_value_total: object + coverage_count: object + variant_records_total: object + epoch_count: object + elapsed_minutes: object + stop_reason: object + execution_metrics: dict[str, object] + novel_value_per_requested_worker_minute: float + novel_value_per_effective_compute_minute: float | None + anytime_curve: list[dict[str, object]] + + +class HarnessScoreSummary(TypedDict): + """Top-level N-arm comparison payload returned by ``aggregate_arms``.""" + + schema_version: str + budget_minutes_per_arm: float + worker_count: int + coverage_denominator: int | None + arms: dict[str, HarnessArmSummary] + + +def _now_perf_minutes(start: float) -> float: + return (time.perf_counter() - start) / 60.0 + + +def _write_json(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + + +def _read_json(path: Path) -> object: + if not path.exists(): + return None + try: + return cast(object, json.loads(path.read_text(encoding="utf-8-sig"))) + except json.JSONDecodeError: + return None + + +def _as_float(value: object, *, default: float = 0.0) -> float: + if value is None or value == "": + return default + if isinstance(value, (int, float, str)): + return float(value) + raise TypeError(f"expected numeric value, got {type(value).__name__}") + + +def _as_int(value: object, *, default: int = 0) -> int: + if value is None or value == "": + return default + if isinstance(value, (int, float, str)): + return int(value) + raise TypeError(f"expected integer value, got {type(value).__name__}") + + +def _collection_or_empty( + raw: object, + *, + field_name: str, +) -> Collection[object]: + """Accept collections and baseline empty containers; fail closed otherwise.""" + + if raw is None or raw == {} or raw == []: + return () + if isinstance(raw, Collection) and not isinstance( + raw, (str, bytes, bytearray, Mapping) + ): + return raw + raise TypeError(f"{field_name} must be a sequence") + + +def _mapping_or_empty( + raw: object, + *, + field_name: str, +) -> Mapping[object, object]: + """Accept mappings and legacy empty lists; fail closed on invalid types.""" + + if raw is None or raw == [] or raw == (): + return {} + if isinstance(raw, Mapping): + return raw + raise TypeError(f"{field_name} must be a mapping") + + +def _normalize_item_failure_policy(value: object) -> str: + if isinstance(value, ItemFailurePolicy): + return value.value + policy = str(value or ITEM_FAILURE_POLICY_RECORD).strip().lower().replace("_", "-") + if policy not in ITEM_FAILURE_POLICIES: + raise ValueError( + "item_failure_policy must be one of: " + + ", ".join(sorted(ITEM_FAILURE_POLICIES)) + ) + return policy + + +def _adapter_error_record( + item: Mapping[str, object], + error: Exception, + *, + duration_minutes: float, +) -> dict[str, object]: + message = " ".join(str(error).split()) + spec = item.get("variant_spec") + return { + "item_id": item.get("item_id"), + "family": item.get("family"), + "is_variant": bool(item.get("is_variant")), + # The error factory must never raise itself: a malformed variant_spec + # would otherwise escalate one recordable failure into a lost lane. + "variant_spec_id": ( + spec.get("spec_id") + if item.get("is_variant") and isinstance(spec, Mapping) + else None + ), + "execution_status": "adapter_error", + "item_failure_policy": ITEM_FAILURE_POLICY_RECORD, + "accepted": False, + "observation_keys": [], + "weighted_flags": {}, + "duration_minutes": max(_MIN_DURATION_MINUTES, float(duration_minutes)), + "retryable_infra_error": bool( + getattr(error, "retryable_infra_error", False) + ), + "adapter_error": { + "schema_version": "loopx_explore_adapter_error_v0", + "type": type(error).__name__, + "message": message[:240], + }, + } + + +def _normalize_outcome_batch( + outcome: object, + *, + item: Mapping[str, object], +) -> list[dict[str, object]]: + if isinstance(outcome, Mapping): + batch = [dict(outcome)] + elif isinstance(outcome, Sequence) and not isinstance( + outcome, (str, bytes, bytearray) + ): + batch = [] + for candidate in outcome: + if not isinstance(candidate, Mapping): + raise TypeError( + "queue execute sequences must contain dict observation records" + ) + batch.append(dict(candidate)) + else: + raise TypeError( + "queue execute must return a dict or sequence of dict observations" + ) + if not batch: + raise TypeError("queue execute must return at least one observation") + spec = item.get("variant_spec") + spec_id = spec.get("spec_id") if isinstance(spec, Mapping) else None + for record in batch: + record.setdefault("item_id", item.get("item_id")) + record.setdefault("family", item.get("family")) + record.setdefault("is_variant", bool(item.get("is_variant"))) + if item.get("is_variant"): + record.setdefault("variant_spec_id", spec_id) + return batch + + +def _pull_next_item( + pending: list[dict[str, object]], + in_flight: set[str], + lock: threading.Lock, +) -> dict[str, object] | None: + with lock: + for index, item in enumerate(pending): + keys = item_concurrency_keys(item) + if any(key in in_flight for key in keys): + continue + pending.pop(index) + in_flight.update(keys) + return item + return None + + +def _run_queue_worker( + worker_index: int, + *, + pending: list[dict[str, object]], + in_flight: set[str], + lock: threading.Lock, + execute: Callable[..., object], + run_root: Path, + arm: str, + epoch: int, + stagger_seconds: float, + failure_policy: str, +) -> HarnessLaneRecord: + branch_id = f"queue_worker_{worker_index + 1:02d}" + started_at = time.perf_counter() + if worker_index and stagger_seconds > 0: + time.sleep(min(30.0, worker_index * stagger_seconds)) + results: list[dict[str, object]] = [] + while True: + item = _pull_next_item(pending, in_flight, lock) + if item is None: + with lock: + if not pending: + break + time.sleep(0.5) + continue + keys = item_concurrency_keys(item) + item_started = time.perf_counter() + try: + outcome = execute( + item, run_root=run_root, arm=arm, epoch=epoch, branch_id=branch_id + ) + batch = _normalize_outcome_batch(outcome, item=item) + except Exception as error: + if failure_policy == ITEM_FAILURE_POLICY_FATAL: + raise + batch = [ + _adapter_error_record( + item, + error, + duration_minutes=_now_perf_minutes(item_started), + ) + ] + finally: + if keys: + with lock: + in_flight.difference_update(keys) + results.extend(batch) + return { + "branch_id": branch_id, + "launch_index": worker_index, + "wall_minutes": round(_now_perf_minutes(started_at), 3), + "item_ids": [record.get("item_id") for record in results], + "families": [record.get("family") for record in results], + "results": results, + } + + +def run_queue_epoch( + items: Sequence[Mapping[str, object]], + *, + execute: Callable[..., object], + worker_count: int, + run_root: Path, + arm: str, + epoch: int, + stagger_seconds: float = 0.0, + item_failure_policy: str = ITEM_FAILURE_POLICY_RECORD, +) -> list[HarnessLaneRecord]: + """Drain one epoch's work items through a shared pull queue. + + Items may declare one ``concurrency_key`` or several ``concurrency_keys``. + Any overlap with an in-flight item waits until all keys free up (the generic + form of "same write scope must serialize"); disjoint items run concurrently + up to ``worker_count`` pullers. Returns per-worker lane records. + """ + + failure_policy = _normalize_item_failure_policy(item_failure_policy) + lock = threading.Lock() + pending: list[dict[str, object]] = [dict(item) for item in items] + in_flight: set[str] = set() + thread_count = max(1, min(int(worker_count), len(pending) or 1)) + with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as pool: + futures = [ + pool.submit( + _run_queue_worker, + index, + pending=pending, + in_flight=in_flight, + lock=lock, + execute=execute, + run_root=run_root, + arm=arm, + epoch=epoch, + stagger_seconds=stagger_seconds, + failure_policy=failure_policy, + ) + for index in range(thread_count) + ] + lanes = [future.result() for future in concurrent.futures.as_completed(futures)] + lanes.sort(key=lambda lane: str(lane.get("branch_id"))) + return lanes + + +def step_auc( + checkpoints: Sequence[Mapping[str, object]], + *, + value_key: str, + horizon_minutes: float, +) -> float: + """Step-integrate a cumulative anytime curve to the budget horizon.""" + + auc = 0.0 + prev_t = 0.0 + prev_v = 0.0 + horizon = float(horizon_minutes) + for checkpoint in checkpoints: + elapsed = checkpoint.get("elapsed_minutes") + t = min(_as_float(elapsed) if elapsed is not None else 0.0, horizon) + if t > prev_t: + auc += prev_v * (t - prev_t) + prev_t = t + val = checkpoint.get(value_key) + prev_v = _as_float(val) if val is not None else 0.0 + if horizon > prev_t: + auc += prev_v * (horizon - prev_t) + return round(auc, 3) + + +def aggregate_arms( + arms: Mapping[str, Mapping[str, object]], + *, + budget_minutes: float, + worker_count: int, + coverage_denominator: int | None = None, +) -> HarnessScoreSummary: + """Generic two-arm (or N-arm) comparison on novelty-first metrics.""" + + arm_summaries: dict[str, HarnessArmSummary] = {} + for arm_key, arm in arms.items(): + raw_checkpoints = arm.get("checkpoints") + checkpoints = [ + dict(point) + for point in _collection_or_empty(raw_checkpoints, field_name="checkpoints") + if isinstance(point, Mapping) + ] + raw_metrics = arm.get("execution_metrics") + execution_metrics: dict[str, object] = ( + dict(raw_metrics) if isinstance(raw_metrics, Mapping) else {} + ) + effective_compute = _as_float( + execution_metrics.get("effective_compute_minutes") or 0.0 + ) + novel_total = arm.get("novel_value_total") + novel_float = _as_float(novel_total) if novel_total is not None else 0.0 + arm_summaries[arm_key] = { + "novel_value_endpoint": novel_total, + "novel_value_auc": step_auc( + checkpoints, value_key="novel_value_cum", horizon_minutes=budget_minutes + ), + "raw_value_total": arm.get("raw_value_total"), + "coverage_count": arm.get("coverage_count"), + "variant_records_total": arm.get("variant_records_total"), + "epoch_count": arm.get("epoch_count"), + "elapsed_minutes": arm.get("elapsed_minutes"), + "stop_reason": arm.get("stop_reason"), + "execution_metrics": execution_metrics, + "novel_value_per_requested_worker_minute": round( + novel_float / max(0.001, float(budget_minutes) * worker_count), + 4, + ), + "novel_value_per_effective_compute_minute": ( + round(novel_float / effective_compute, 4) + if effective_compute > 0 + else None + ), + "anytime_curve": checkpoints, + } + return { + "schema_version": "loopx_explore_harness_score_v0", + "budget_minutes_per_arm": float(budget_minutes), + "worker_count": int(worker_count), + "coverage_denominator": coverage_denominator, + "arms": arm_summaries, + } + + +def arm_runtime_signature( + adapter: object, + *, + arm_key: str, + worker_count: int, + use_router: bool, + frontier_max_lanes: int, + variant_catalog_enabled: bool, + goal_id: str, + agent_id: str, + item_failure_policy: str, + episode_mode: str | None, +) -> dict[str, object]: + """Build the runtime compatibility signature persisted in arm checkpoints.""" + + adapter_type = f"{type(adapter).__module__}.{type(adapter).__qualname__}" + # Missing keys in legacy manifests read as None, so old standalone arms + # remain compatible while a recoverable arm cannot resume as standalone. + return { + "arm_key": str(arm_key), + "adapter_type": adapter_type, + "worker_count": max(1, int(worker_count)), + "use_router": bool(use_router), + "frontier_max_lanes": max(0, int(frontier_max_lanes)), + "variant_catalog_enabled": bool(variant_catalog_enabled), + "goal_id": str(goal_id), + "agent_id": str(agent_id), + "item_failure_policy": item_failure_policy, + "episode_mode": episode_mode, + } + + +def build_arm_runtime_policy( + *, + failure_policy: str, + episode_mode: str | None, +) -> HarnessRuntimePolicy: + """Build the typed ``runtime_policy`` projection returned by ``run_budget_arm``.""" + + return { + "schema_version": HARNESS_RUNTIME_POLICY_SCHEMA_VERSION, + "item_failure_policy": failure_policy, + "item_exception_isolation": failure_policy == ITEM_FAILURE_POLICY_RECORD, + "episode_execution": { + "mode": episode_mode or "standalone", + "adapter_owned_restore": episode_mode is not None, + }, + "planner_guidance": { + "retry_backoff": {"enforced": False, "owner": "external_runner"}, + "infra_cooldown": {"enforced": False, "owner": "external_runner"}, + }, + } diff --git a/loopx/capabilities/explore/harness_runtime.py b/loopx/capabilities/explore/harness_runtime.py index 9de5b38850..48a1a503b1 100644 --- a/loopx/capabilities/explore/harness_runtime.py +++ b/loopx/capabilities/explore/harness_runtime.py @@ -1,35 +1,3 @@ -from __future__ import annotations - -import json -import threading -import time -from enum import Enum -from pathlib import Path -from typing import Any, Callable, Mapping, Sequence - -from .episode_runtime import ( - RECORD_KIND_STANDALONE, - build_episode_execution_units, - build_router_probes, - combine_execution_metrics, - execute_episode_group, - item_concurrency_keys, - recoverable_episode_mode, - summarize_execution_records, -) -from .harness_checkpoint import ( - HARNESS_CHECKPOINT_SCHEMA_VERSION, - build_arm_checkpoint, - load_arm_checkpoint, - write_arm_checkpoint, -) -from .router_state import ( - advance_epoch, - initial_router_state, - observe_epoch, -) -from .worker_branch_plan import build_explore_worker_branch_plan - """Software-agnostic exploration harness runtime. This module is the generic half of a two-layer design: @@ -55,603 +23,359 @@ planner uses; - novelty is only ever credited from observation keys and weighted flags the adapter reports; specs carry intent, not novelty. - -Adapter protocol (duck-typed; see the experiment layer for a reference -implementation): - -- ``list_seed_items() -> list[dict]``: fresh seed work items each epoch, - each with ``item_id``, ``text``, ``family``; optional ``payload``. -- ``execute(item, *, run_root, arm, epoch, branch_id) -> dict``: run one work - item and return an observation record with ``item_id``, ``family``, - ``observation_keys`` (list[str]), ``weighted_flags`` ({name: weight} for - true flags), ``accepted`` (bool), ``duration_minutes`` (float), - ``retryable_infra_error`` (bool), plus any adapter-private fields. -- ``compile_variant(spec, seed_item) -> dict``: turn an agent-authored - variant spec into an executable work item (``is_variant`` True, - ``variant_spec`` attached, own ``concurrency_key``). -- ``flag_weights`` is implicit: the adapter reports weights per record, so - the harness never holds a domain weight table. -- ``item_failure_policy`` may be set to ``"fatal"`` on the adapter to make - execution exceptions propagate; the default ``"record"`` policy emits a - zero-value structured observation and keeps independent lanes running. -- Adapters that can checkpoint an expensive shared execution prefix may - optionally implement all three recoverable-episode methods: - ``prepare_episode_group(seed_item, episode_items, **context)`` returns - ``{handle, prefix_record, checkpoint_ref?}``, ``execute_episode(handle, - item, **context)`` returns a suffix-only observation, and - ``release_episode_group(handle, **context)`` releases adapter-owned state. - Returning ``None`` from prepare is an explicit, side-effect-free fallback - to legacy ``execute`` for that group (the only case where an episode - adapter needs ``execute`` at all). The adapter owns all restore mechanics. - Distinct groups run concurrently on separate workers, so the three methods - must be thread-safe across groups; concurrently active handles must not alias - mutable state, while safe sequential or immutable reuse remains valid. - Malformed grouping inputs (empty or duplicate seed/variant ids, id - collisions, or variants naming an unknown seed) degrade through the item - failure policy like any execution error: structured records under ``record``, - or a pre-dispatch raised error under ``fatal``. """ +from __future__ import annotations +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +import time +from typing import cast -HARNESS_ARM_SCHEMA_VERSION = "loopx_explore_harness_arm_v0" -VARIANT_CATALOG_SCHEMA_VERSION = "loopx_explore_variant_catalog_v0" -FRONTIER_REQUESTS_SCHEMA_VERSION = "loopx_explore_frontier_requests_v0" -HARNESS_RUNTIME_POLICY_SCHEMA_VERSION = "loopx_explore_harness_runtime_policy_v0" - -class ItemFailurePolicy(str, Enum): - RECORD = "record" - FATAL = "fatal" - - -ITEM_FAILURE_POLICY_RECORD = ItemFailurePolicy.RECORD.value -ITEM_FAILURE_POLICY_FATAL = ItemFailurePolicy.FATAL.value -ITEM_FAILURE_POLICIES = {policy.value for policy in ItemFailurePolicy} - -DEFAULT_OBSERVATION_WEIGHT = 1.0 -_MIN_DURATION_MINUTES = 0.05 - - -def _now_perf_minutes(start: float) -> float: - return (time.perf_counter() - start) / 60.0 - - -def _write_json(path: Path, payload: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - - -def _read_json(path: Path) -> Any: - if not path.exists(): - return None - try: - return json.loads(path.read_text(encoding="utf-8-sig")) - except json.JSONDecodeError: - return None - +from .episode_runtime import ( + RECORD_KIND_STANDALONE, + build_episode_execution_units, + combine_execution_metrics, + execute_episode_group, + recoverable_episode_mode, + summarize_execution_records, +) +from .harness_checkpoint import ( + HARNESS_CHECKPOINT_SCHEMA_VERSION, + build_arm_checkpoint, + load_arm_checkpoint, + write_arm_checkpoint, +) +from .harness_frontier import ( + FRONTIER_REQUESTS_SCHEMA_VERSION as FRONTIER_REQUESTS_SCHEMA_VERSION, + VARIANT_CATALOG_SCHEMA_VERSION as VARIANT_CATALOG_SCHEMA_VERSION, + NoveltyLedger as NoveltyLedger, + VariantCatalog as VariantCatalog, + _frontier_gain as _frontier_gain, + emit_frontier_requests as emit_frontier_requests, + initial_arm_router_state, + plan_round_robin as plan_round_robin, + plan_router_no_prune as plan_router_no_prune, + select_frontier_work as select_frontier_work, + update_router_epoch_feedback, +) +from .harness_queue import ( + DEFAULT_OBSERVATION_WEIGHT as DEFAULT_OBSERVATION_WEIGHT, + HARNESS_ARM_SCHEMA_VERSION as HARNESS_ARM_SCHEMA_VERSION, + HARNESS_RUNTIME_POLICY_SCHEMA_VERSION as HARNESS_RUNTIME_POLICY_SCHEMA_VERSION, + ITEM_FAILURE_POLICIES as ITEM_FAILURE_POLICIES, + ITEM_FAILURE_POLICY_FATAL as ITEM_FAILURE_POLICY_FATAL, + ITEM_FAILURE_POLICY_RECORD as ITEM_FAILURE_POLICY_RECORD, + _MIN_DURATION_MINUTES as _MIN_DURATION_MINUTES, + HarnessArmResult as HarnessArmResult, + HarnessArmSummary as HarnessArmSummary, + HarnessCheckpointPoint as HarnessCheckpointPoint, + HarnessEpochRecord as HarnessEpochRecord, + HarnessEpisodePolicy as HarnessEpisodePolicy, + HarnessLaneRecord as HarnessLaneRecord, + HarnessResumeSummary as HarnessResumeSummary, + HarnessRuntimePolicy as HarnessRuntimePolicy, + HarnessScoreSummary as HarnessScoreSummary, + ItemFailurePolicy as ItemFailurePolicy, + SeedAdapter as SeedAdapter, + _adapter_error_record as _adapter_error_record, + _as_float, + _as_int, + _now_perf_minutes as _now_perf_minutes, + _normalize_item_failure_policy as _normalize_item_failure_policy, + _read_json as _read_json, + _write_json as _write_json, + aggregate_arms as aggregate_arms, + arm_runtime_signature as _arm_runtime_signature, + build_arm_runtime_policy, + run_queue_epoch as run_queue_epoch, + step_auc as step_auc, +) -def _normalize_item_failure_policy(value: Any) -> str: - if isinstance(value, ItemFailurePolicy): - return value.value - policy = str(value or ITEM_FAILURE_POLICY_RECORD).strip().lower().replace("_", "-") - if policy not in ITEM_FAILURE_POLICIES: - raise ValueError( - "item_failure_policy must be one of: " - + ", ".join(sorted(ITEM_FAILURE_POLICIES)) +__all__ = [ + "DEFAULT_OBSERVATION_WEIGHT", + "FRONTIER_REQUESTS_SCHEMA_VERSION", + "HARNESS_ARM_SCHEMA_VERSION", + "HARNESS_RUNTIME_POLICY_SCHEMA_VERSION", + "ITEM_FAILURE_POLICIES", + "ITEM_FAILURE_POLICY_FATAL", + "ITEM_FAILURE_POLICY_RECORD", + "VARIANT_CATALOG_SCHEMA_VERSION", + "HarnessArmResult", + "HarnessArmSummary", + "HarnessCheckpointPoint", + "HarnessEpochRecord", + "HarnessEpisodePolicy", + "HarnessLaneRecord", + "HarnessResumeSummary", + "HarnessRuntimePolicy", + "HarnessScoreSummary", + "ItemFailurePolicy", + "NoveltyLedger", + "SeedAdapter", + "VariantCatalog", + "aggregate_arms", + "emit_frontier_requests", + "plan_round_robin", + "plan_router_no_prune", + "run_budget_arm", + "run_queue_epoch", + "select_frontier_work", + "step_auc", +] + + +@dataclass +class _ArmExecutionState: + epochs: list[HarnessEpochRecord] + checkpoints: list[HarnessCheckpointPoint] + coverage_first_seen: dict[str, float] + router_state: dict[str, object] | None + load_profile: dict[str, object] | None + raw_cum: float + novel_cum: float + variant_records_cum: int + next_epoch: int + elapsed_offset: float + execution_metrics_cum: dict[str, object] + + +def _seed_historical_execution_metrics( + epochs: Sequence[HarnessEpochRecord], + *, + episode_mode: str | None, +) -> dict[str, object]: + execution_metric_fields = set(combine_execution_metrics([])) + historical_execution_metrics: list[dict[str, object]] = [] + for completed_epoch in epochs: + stored_metrics = completed_epoch.get("execution_metrics") + if ( + isinstance(stored_metrics, Mapping) + and execution_metric_fields.issubset(stored_metrics) + ): + historical_execution_metrics.append(dict(stored_metrics)) + continue + historical_records: list[Mapping[str, object]] = [ + record + for lane in completed_epoch.get("lanes") or () + for record in lane.get("results") or () + ] + if episode_mode is None: + historical_records = [ + { + **record, + "execution_group_id": None, + "record_kind": RECORD_KIND_STANDALONE, + } + for record in historical_records + ] + historical_execution_metrics.append( + dict(summarize_execution_records(historical_records)) ) - return policy + return dict(combine_execution_metrics(historical_execution_metrics)) -def _adapter_error_record( - item: Mapping[str, Any], - error: Exception, +def _restore_arm_state( *, - duration_minutes: float, -) -> dict[str, Any]: - message = " ".join(str(error).split()) - spec = item.get("variant_spec") - return { - "item_id": item.get("item_id"), - "family": item.get("family"), - "is_variant": bool(item.get("is_variant")), - # The error factory must never raise itself: a malformed variant_spec - # would otherwise escalate one recordable failure into a lost lane. - "variant_spec_id": ( - spec.get("spec_id") - if item.get("is_variant") and isinstance(spec, Mapping) + checkpoint_file: Path, + checkpoint_enabled: bool, + resume: bool, + use_router: bool, + runtime_signature: Mapping[str, object], + ledger: NoveltyLedger, + catalog: VariantCatalog | None, + episode_mode: str | None, +) -> _ArmExecutionState: + epochs: list[HarnessEpochRecord] = [] + checkpoints: list[HarnessCheckpointPoint] = [] + coverage_first_seen: dict[str, float] = {} + router_state = initial_arm_router_state() if use_router else None + load_profile: dict[str, object] | None = None + raw_cum = 0.0 + novel_cum = 0.0 + variant_records_cum = 0 + next_epoch = 1 + elapsed_offset = 0.0 + if resume: + state = load_arm_checkpoint( + checkpoint_file, + expected_signature=runtime_signature, + ) + epochs = [cast(HarnessEpochRecord, dict(epoch)) for epoch in state["epochs"]] + checkpoints = [ + cast(HarnessCheckpointPoint, dict(point)) for point in state["checkpoints"] + ] + ledger.seen = {str(key) for key in state["novelty_seen"]} + router_state = ( + dict(state["router_state"]) + if isinstance(state.get("router_state"), Mapping) else None - ), - "execution_status": "adapter_error", - "item_failure_policy": ITEM_FAILURE_POLICY_RECORD, - "accepted": False, - "observation_keys": [], - "weighted_flags": {}, - "duration_minutes": max(_MIN_DURATION_MINUTES, float(duration_minutes)), - "retryable_infra_error": bool( - getattr(error, "retryable_infra_error", False) - ), - "adapter_error": { - "schema_version": "loopx_explore_adapter_error_v0", - "type": type(error).__name__, - "message": message[:240], - }, - } - - -class NoveltyLedger: - """First-seen ledger: raw observation keys global, flags family-scoped. - - Raw keys are ledgered globally so relabeling an item under a different - family can never re-mint an already-seen key; weighted flags are - family-scoped facts. Weights come from the record itself (adapter-owned). - """ - - def __init__(self) -> None: - self.seen: set[str] = set() - - def raw_value(self, record: Mapping[str, Any]) -> float: - keys = record.get("observation_keys") or [] - flags = record.get("weighted_flags") or {} - return DEFAULT_OBSERVATION_WEIGHT * len(keys) + sum( - float(weight) for weight in flags.values() ) - - def credit(self, record: Mapping[str, Any]) -> dict[str, float]: - family = str(record.get("family") or "general") - novel_value = 0.0 - novel_keys = 0 - for key in record.get("observation_keys") or []: - key = str(key) - if key not in self.seen: - self.seen.add(key) - novel_value += DEFAULT_OBSERVATION_WEIGHT - novel_keys += 1 - for flag, weight in (record.get("weighted_flags") or {}).items(): - pseudo = f"flag:{family}:{flag}" - if pseudo not in self.seen: - self.seen.add(pseudo) - novel_value += float(weight) - return {"novel_value": novel_value, "novel_observation_keys": novel_keys} + load_profile = ( + dict(state["load_profile"]) + if isinstance(state.get("load_profile"), Mapping) + else None + ) + coverage_first_seen = { + str(family): _as_float(minutes) + for family, minutes in state["coverage_first_seen"].items() + } + raw_cum = _as_float(state.get("raw_value_total") or 0.0) + novel_cum = _as_float(state.get("novel_value_total") or 0.0) + variant_records_cum = _as_int(state.get("variant_records_total") or 0) + next_epoch = _as_int(state["next_epoch"]) + elapsed_offset = _as_float(state.get("elapsed_minutes") or 0.0) + if catalog is not None: + catalog.restore_consumed(state["catalog_consumed"]) + elif checkpoint_enabled and catalog is not None: + # Reusing a run_root is not an implicit restart contract. A fresh arm + # starts with fresh consumption; only resume restores prior attempts. + catalog.restore_consumed([]) + if not resume: + checkpoint_file.unlink(missing_ok=True) + return _ArmExecutionState( + epochs=epochs, + checkpoints=checkpoints, + coverage_first_seen=coverage_first_seen, + router_state=router_state, + load_profile=load_profile, + raw_cum=raw_cum, + novel_cum=novel_cum, + variant_records_cum=variant_records_cum, + next_epoch=next_epoch, + elapsed_offset=elapsed_offset, + execution_metrics_cum=_seed_historical_execution_metrics( + epochs, episode_mode=episode_mode + ), + ) -def run_queue_epoch( - items: Sequence[Mapping[str, Any]], +def _epoch_executor( + adapter: object, *, - execute: Callable[..., dict[str, Any] | Sequence[dict[str, Any]]], - worker_count: int, - run_root: Path, - arm: str, - epoch: int, - stagger_seconds: float = 0.0, - item_failure_policy: str = ITEM_FAILURE_POLICY_RECORD, -) -> list[dict[str, Any]]: - """Drain one epoch's work items through a shared pull queue. - - Items may declare one ``concurrency_key`` or several ``concurrency_keys``. - Any overlap with an in-flight item waits until all keys free up (the generic - form of "same write scope must serialize"); disjoint items run concurrently - up to ``worker_count`` pullers. Returns per-worker lane records. - """ - - failure_policy = _normalize_item_failure_policy(item_failure_policy) - lock = threading.Lock() - pending: list[dict[str, Any]] = [dict(item) for item in items] - in_flight: set[str] = set() - - def pull_next() -> dict[str, Any] | None: - with lock: - for index, item in enumerate(pending): - keys = item_concurrency_keys(item) - if any(key in in_flight for key in keys): - continue - pending.pop(index) - in_flight.update(keys) - return item - return None + episode_mode: str | None, + failure_policy: str, +) -> Callable[..., object]: + if episode_mode is not None: - def worker(worker_index: int) -> dict[str, Any]: - branch_id = f"queue_worker_{worker_index + 1:02d}" - started_at = time.perf_counter() - if worker_index and stagger_seconds > 0: - time.sleep(min(30.0, worker_index * stagger_seconds)) - results: list[dict[str, Any]] = [] - while True: - item = pull_next() - if item is None: - with lock: - if not pending: - break - time.sleep(0.5) - continue - keys = item_concurrency_keys(item) - item_started = time.perf_counter() - try: - outcome = execute( - item, run_root=run_root, arm=arm, epoch=epoch, branch_id=branch_id + def _run_episode(item: Mapping[str, object], **context: object) -> list[dict[str, object]]: + return list( + execute_episode_group( + item, + adapter=adapter, + failure_policy=failure_policy, + fatal_failure_policy=ITEM_FAILURE_POLICY_FATAL, + error_record_factory=_adapter_error_record, + run_root=cast(Path, context["run_root"]), + arm=str(context["arm"]), + epoch=cast(int, context["epoch"]), + branch_id=str(context["branch_id"]), ) - if isinstance(outcome, Mapping): - batch = [dict(outcome)] - elif isinstance(outcome, Sequence) and not isinstance( - outcome, (str, bytes) - ): - batch = [] - for candidate in outcome: - if not isinstance(candidate, Mapping): - raise TypeError( - "queue execute sequences must contain dict observation records" - ) - batch.append(dict(candidate)) - else: - raise TypeError( - "queue execute must return a dict or sequence of dict observations" - ) - if not batch: - raise TypeError("queue execute must return at least one observation") - for record in batch: - record.setdefault("item_id", item.get("item_id")) - record.setdefault("family", item.get("family")) - record.setdefault("is_variant", bool(item.get("is_variant"))) - if item.get("is_variant"): - record.setdefault( - "variant_spec_id", - (item.get("variant_spec") or {}).get("spec_id"), - ) - except Exception as error: - if failure_policy == ITEM_FAILURE_POLICY_FATAL: - raise - batch = [ - _adapter_error_record( - item, - error, - duration_minutes=_now_perf_minutes(item_started), - ) - ] - finally: - if keys: - with lock: - in_flight.difference_update(keys) - results.extend(batch) - return { - "branch_id": branch_id, - "launch_index": worker_index, - "wall_minutes": round(_now_perf_minutes(started_at), 3), - "item_ids": [r.get("item_id") for r in results], - "families": [r.get("family") for r in results], - "results": results, - } - - thread_count = max(1, min(int(worker_count), len(pending) or 1)) - import concurrent.futures - - with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as pool: - futures = [pool.submit(worker, index) for index in range(thread_count)] - lanes = [future.result() for future in concurrent.futures.as_completed(futures)] - lanes.sort(key=lambda lane: str(lane.get("branch_id"))) - return lanes - - -def _frontier_gain(router_state: Mapping[str, Any] | None, family: str, *, epoch: int) -> float: - """Expected value of spending a speculative slot near this family. - - Generic signals only: whether the base loop has probed the family yet, - its residual novelty pressure, and a small age bonus. Field names track - the router_state family schema; the lookup accepts both the raw family - id and adapter-prefixed forms (e.g. 'scope:artifacts/'). - """ - - stats: Mapping[str, Any] = {} - families = (router_state or {}).get("families") if isinstance(router_state, Mapping) else None - if isinstance(families, Mapping): - exact = families.get(family) - if isinstance(exact, Mapping): - stats = exact - else: - suffix = "/" + str(family) - for key, value in families.items(): - if isinstance(value, Mapping) and str(key).endswith(suffix): - stats = value - break - score = 1.0 - runs = float(stats.get("runs") or 0.0) - if runs <= 0: - score += 1.25 - else: - novelty_rate = stats.get("novelty_rate") - if novelty_rate is not None: - score += min(1.25, max(0.0, float(novelty_rate)) * 1.25) - accept_rate = stats.get("accept_rate_ema") - if accept_rate is not None and float(accept_rate) <= 0.5: - score += 0.25 - score += min(0.5, max(0, int(epoch) - 1) * 0.03) - return round(score, 4) - - -class VariantCatalog: - """Agent-authored variant specs + per-arm consumption bookkeeping. - - Catalog file schema (written by the experiment agent, never by code): - ``{"schema_version": ..., "specs": [{"spec_id", "seed_family", - "intent", "ops": [...adapter-defined...], "key_prefix", - "seed_item_id"?, "priority"?}]}``. The harness treats ``ops`` as opaque. - """ - - def __init__(self, catalog_path: Path, consumption_path: Path) -> None: - self.catalog_path = Path(catalog_path) - self.consumption_path = Path(consumption_path) - consumed = _read_json(self.consumption_path) - self.consumed: set[str] = set(consumed or []) - - def _specs(self) -> list[dict[str, Any]]: - payload = _read_json(self.catalog_path) - specs = (payload or {}).get("specs") if isinstance(payload, Mapping) else None - return [dict(spec) for spec in specs or [] if spec.get("spec_id")] - - def pending_for(self, family: str) -> list[dict[str, Any]]: - return [ - spec - for spec in self._specs() - if str(spec.get("seed_family") or "") == str(family) - and str(spec.get("spec_id")) not in self.consumed - ] - - def pending_count(self) -> int: - return len([s for s in self._specs() if str(s.get("spec_id")) not in self.consumed]) - - def consume(self, spec_id: str) -> None: - self.consumed.add(str(spec_id)) - _write_json(self.consumption_path, sorted(self.consumed)) + ) - def restore_consumed(self, spec_ids: Sequence[Any]) -> None: - self.consumed = {str(spec_id) for spec_id in spec_ids if str(spec_id).strip()} - _write_json(self.consumption_path, sorted(self.consumed)) + return _run_episode + # Accessed lazily so an episode-only adapter (no legacy execute) is valid + # as long as prepare_episode_group never returns None. + execute_fn = getattr(adapter, "execute", None) + if not callable(execute_fn): + raise AttributeError(f"{type(adapter).__name__!r} object has no attribute 'execute'") + return cast(Callable[..., object], execute_fn) -def select_frontier_work( - seed_items: Sequence[Mapping[str, Any]], +def _record_epoch_outcomes( *, - catalog: VariantCatalog, - adapter: Any, - router_state: Mapping[str, Any] | None, + state: _ArmExecutionState, + lanes: list[HarnessLaneRecord], + seed_items: Sequence[Mapping[str, object]], + queue_size: int, + execution_unit_count: int, + frontier_audit: dict[str, object] | None, + ledger: NoveltyLedger, + episode_mode: str | None, + use_router: bool, + worker_count: int, epoch: int, - max_lanes: int, -) -> tuple[list[dict[str, Any]], dict[str, Any]]: - """Pick up to ``max_lanes`` agent-authored variant specs to execute. - - Seeds are ranked by the generic frontier gain with an epoch-rotating - tie-break (multiplicative permutation over a prime modulus) so equal - gains spread across families over epochs instead of freezing on an - alphabetical prefix. Spec choice within a family follows the agent's - ``priority`` then catalog order. The harness only ever schedules specs; - it cannot invent them. - """ - - import hashlib - - def _hash(value: str) -> int: - return int(hashlib.sha1(value.encode("utf-8")).hexdigest()[:8], 16) - - by_family: dict[str, Mapping[str, Any]] = {} - for item in seed_items: - family = str(item.get("family") or "") - if family and family not in by_family: - by_family[family] = item - ranked = sorted( - by_family.items(), - key=lambda pair: ( - -_frontier_gain(router_state, pair[0], epoch=epoch), - (_hash(pair[0]) * (2 * int(epoch) + 1)) % 1_000_003, - pair[0], - ), - ) - selected: list[dict[str, Any]] = [] - audit_specs: list[dict[str, Any]] = [] - for family, seed in ranked: - if len(selected) >= max(0, int(max_lanes)): - break - pending = sorted( - catalog.pending_for(family), - key=lambda spec: (-float(spec.get("priority") or 0.0), str(spec.get("spec_id"))), - ) - if not pending: - continue - spec = pending[0] - item = adapter.compile_variant(spec, dict(seed)) - item.setdefault("is_variant", True) - item.setdefault("variant_spec", spec) - item.setdefault("family", family) - item.setdefault("seed_item_id", seed.get("item_id")) - item.setdefault( - "concurrency_key", f"{family}:variant:{spec.get('spec_id')}" - ) - catalog.consume(str(spec.get("spec_id"))) - selected.append(item) - audit_specs.append( + epoch_wall: float, + started: float, + run_root: Path, + arm_key: str, +) -> None: + epoch_raw = 0.0 + epoch_novel = 0.0 + records: list[dict[str, object]] = [] + for lane in lanes: + for record in lane.get("results") or (): + credit = ledger.credit(record) + record["novel_value"] = credit["novel_value"] + record["raw_value"] = ledger.raw_value(record) + epoch_raw += _as_float(record["raw_value"]) + epoch_novel += credit["novel_value"] + if record.get("is_variant"): + state.variant_records_cum += 1 + records.append(record) + state.raw_cum += epoch_raw + state.novel_cum += epoch_novel + metric_records: list[Mapping[str, object]] = ( + list(records) + if episode_mode is not None + else [ { - "spec_id": spec.get("spec_id"), - "seed_family": family, - "intent": spec.get("intent"), - "gain": _frontier_gain(router_state, family, epoch=epoch), + **record, + "execution_group_id": None, + "record_kind": RECORD_KIND_STANDALONE, } + for record in records + ] + ) + epoch_execution_metrics = dict(summarize_execution_records(metric_records)) + state.execution_metrics_cum = dict( + combine_execution_metrics([state.execution_metrics_cum, epoch_execution_metrics]) + ) + elapsed_after = state.elapsed_offset + _now_perf_minutes(started) + for record in records: + family = str(record.get("family") or "") + if family: + state.coverage_first_seen.setdefault(family, round(elapsed_after, 3)) + if use_router: + state.router_state, state.load_profile = update_router_epoch_feedback( + current_router_state=state.router_state, + records=records, + seed_items=seed_items, + lanes=lanes, + episode_mode=episode_mode, + epoch=epoch, + epoch_wall=epoch_wall, + run_root=run_root, + arm_key=arm_key, ) - audit = { - "requested_lanes": int(max_lanes), - "admitted": len(selected), - "catalog_pending_after": catalog.pending_count(), - "specs": audit_specs, - } - return selected, audit - - -def emit_frontier_requests( - path: Path, - *, - arm_key: str, - epoch: int, - seed_items: Sequence[Mapping[str, Any]], - ledger: NoveltyLedger, - catalog: VariantCatalog, - router_state: Mapping[str, Any] | None, - per_family_key_cap: int = 24, -) -> None: - """Publish what the harness NEEDS from the experiment agent. - - The agent (a Claude/Codex session driving the experiment) reads this - packet -- seed text plus a digest of already-seen observation keys and - exhausted specs -- and appends new specs to the variant catalog. This is - the LoopX interaction pattern: packet out, decision in, no LLM calls - from code. - """ - - families: dict[str, dict[str, Any]] = {} - for item in seed_items: - family = str(item.get("family") or "") - if not family or family in families: - continue - seen_for_family = sorted( - key - for key in ledger.seen - if not key.startswith("flag:") or key.startswith(f"flag:{family}:") - )[: max(1, per_family_key_cap)] - families[family] = { - "family": family, - "seed_item_id": item.get("item_id"), - "seed_text": item.get("text"), - "pending_spec_count": len(catalog.pending_for(family)), - "frontier_gain": _frontier_gain(router_state, family, epoch=epoch), - "seen_keys_sample": seen_for_family, - } - _write_json( - path, + state.checkpoints.append( { - "schema_version": FRONTIER_REQUESTS_SCHEMA_VERSION, - "arm": arm_key, - "epoch": int(epoch), - "total_seen_keys": len(ledger.seen), - "catalog_pending_total": catalog.pending_count(), - "families": sorted(families.values(), key=lambda f: -float(f["frontier_gain"])), - "how_to_respond": ( - "Append specs to the variant catalog file: {spec_id, seed_family, " - "intent, ops (adapter-defined), key_prefix, priority}. The harness " - "schedules them by frontier gain; it never invents specs." - ), - }, + "epoch": epoch, + "elapsed_minutes": round(elapsed_after, 3), + "raw_value_cum": round(state.raw_cum, 3), + "novel_value_cum": round(state.novel_cum, 3), + "coverage_count_cum": len(state.coverage_first_seen), + "variant_records_cum": state.variant_records_cum, + "requested_worker_minutes_cum": round(elapsed_after * worker_count, 3), + "execution_metrics_cum": dict(state.execution_metrics_cum), + } ) - - -def plan_round_robin(seed_items: Sequence[Mapping[str, Any]], **_: Any) -> list[dict[str, Any]]: - """Baseline planner: every seed, catalog untouched, no ordering signal.""" - - return [dict(item) for item in seed_items] - - -def plan_router_no_prune( - seed_items: Sequence[Mapping[str, Any]], - *, - goal_id: str, - agent_id: str, - worker_count: int, - router_state: Mapping[str, Any] | None, - load_profile: Mapping[str, Any] | None, - harness_profile: str = "moe-router", - branch_fill_policy: str = "confident-prefix", -) -> list[dict[str, Any]]: - """Router-ordered no-prune planner over generic seed items. - - Uses the LoopX worker-branch planner for VALUE ORDERING only, then - appends every unselected seed as a ranked tail -- sorting without - pruning: an executable seed never loses its slot to low confidence. - """ - - by_id: dict[str, dict[str, Any]] = {} - duplicate_items: list[dict[str, Any]] = [] - for item in seed_items: - item_id = str(item.get("item_id")) - if item_id in by_id: - duplicate_items.append(dict(item)) - else: - by_id[item_id] = dict(item) - todos = [ + state.epochs.append( { - "todo_id": item_id, - "text": str(item.get("text") or item.get("item_id")), - "status": "open", - "task_class": "advancement_task", - "required_write_scopes": [f"artifacts/{item.get('family')}/**"], - "index": index, + "schema_version": HARNESS_ARM_SCHEMA_VERSION, + "epoch": epoch, + "epoch_wall_minutes": round(epoch_wall, 3), + "queue_size": queue_size, + "execution_unit_count": execution_unit_count, + "execution_metrics": epoch_execution_metrics, + "frontier": frontier_audit, + "lanes": lanes, } - for index, (item_id, item) in enumerate(by_id.items()) - ] - plan = build_explore_worker_branch_plan( - goal_id=goal_id, - todos=todos, - agent_id=agent_id, - # This standalone benchmark arm opts in explicitly and consumes value - # ordering only; spawn stays disallowed, so the plan carries no - # suggested claim/lease commands. - orchestration={"explore_harness": {"enabled": True}}, - worker_width=worker_count, - harness_profile=harness_profile, - branch_fill_policy=branch_fill_policy, - router_state=router_state, - load_profile=load_profile, ) - ordered: list[dict[str, Any]] = [] - used: set[str] = set() - for branch in plan.get("selected_worker_branches") or []: - for todo_id in branch.get("todo_ids") or []: - todo_id = str(todo_id) - if todo_id in by_id and todo_id not in used: - ordered.append(by_id[todo_id]) - used.add(todo_id) - for branch in plan.get("rejected_worker_branches") or []: - for todo_id in branch.get("todo_ids") or []: - todo_id = str(todo_id) - if todo_id in by_id and todo_id not in used: - ordered.append(by_id[todo_id]) - used.add(todo_id) - for item_id, item in by_id.items(): - if item_id not in used: - ordered.append(item) - used.add(item_id) - # Preserve malformed duplicates for the episode grouping boundary. The - # planner still reasons over unique ids, but no-prune means it must not - # silently erase an input that record/fatal policy needs to classify. - ordered.extend(duplicate_items) - return ordered - - -def _arm_runtime_signature( - adapter: Any, - *, - arm_key: str, - worker_count: int, - use_router: bool, - frontier_max_lanes: int, - variant_catalog_enabled: bool, - goal_id: str, - agent_id: str, - item_failure_policy: str, - episode_mode: str | None, -) -> dict[str, Any]: - adapter_type = f"{type(adapter).__module__}.{type(adapter).__qualname__}" - signature = { - "arm_key": str(arm_key), - "adapter_type": adapter_type, - "worker_count": max(1, int(worker_count)), - "use_router": bool(use_router), - "frontier_max_lanes": max(0, int(frontier_max_lanes)), - "variant_catalog_enabled": bool(variant_catalog_enabled), - "goal_id": str(goal_id), - "agent_id": str(agent_id), - "item_failure_policy": item_failure_policy, - } - # Missing keys in legacy manifests read as None, so old standalone arms - # remain compatible while a recoverable arm cannot resume as standalone. - signature["episode_mode"] = episode_mode - return signature def run_budget_arm( - adapter: Any, + adapter: object, *, arm_key: str, run_root: Path, @@ -670,7 +394,7 @@ def run_budget_arm( resume: bool = False, checkpoint_path: Path | None = None, item_failure_policy: str | None = None, -) -> dict[str, Any]: +) -> HarnessArmResult: """Run ONE arm alone against its wall-clock budget; return arm payload. ``use_router=False`` is the blind baseline (round-robin sweep, no @@ -707,8 +431,6 @@ def run_budget_arm( episode_mode=episode_mode, ) ledger = NoveltyLedger() - router_state = initial_router_state() if use_router else None - load_profile: Mapping[str, Any] | None = None catalog = ( VariantCatalog( Path(variant_catalog_path), @@ -717,96 +439,33 @@ def run_budget_arm( if variant_catalog_path else None ) - epochs: list[dict[str, Any]] = [] - checkpoints: list[dict[str, Any]] = [] - coverage_first_seen: dict[str, float] = {} - raw_cum = 0.0 - novel_cum = 0.0 - variant_records_cum = 0 - next_epoch = 1 - elapsed_offset = 0.0 - if resume: - state = load_arm_checkpoint( - checkpoint_file, - expected_signature=runtime_signature, - ) - epochs = [dict(epoch) for epoch in state["epochs"]] - checkpoints = [dict(checkpoint) for checkpoint in state["checkpoints"]] - ledger.seen = {str(key) for key in state["novelty_seen"]} - router_state = ( - dict(state["router_state"]) - if isinstance(state.get("router_state"), Mapping) - else None - ) - load_profile = ( - dict(state["load_profile"]) - if isinstance(state.get("load_profile"), Mapping) - else None - ) - coverage_first_seen = { - str(family): float(minutes) - for family, minutes in state["coverage_first_seen"].items() - } - raw_cum = float(state.get("raw_value_total") or 0.0) - novel_cum = float(state.get("novel_value_total") or 0.0) - variant_records_cum = int(state.get("variant_records_total") or 0) - next_epoch = int(state["next_epoch"]) - elapsed_offset = float(state.get("elapsed_minutes") or 0.0) - if catalog is not None: - catalog.restore_consumed(state["catalog_consumed"]) - elif checkpoint_enabled and catalog is not None: - # Reusing a run_root is not an implicit restart contract. A fresh arm - # starts with fresh consumption; only resume restores prior attempts. - catalog.restore_consumed([]) - if not resume: - checkpoint_file.unlink(missing_ok=True) - execution_metric_fields = set(combine_execution_metrics([])) - historical_execution_metrics: list[dict[str, Any]] = [] - for completed_epoch in epochs: - stored_metrics = completed_epoch.get("execution_metrics") - if ( - isinstance(stored_metrics, Mapping) - and execution_metric_fields.issubset(stored_metrics) - ): - historical_execution_metrics.append(dict(stored_metrics)) - continue - historical_records = [ - record - for lane in completed_epoch.get("lanes") or [] - for record in lane.get("results") or [] - ] - if episode_mode is None: - historical_records = [ - { - **record, - "execution_group_id": None, - "record_kind": RECORD_KIND_STANDALONE, - } - for record in historical_records - ] - historical_execution_metrics.append( - summarize_execution_records(historical_records) - ) - execution_metrics_cum = combine_execution_metrics( - historical_execution_metrics + state = _restore_arm_state( + checkpoint_file=checkpoint_file, + checkpoint_enabled=checkpoint_enabled, + resume=resume, + use_router=use_router, + runtime_signature=runtime_signature, + ledger=ledger, + catalog=catalog, + episode_mode=episode_mode, ) stop_reason = "max_epochs" started = time.perf_counter() - for epoch in range(next_epoch, int(max_epochs) + 1): - elapsed = elapsed_offset + _now_perf_minutes(started) + for epoch in range(state.next_epoch, int(max_epochs) + 1): + elapsed = state.elapsed_offset + _now_perf_minutes(started) remaining = float(budget_minutes) - elapsed - if epochs and remaining <= 0: + if state.epochs and remaining <= 0: stop_reason = "budget_exhausted" break - if epochs and duration_guard_factor > 0: - recent = epochs[-max(1, int(duration_guard_recent)) :] + if state.epochs and duration_guard_factor > 0: + recent = state.epochs[-max(1, int(duration_guard_recent)) :] estimated = max( float(entry.get("epoch_wall_minutes") or 0.0) for entry in recent ) * float(duration_guard_factor) if remaining < estimated: stop_reason = "duration_guard" break - seed_items = [dict(item) for item in adapter.list_seed_items()] + seed_items = [dict(item) for item in cast(SeedAdapter, adapter).list_seed_items()] if not seed_items: stop_reason = "seed_queue_empty" break @@ -815,29 +474,27 @@ def run_budget_arm( # adapter code, so fatal structural validation must see the raw # seeds before either operation can collapse ids or cause effects. build_episode_execution_units( - seed_items, - arm=arm_key, - epoch=epoch, - fatal_preflight=True, + seed_items, arm=arm_key, epoch=epoch, fatal_preflight=True ) - if use_router: - queue_items = plan_router_no_prune( + queue_items = ( + plan_router_no_prune( seed_items, goal_id=goal_id, agent_id=agent_id, worker_count=worker_count, - router_state=router_state, - load_profile=load_profile, + router_state=state.router_state, + load_profile=state.load_profile, ) - else: - queue_items = plan_round_robin(seed_items) - frontier_audit: dict[str, Any] | None = None + if use_router + else plan_round_robin(seed_items) + ) + frontier_audit: dict[str, object] | None = None if use_router and catalog is not None and int(frontier_max_lanes) > 0: variant_items, frontier_audit = select_frontier_work( seed_items, catalog=catalog, adapter=adapter, - router_state=router_state, + router_state=state.router_state, epoch=epoch, max_lanes=frontier_max_lanes, ) @@ -849,36 +506,27 @@ def run_budget_arm( seed_items=seed_items, ledger=ledger, catalog=catalog, - router_state=router_state, + router_state=state.router_state, ) epoch_start = time.perf_counter() - execution_items = queue_items - if episode_mode is not None: - execution_items = build_episode_execution_units( - queue_items, - arm=arm_key, - epoch=epoch, - fatal_preflight=failure_policy == ITEM_FAILURE_POLICY_FATAL, - ) - - def execute_epoch(item: Mapping[str, Any], **context: Any) -> list[dict[str, Any]]: - return execute_episode_group( - item, - adapter=adapter, - failure_policy=failure_policy, - fatal_failure_policy=ITEM_FAILURE_POLICY_FATAL, - error_record_factory=_adapter_error_record, - **context, + execution_items: list[dict[str, object]] = ( + [ + dict(unit) + for unit in build_episode_execution_units( + queue_items, + arm=arm_key, + epoch=epoch, + fatal_preflight=failure_policy == ITEM_FAILURE_POLICY_FATAL, ) - - else: - # Accessed lazily so an episode-only adapter (no legacy execute) - # is valid as long as prepare_episode_group never returns None. - execute_epoch: Callable[..., Any] = adapter.execute - + ] + if episode_mode is not None + else queue_items + ) lanes = run_queue_epoch( execution_items, - execute=execute_epoch, + execute=_epoch_executor( + adapter, episode_mode=episode_mode, failure_policy=failure_policy + ), worker_count=worker_count, run_root=run_root, arm=arm_key, @@ -886,99 +534,22 @@ def execute_epoch(item: Mapping[str, Any], **context: Any) -> list[dict[str, Any stagger_seconds=stagger_seconds, item_failure_policy=failure_policy, ) - epoch_wall = _now_perf_minutes(epoch_start) - epoch_raw = 0.0 - epoch_novel = 0.0 - records: list[dict[str, Any]] = [] - for lane in lanes: - for record in lane.get("results") or []: - credit = ledger.credit(record) - record["novel_value"] = credit["novel_value"] - record["raw_value"] = ledger.raw_value(record) - epoch_raw += record["raw_value"] - epoch_novel += credit["novel_value"] - if record.get("is_variant"): - variant_records_cum += 1 - records.append(record) - raw_cum += epoch_raw - novel_cum += epoch_novel - metric_records = records - if episode_mode is None: - metric_records = [ - { - **record, - "execution_group_id": None, - "record_kind": RECORD_KIND_STANDALONE, - } - for record in records - ] - epoch_execution_metrics = summarize_execution_records(metric_records) - execution_metrics_cum = combine_execution_metrics( - [execution_metrics_cum, epoch_execution_metrics] - ) - elapsed_after = elapsed_offset + _now_perf_minutes(started) - for record in records: - family = str(record.get("family") or "") - if family: - coverage_first_seen.setdefault(family, round(elapsed_after, 3)) - if use_router: - if episode_mode is not None: - probes = build_router_probes(records) - else: - probes = [ - { - "family": str(record.get("family") or "general"), - "duration_minutes": record.get("duration_minutes"), - "observation_keys": record.get("observation_keys") or [], - "weighted_flags": record.get("weighted_flags") or {}, - "accepted": bool(record.get("accepted")), - "retryable_infra_error": bool( - record.get("retryable_infra_error") - ), - } - for record in records - ] - router_state = observe_epoch(router_state, epoch=epoch, probes=probes) - router_state = advance_epoch( - router_state, - epoch=epoch, - eligible_families=sorted( - {str(item.get("family")) for item in seed_items if item.get("family")} - ), - ) - _write_json(run_root / f"router_state_{arm_key}.json", router_state) - max_lane_wall = max( - (float(lane.get("wall_minutes") or 0.0) for lane in lanes), default=0.0 - ) - load_profile = { - "source": f"observed_epoch_{epoch:02d}_{arm_key}", - "parallel_wall_minutes": epoch_wall, - "max_branch_minutes": max_lane_wall, - "branch_count": len(lanes), - } - checkpoints.append( - { - "epoch": epoch, - "elapsed_minutes": round(elapsed_after, 3), - "raw_value_cum": round(raw_cum, 3), - "novel_value_cum": round(novel_cum, 3), - "coverage_count_cum": len(coverage_first_seen), - "variant_records_cum": variant_records_cum, - "requested_worker_minutes_cum": round(elapsed_after * worker_count, 3), - "execution_metrics_cum": dict(execution_metrics_cum), - } - ) - epochs.append( - { - "schema_version": HARNESS_ARM_SCHEMA_VERSION, - "epoch": epoch, - "epoch_wall_minutes": round(epoch_wall, 3), - "queue_size": len(queue_items), - "execution_unit_count": len(execution_items), - "execution_metrics": epoch_execution_metrics, - "frontier": frontier_audit, - "lanes": lanes, - } + _record_epoch_outcomes( + state=state, + lanes=lanes, + seed_items=seed_items, + queue_size=len(queue_items), + execution_unit_count=len(execution_items), + frontier_audit=frontier_audit, + ledger=ledger, + episode_mode=episode_mode, + use_router=use_router, + worker_count=worker_count, + epoch=epoch, + epoch_wall=_now_perf_minutes(epoch_start), + started=started, + run_root=run_root, + arm_key=arm_key, ) if checkpoint_enabled: write_arm_checkpoint( @@ -987,137 +558,51 @@ def execute_epoch(item: Mapping[str, Any], **context: Any) -> list[dict[str, Any arm_key=arm_key, runtime_signature=runtime_signature, next_epoch=epoch + 1, - elapsed_minutes=elapsed_after, - epochs=epochs, - checkpoints=checkpoints, + elapsed_minutes=state.checkpoints[-1]["elapsed_minutes"], + epochs=state.epochs, + checkpoints=state.checkpoints, novelty_seen=sorted(ledger.seen), - router_state=router_state, - load_profile=load_profile, + router_state=state.router_state, + load_profile=state.load_profile, catalog_consumed=sorted(catalog.consumed) if catalog else [], - coverage_first_seen=coverage_first_seen, - raw_value_total=raw_cum, - novel_value_total=novel_cum, - variant_records_total=variant_records_cum, + coverage_first_seen=state.coverage_first_seen, + raw_value_total=state.raw_cum, + novel_value_total=state.novel_cum, + variant_records_total=state.variant_records_cum, ), ) _write_json( run_root / f"rolling_progress_{arm_key}.json", - {"arm": arm_key, "completed_epochs": len(epochs), "last_checkpoint": checkpoints[-1]}, + { + "arm": arm_key, + "completed_epochs": len(state.epochs), + "last_checkpoint": state.checkpoints[-1], + }, ) return { "schema_version": HARNESS_ARM_SCHEMA_VERSION, "arm_key": arm_key, "budget_minutes": float(budget_minutes), - "elapsed_minutes": round(elapsed_offset + _now_perf_minutes(started), 3), + "elapsed_minutes": round(state.elapsed_offset + _now_perf_minutes(started), 3), "stop_reason": stop_reason, - "epoch_count": len(epochs), - "raw_value_total": round(raw_cum, 3), - "novel_value_total": round(novel_cum, 3), - "variant_records_total": variant_records_cum, - "execution_metrics": execution_metrics_cum, - "coverage_count": len(coverage_first_seen), - "coverage_first_seen_minutes": coverage_first_seen, - "checkpoints": checkpoints, - "epochs": epochs, + "epoch_count": len(state.epochs), + "raw_value_total": round(state.raw_cum, 3), + "novel_value_total": round(state.novel_cum, 3), + "variant_records_total": state.variant_records_cum, + "execution_metrics": state.execution_metrics_cum, + "coverage_count": len(state.coverage_first_seen), + "coverage_first_seen_minutes": state.coverage_first_seen, + "checkpoints": state.checkpoints, + "epochs": state.epochs, "resume": { "schema_version": "loopx_explore_harness_resume_v0", "enabled": checkpoint_enabled, "resumed": bool(resume), "checkpoint_schema_version": HARNESS_CHECKPOINT_SCHEMA_VERSION, "checkpoint_path": str(checkpoint_file) if checkpoint_enabled else None, - "restored_epoch_count": next_epoch - 1 if resume else 0, + "restored_epoch_count": state.next_epoch - 1 if resume else 0, }, - "runtime_policy": { - "schema_version": HARNESS_RUNTIME_POLICY_SCHEMA_VERSION, - "item_failure_policy": failure_policy, - "item_exception_isolation": failure_policy == ITEM_FAILURE_POLICY_RECORD, - "episode_execution": { - "mode": episode_mode or "standalone", - "adapter_owned_restore": episode_mode is not None, - }, - "planner_guidance": { - "retry_backoff": { - "enforced": False, - "owner": "external_runner", - }, - "infra_cooldown": { - "enforced": False, - "owner": "external_runner", - }, - }, - }, - } - - -def step_auc(checkpoints: Sequence[Mapping[str, Any]], *, value_key: str, horizon_minutes: float) -> float: - """Step-integrate a cumulative anytime curve to the budget horizon.""" - - auc = 0.0 - prev_t = 0.0 - prev_v = 0.0 - for checkpoint in checkpoints: - t = min(float(checkpoint.get("elapsed_minutes") or 0.0), float(horizon_minutes)) - if t > prev_t: - auc += prev_v * (t - prev_t) - prev_t = t - prev_v = float(checkpoint.get(value_key) or 0.0) - if float(horizon_minutes) > prev_t: - auc += prev_v * (float(horizon_minutes) - prev_t) - return round(auc, 3) - - -def aggregate_arms( - arms: Mapping[str, Mapping[str, Any]], - *, - budget_minutes: float, - worker_count: int, - coverage_denominator: int | None = None, -) -> dict[str, Any]: - """Generic two-arm (or N-arm) comparison on novelty-first metrics.""" - - summary: dict[str, Any] = { - "schema_version": "loopx_explore_harness_score_v0", - "budget_minutes_per_arm": float(budget_minutes), - "worker_count": int(worker_count), - "coverage_denominator": coverage_denominator, - "arms": {}, + "runtime_policy": build_arm_runtime_policy( + failure_policy=failure_policy, episode_mode=episode_mode + ), } - for arm_key, arm in arms.items(): - checkpoints = arm.get("checkpoints") or [] - execution_metrics = ( - dict(arm.get("execution_metrics") or {}) - if isinstance(arm.get("execution_metrics"), Mapping) - else {} - ) - effective_compute = float( - execution_metrics.get("effective_compute_minutes") or 0.0 - ) - summary["arms"][arm_key] = { - "novel_value_endpoint": arm.get("novel_value_total"), - "novel_value_auc": step_auc( - checkpoints, value_key="novel_value_cum", horizon_minutes=budget_minutes - ), - "raw_value_total": arm.get("raw_value_total"), - "coverage_count": arm.get("coverage_count"), - "variant_records_total": arm.get("variant_records_total"), - "epoch_count": arm.get("epoch_count"), - "elapsed_minutes": arm.get("elapsed_minutes"), - "stop_reason": arm.get("stop_reason"), - "execution_metrics": execution_metrics, - "novel_value_per_requested_worker_minute": round( - float(arm.get("novel_value_total") or 0.0) - / max(0.001, float(budget_minutes) * worker_count), - 4, - ), - "novel_value_per_effective_compute_minute": ( - round( - float(arm.get("novel_value_total") or 0.0) - / effective_compute, - 4, - ) - if effective_compute > 0 - else None - ), - "anytime_curve": checkpoints, - } - return summary diff --git a/tests/capabilities/test_explore_harness_runtime_contract.py b/tests/capabilities/test_explore_harness_runtime_contract.py new file mode 100644 index 0000000000..71cd6ad6bf --- /dev/null +++ b/tests/capabilities/test_explore_harness_runtime_contract.py @@ -0,0 +1,564 @@ +from __future__ import annotations + +import ast +from collections.abc import Iterator, Mapping, Sequence +from pathlib import Path +from types import MappingProxyType +from typing import cast +import pytest + +from loopx.capabilities.explore import harness_frontier, harness_queue, harness_runtime +from loopx.capabilities.explore.harness_runtime import ( + DEFAULT_OBSERVATION_WEIGHT, + FRONTIER_REQUESTS_SCHEMA_VERSION, + HARNESS_ARM_SCHEMA_VERSION, + HARNESS_RUNTIME_POLICY_SCHEMA_VERSION, + ITEM_FAILURE_POLICIES, + ITEM_FAILURE_POLICY_FATAL, + ITEM_FAILURE_POLICY_RECORD, + VARIANT_CATALOG_SCHEMA_VERSION, + ItemFailurePolicy, + NoveltyLedger, + SeedAdapter, + VariantCatalog, + _MIN_DURATION_MINUTES, + _adapter_error_record, + _frontier_gain, + _normalize_item_failure_policy, + _now_perf_minutes, + _read_json, + _write_json, + aggregate_arms, + emit_frontier_requests, + plan_round_robin, + plan_router_no_prune, + run_budget_arm, + run_queue_epoch, + select_frontier_work, + step_auc, +) + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _ast_any_nodes(source: str, filename: str) -> list[tuple[int, str]]: + tree = ast.parse(source, filename=filename) + hits: list[tuple[int, str]] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "Any": + hits.append((node.lineno, "Name")) + elif isinstance(node, ast.Attribute) and node.attr == "Any": + hits.append((node.lineno, "Attribute")) + elif isinstance(node, ast.alias) and node.name == "Any": + hits.append((node.lineno, "alias")) + return hits + + +def test_harness_modules_satisfy_zero_any_and_loc_budgets() -> None: + root = _repo_root() + budgets = { + "loopx/capabilities/explore/harness_runtime.py": 650, + "loopx/capabilities/explore/harness_frontier.py": 749, + "loopx/capabilities/explore/harness_queue.py": 749, + "tests/capabilities/test_explore_harness_runtime_contract.py": 599, + } + for rel_path, max_lines in budgets.items(): + source = (root / rel_path).read_text(encoding="utf-8") + lines = source.splitlines() + assert len(lines) <= max_lines, f"{rel_path} exceeded {max_lines} LOC: {len(lines)}" + assert _ast_any_nodes(source, rel_path) == [], f"{rel_path} uses Any" + type_ignore_marker = "type" + ": ignore" + ignores = [ + idx + 1 for idx, line in enumerate(lines) if type_ignore_marker in line + ] + assert ignores == [], f"{rel_path} has type-ignore comments on lines {ignores}" + + +def test_harness_runtime_reexports_all_public_and_shared_helper_symbols() -> None: + expected_public = { + "DEFAULT_OBSERVATION_WEIGHT", + "FRONTIER_REQUESTS_SCHEMA_VERSION", + "HARNESS_ARM_SCHEMA_VERSION", + "HARNESS_RUNTIME_POLICY_SCHEMA_VERSION", + "ITEM_FAILURE_POLICIES", + "ITEM_FAILURE_POLICY_FATAL", + "ITEM_FAILURE_POLICY_RECORD", + "VARIANT_CATALOG_SCHEMA_VERSION", + "HarnessArmResult", + "HarnessArmSummary", + "HarnessCheckpointPoint", + "HarnessEpochRecord", + "HarnessEpisodePolicy", + "HarnessLaneRecord", + "HarnessResumeSummary", + "HarnessRuntimePolicy", + "HarnessScoreSummary", + "ItemFailurePolicy", + "NoveltyLedger", + "SeedAdapter", + "VariantCatalog", + "aggregate_arms", + "emit_frontier_requests", + "plan_round_robin", + "plan_router_no_prune", + "run_budget_arm", + "run_queue_epoch", + "select_frontier_work", + "step_auc", + } + assert set(harness_runtime.__all__) == expected_public + assert DEFAULT_OBSERVATION_WEIGHT == 1.0 + assert HARNESS_ARM_SCHEMA_VERSION == harness_queue.HARNESS_ARM_SCHEMA_VERSION + assert ( + HARNESS_RUNTIME_POLICY_SCHEMA_VERSION + == harness_queue.HARNESS_RUNTIME_POLICY_SCHEMA_VERSION + ) + assert FRONTIER_REQUESTS_SCHEMA_VERSION == harness_frontier.FRONTIER_REQUESTS_SCHEMA_VERSION + assert VARIANT_CATALOG_SCHEMA_VERSION == harness_frontier.VARIANT_CATALOG_SCHEMA_VERSION + assert ITEM_FAILURE_POLICIES == {"record", "fatal"} + assert ITEM_FAILURE_POLICY_FATAL == "fatal" + assert ITEM_FAILURE_POLICY_RECORD == "record" + assert ItemFailurePolicy is harness_queue.ItemFailurePolicy + assert NoveltyLedger is harness_frontier.NoveltyLedger + assert SeedAdapter is harness_queue.SeedAdapter + assert VariantCatalog is harness_frontier.VariantCatalog + assert select_frontier_work is harness_frontier.select_frontier_work + assert emit_frontier_requests is harness_frontier.emit_frontier_requests + assert plan_round_robin is harness_frontier.plan_round_robin + assert plan_router_no_prune is harness_frontier.plan_router_no_prune + assert run_queue_epoch is harness_queue.run_queue_epoch + assert step_auc is harness_queue.step_auc + assert aggregate_arms is harness_queue.aggregate_arms + assert _frontier_gain is harness_frontier._frontier_gain + assert _adapter_error_record is harness_queue._adapter_error_record + assert _normalize_item_failure_policy is harness_queue._normalize_item_failure_policy + assert _now_perf_minutes is harness_queue._now_perf_minutes + assert _read_json is harness_queue._read_json + assert _write_json is harness_queue._write_json + assert _MIN_DURATION_MINUTES == harness_queue._MIN_DURATION_MINUTES + + +def test_empty_container_compatibility_and_fail_closed_type_guards(tmp_path: Path) -> None: + ledger = NoveltyLedger() + # Legacy callers sometimes serialize empty observation_keys as {} or weighted_flags as []. + assert ledger.raw_value({"observation_keys": {}, "weighted_flags": []}) == 0.0 + assert ledger.credit({"family": "alpha", "observation_keys": {}, "weighted_flags": []}) == { + "novel_value": 0.0, + "novel_observation_keys": 0, + } + + with pytest.raises(TypeError, match="observation_keys"): + ledger.raw_value({"observation_keys": "scalar-str"}) + with pytest.raises(TypeError, match="observation_keys"): + ledger.credit({"observation_keys": 42}) + with pytest.raises(TypeError, match="weighted_flags"): + ledger.credit({"weighted_flags": ["flag-a"]}) + + catalog_path = tmp_path / "catalog.json" + consumption_path = tmp_path / "consumption.json" + _write_json(catalog_path, {"specs": {}}) + _write_json(consumption_path, {}) + catalog = VariantCatalog(catalog_path, consumption_path) + assert catalog.pending_count() == 0 + + _write_json(catalog_path, {"specs": "not-a-sequence"}) + with pytest.raises(TypeError, match="specs"): + catalog.pending_count() + + _write_json(consumption_path, "not-a-sequence") + with pytest.raises(TypeError, match="variant_consumption"): + VariantCatalog(catalog_path, consumption_path) + + empty_ckpt_agg = aggregate_arms( + {"arm-a": {"checkpoints": {}, "novel_value_total": 3.0, "execution_metrics": {}}}, + budget_minutes=5.0, + worker_count=1, + ) + assert empty_ckpt_agg["arms"]["arm-a"]["novel_value_auc"] == 0.0 + assert ( + empty_ckpt_agg["arms"]["arm-a"]["novel_value_per_effective_compute_minute"] is None + ) + + with pytest.raises(TypeError, match="checkpoints"): + aggregate_arms( + {"arm-a": {"checkpoints": "not-a-list"}}, + budget_minutes=5.0, + worker_count=1, + ) + + +def test_mapping_proxy_key_presence_and_zero_float_frontier_gain() -> None: + seed_item = MappingProxyType({"item_id": "seed-1", "family": "alpha", "text": "check alpha"}) + router_state = MappingProxyType( + { + "families": MappingProxyType( + { + "scope:artifacts/alpha": MappingProxyType( + { + "runs": 2, + "novelty_rate": 0.0, + "accept_rate_ema": 0.0, + } + ) + } + ) + } + ) + router_state_none_accept = MappingProxyType( + { + "families": MappingProxyType( + { + "scope:artifacts/alpha": MappingProxyType( + { + "runs": 2, + "novelty_rate": 0.0, + "accept_rate_ema": None, + } + ) + } + ) + } + ) + # accept_rate_ema=0.0 qualifies for the <=0.5 bonus (+0.25), unlike None. + assert _frontier_gain(router_state, "alpha", epoch=5) == pytest.approx(1.37) + assert _frontier_gain(router_state_none_accept, "alpha", epoch=5) == pytest.approx(1.12) + + ledger = NoveltyLedger() + credit = ledger.credit( + MappingProxyType( + { + "family": "alpha", + "observation_keys": ("k1", "k2"), + "weighted_flags": MappingProxyType({"passed": 2.5}), + } + ) + ) + assert credit == {"novel_value": 4.5, "novel_observation_keys": 2} + + planned = plan_router_no_prune( + [seed_item], + goal_id="g1", + agent_id="a1", + worker_count=1, + router_state=router_state, + load_profile=MappingProxyType({"source": "ro", "branch_count": 1}), + ) + assert [item["item_id"] for item in planned] == ["seed-1"] + + err_record = _adapter_error_record( + MappingProxyType({"item_id": None, "family": "alpha", "is_variant": True}), + RuntimeError("boom"), + duration_minutes=0.01, + ) + assert "item_id" in err_record and err_record["item_id"] is None + assert err_record["is_variant"] is True + assert err_record["duration_minutes"] == _MIN_DURATION_MINUTES + assert err_record["execution_status"] == "adapter_error" + + class _DummyAdapter: + pass + + sig = harness_queue.arm_runtime_signature( + _DummyAdapter(), + arm_key="k", + worker_count=2, + use_router=True, + frontier_max_lanes=1, + variant_catalog_enabled=False, + goal_id="g", + agent_id="a", + item_failure_policy="record", + episode_mode=None, + ) + assert "episode_mode" in sig and sig["episode_mode"] is None + + +def test_select_and_emit_frontier_avoid_redundant_catalog_reads_and_gain_calls( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + families = [f"fam-{idx}" for idx in range(6)] + catalog_path = tmp_path / "variant_catalog.json" + specs: list[dict[str, object]] = [] + for fam in families: + specs.append( + { + "spec_id": f"{fam}-low", + "seed_family": fam, + "intent": "low", + "priority": 1.0, + } + ) + specs.append( + { + "spec_id": f"{fam}-high", + "seed_family": fam, + "intent": "high", + "priority": 5.0, + } + ) + _write_json( + catalog_path, + {"schema_version": VARIANT_CATALOG_SCHEMA_VERSION, "specs": specs}, + ) + + class MultiFamilyAdapter: + def list_seed_items(self) -> list[dict[str, object]]: + return [ + { + "item_id": f"seed-{fam}", + "family": fam, + "text": f"explore {fam}", + "concurrency_key": fam, + } + for fam in families + ] + + def compile_variant( + self, spec: Mapping[str, object], seed_item: Mapping[str, object] + ) -> dict[str, object]: + return { + "item_id": f"var-{spec['spec_id']}", + "family": seed_item["family"], + } + + def execute( + self, item: Mapping[str, object], **_: object + ) -> dict[str, object]: + return { + "item_id": item["item_id"], + "family": item["family"], + "observation_keys": [f"obs:{item['item_id']}"], + "weighted_flags": {"pass": 1.0} if item.get("is_variant") else {}, + "accepted": True, + "duration_minutes": 0.1, + } + + catalog_reads = 0 + real_read_json = _read_json + + def counting_read_json(path: Path) -> object: + nonlocal catalog_reads + if path == catalog_path: + catalog_reads += 1 + return real_read_json(path) + + gain_calls = 0 + real_frontier_gain = harness_frontier._frontier_gain + + def counting_frontier_gain( + router_state: Mapping[str, object] | None, + family: str, + *, + epoch: int, + ) -> float: + nonlocal gain_calls + gain_calls += 1 + return real_frontier_gain(router_state, family, epoch=epoch) + + monkeypatch.setattr(harness_frontier, "_read_json", counting_read_json) + monkeypatch.setattr(harness_frontier, "_frontier_gain", counting_frontier_gain) + + result = run_budget_arm( + MultiFamilyAdapter(), + arm_key="frontier-io", + run_root=tmp_path, + budget_minutes=10.0, + worker_count=2, + max_epochs=1, + use_router=True, + frontier_max_lanes=3, + variant_catalog_path=catalog_path, + duration_guard_factor=0.0, + ) + assert result["epoch_count"] == 1 + assert result["variant_records_total"] == 3 + # One catalog read in select_frontier_work + one in emit_frontier_requests (previously 2*6+2 = 14). + assert catalog_reads == 2 + # Computed once per family in select_frontier_work (6) + once per family in emit_frontier_requests (6). + assert gain_calls == 12 + admitted = result["epochs"][0]["frontier"] + assert admitted is not None + assert admitted["catalog_pending_after"] == len(specs) - 3 + + +def test_select_frontier_work_persists_partial_consumption_and_supports_mock_catalog( + tmp_path: Path, +) -> None: + catalog_path = tmp_path / "catalog.json" + consumption_path = tmp_path / "consumption.json" + _write_json( + catalog_path, + { + "schema_version": VARIANT_CATALOG_SCHEMA_VERSION, + "specs": [ + {"spec_id": "s1", "seed_family": "alpha", "intent": "first", "priority": 2}, + {"spec_id": "s2", "seed_family": "beta", "intent": "second", "priority": 1}, + ], + }, + ) + catalog = VariantCatalog(catalog_path, consumption_path) + seeds = [ + {"item_id": "seed-a", "family": "alpha", "text": "a"}, + {"item_id": "seed-b", "family": "beta", "text": "b"}, + ] + + class ExplodingSecondVariantAdapter: + def __init__(self) -> None: + self.calls = 0 + + def compile_variant( + self, spec: Mapping[str, object], seed_item: Mapping[str, object] + ) -> dict[str, object]: + self.calls += 1 + if self.calls == 2: + raise RuntimeError("compile crashed on second spec") + return {"item_id": f"v-{spec['spec_id']}", "family": seed_item["family"]} + + with pytest.raises(RuntimeError, match="compile crashed on second spec"): + select_frontier_work( + seeds, + catalog=catalog, + adapter=ExplodingSecondVariantAdapter(), + router_state=None, + epoch=1, + max_lanes=2, + ) + persisted = _read_json(consumption_path) + assert isinstance(persisted, list) and len(persisted) == 1 + + # Mock VariantCatalog without pending_snapshot must still work via fallback path. + class LegacyMockCatalog: + def __init__(self) -> None: + self.consumed: set[str] = set() + self.pending_calls: list[str] = [] + + def pending_for(self, family: str) -> list[dict[str, object]]: + self.pending_calls.append(family) + if family == "alpha" and "legacy-1" not in self.consumed: + return [{"spec_id": "legacy-1", "seed_family": "alpha", "intent": "ok"}] + return [] + + def pending_count(self) -> int: + return 0 if "legacy-1" in self.consumed else 1 + + def consume(self, spec_id: str) -> None: + self.consumed.add(spec_id) + + mock_catalog = LegacyMockCatalog() + + class MockAdapter: + def compile_variant( + self, spec: Mapping[str, object], seed_item: Mapping[str, object] + ) -> dict[str, object]: + return {"item_id": f"v-{spec['spec_id']}", "family": seed_item["family"]} + + mock_catalog_typed = cast(VariantCatalog, mock_catalog) + selected, audit = select_frontier_work( + seeds, + catalog=mock_catalog_typed, + adapter=MockAdapter(), + router_state=None, + epoch=1, + max_lanes=1, + ) + assert [item["item_id"] for item in selected] == ["v-legacy-1"] + assert audit["catalog_pending_after"] == 0 + assert set(mock_catalog.pending_calls) == {"alpha", "beta"} + + emit_frontier_requests( + tmp_path / "frontier_requests.json", + arm_key="mock", + epoch=1, + seed_items=seeds, + ledger=NoveltyLedger(), + catalog=mock_catalog_typed, + router_state=None, + ) + req_payload = _read_json(tmp_path / "frontier_requests.json") + assert isinstance(req_payload, dict) + assert req_payload["catalog_pending_total"] == 0 + + +def test_step_auc_and_fatal_policy_contracts(tmp_path: Path) -> None: + auc = step_auc( + [ + {"elapsed_minutes": 1.0, "novel_value_cum": 2.0}, + {"elapsed_minutes": 3.0, "novel_value_cum": 5.0}, + ], + value_key="novel_value_cum", + horizon_minutes=4.0, + ) + # 0..1 -> 0*1; 1..3 -> 2*2=4; 3..4 -> 5*1=5 => 9.0 + assert auc == 9.0 + + with pytest.raises(ValueError, match="item_failure_policy must be one of"): + _normalize_item_failure_policy("ignore") + + class MissingExecuteAdapter: + def list_seed_items(self) -> Sequence[Mapping[str, object]]: + return [{"item_id": "seed-1", "family": "alpha"}] + + with pytest.raises(AttributeError, match="execute"): + run_budget_arm( + MissingExecuteAdapter(), + arm_key="missing-exec", + run_root=tmp_path, + budget_minutes=1.0, + worker_count=1, + max_epochs=1, + item_failure_policy=ITEM_FAILURE_POLICY_FATAL, + ) + + class TupleBatchAdapter: + def list_seed_items(self) -> list[dict[str, object]]: + return [{"item_id": "s1", "family": "alpha"}] + + def execute( + self, item: Mapping[str, object], **_: object + ) -> tuple[dict[str, object], ...]: + return ( + { + "item_id": item["item_id"], + "family": item["family"], + "observation_keys": ["k1"], + "weighted_flags": {}, + "accepted": True, + "duration_minutes": 0.2, + }, + ) + + batch_res = run_budget_arm( + TupleBatchAdapter(), + arm_key="seq-arm", + run_root=tmp_path, + budget_minutes=1.0, + worker_count=1, + max_epochs=1, + ) + assert batch_res["novel_value_total"] == 1.0 + + class GeneratorOutcomeAdapter: + def list_seed_items(self) -> list[dict[str, object]]: + return [{"item_id": "gen-1", "family": "alpha"}] + + def execute( + self, item: Mapping[str, object], **_: object + ) -> Iterator[dict[str, object]]: + yield {"item_id": item["item_id"], "family": item["family"]} + + gen_res = run_budget_arm( + GeneratorOutcomeAdapter(), + arm_key="gen-arm", + run_root=tmp_path, + budget_minutes=1.0, + worker_count=1, + max_epochs=1, + ) + assert gen_res["novel_value_total"] == 0.0 + gen_rec = gen_res["epochs"][0]["lanes"][0]["results"][0] + assert gen_rec["execution_status"] == "adapter_error" + assert isinstance(gen_rec["adapter_error"], dict) + assert gen_rec["adapter_error"]["type"] == "TypeError" + assert plan_round_robin([MappingProxyType({"item_id": "x"})]) == [{"item_id": "x"}] From 37cc6da78f6347161ec6a4552b943b5f78f31301 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:08:54 +0800 Subject: [PATCH 2/3] fix(explore): filter consumed spec_ids inside frontier snapshot selection Filter VariantCatalog snapshot rows by the running consumed spec_id set inside select_frontier_work and recount remaining unconsumed snapshot rows for catalog_pending_after while preserving single-read catalog I/O. Adds an arm-level cross-family duplicate spec_id regression test. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../capabilities/explore/harness_frontier.py | 88 +++++++++++++----- .../test_explore_harness_runtime_contract.py | 91 ++++++++++++++++++- 2 files changed, 154 insertions(+), 25 deletions(-) diff --git a/loopx/capabilities/explore/harness_frontier.py b/loopx/capabilities/explore/harness_frontier.py index 390ea36f82..ac71896e86 100644 --- a/loopx/capabilities/explore/harness_frontier.py +++ b/loopx/capabilities/explore/harness_frontier.py @@ -138,17 +138,20 @@ def _specs(self) -> list[dict[str, object]]: if isinstance(spec, Mapping) and spec.get("spec_id") ] + def pending_rows_snapshot(self) -> list[dict[str, object]]: + """Read ``catalog_path`` once and return all unconsumed specs.""" + + return [ + spec + for spec in self._specs() + if str(spec.get("spec_id")) not in self.consumed + ] + def pending_snapshot(self) -> tuple[dict[str, list[dict[str, object]]], int]: """Read ``catalog_path`` once and index pending specs by ``seed_family``.""" - by_family: dict[str, list[dict[str, object]]] = {} - total_pending = 0 - for spec in self._specs(): - if str(spec.get("spec_id")) in self.consumed: - continue - total_pending += 1 - by_family.setdefault(str(spec.get("seed_family") or ""), []).append(spec) - return by_family, total_pending + rows = self.pending_rows_snapshot() + return _index_specs_by_family(rows), len(rows) def pending_for(self, family: str) -> list[dict[str, object]]: return [ @@ -159,9 +162,7 @@ def pending_for(self, family: str) -> list[dict[str, object]]: ] def pending_count(self) -> int: - return len( - [s for s in self._specs() if str(s.get("spec_id")) not in self.consumed] - ) + return len(self.pending_rows_snapshot()) def consume(self, spec_id: str) -> None: self.consumed.add(str(spec_id)) @@ -172,21 +173,42 @@ def restore_consumed(self, spec_ids: Sequence[object]) -> None: _write_json(self.consumption_path, sorted(self.consumed)) +def _index_specs_by_family( + specs: Sequence[dict[str, object]], +) -> dict[str, list[dict[str, object]]]: + by_family: dict[str, list[dict[str, object]]] = {} + for spec in specs: + by_family.setdefault(str(spec.get("seed_family") or ""), []).append(spec) + return by_family + + +def _consumed_spec_ids(catalog: object) -> set[str]: + raw = getattr(catalog, "consumed", ()) + if isinstance(raw, (set, frozenset, list, tuple)): + return {str(spec_id) for spec_id in raw} + return set() + + def _catalog_pending_index( catalog: VariantCatalog, families: Sequence[str], -) -> tuple[dict[str, list[dict[str, object]]], int]: - """Use single-read ``pending_snapshot`` when available; fall back for mocks.""" +) -> tuple[dict[str, list[dict[str, object]]], list[dict[str, object]] | None, int]: + """Read catalog state once when snapshot helpers exist; fall back for mocks.""" + rows_fn = getattr(catalog, "pending_rows_snapshot", None) + if callable(rows_fn): + rows = cast(Callable[[], list[dict[str, object]]], rows_fn)() + return _index_specs_by_family(rows), rows, len(rows) snapshot_fn = getattr(catalog, "pending_snapshot", None) if callable(snapshot_fn): typed_snapshot = cast( Callable[[], tuple[dict[str, list[dict[str, object]]], int]], snapshot_fn, ) - return typed_snapshot() + by_family, total_pending = typed_snapshot() + return by_family, None, total_pending by_family = {family: catalog.pending_for(family) for family in families} - return by_family, catalog.pending_count() + return by_family, None, catalog.pending_count() def select_frontier_work( @@ -228,9 +250,11 @@ def _hash(value: str) -> int: pair[0], ), ) - pending_by_family, catalog_pending_total = _catalog_pending_index( + pending_by_family, snapshot_rows, catalog_pending_total = _catalog_pending_index( catalog, [family for family, _ in ranked] ) + consumed_ids = _consumed_spec_ids(catalog) + newly_consumed: set[str] = set() selected: list[dict[str, object]] = [] audit_specs: list[dict[str, object]] = [] compile_variant_raw = getattr(adapter, "compile_variant", None) @@ -238,7 +262,11 @@ def _hash(value: str) -> int: if len(selected) >= max(0, int(max_lanes)): break pending = sorted( - pending_by_family.get(family, ()), + ( + spec + for spec in pending_by_family.get(family, ()) + if str(spec.get("spec_id")) not in consumed_ids + ), key=lambda spec: ( -_as_float(spec.get("priority") or 0.0), str(spec.get("spec_id")), @@ -263,7 +291,10 @@ def _hash(value: str) -> int: compiled.setdefault( "concurrency_key", f"{family}:variant:{spec.get('spec_id')}" ) - catalog.consume(str(spec.get("spec_id"))) + spec_id = str(spec.get("spec_id")) + catalog.consume(spec_id) + consumed_ids.add(spec_id) + newly_consumed.add(spec_id) selected.append(compiled) audit_specs.append( { @@ -273,11 +304,20 @@ def _hash(value: str) -> int: "gain": gain_by_family[family], } ) - pending_after = ( - max(0, catalog_pending_total - len(selected)) - if callable(getattr(catalog, "pending_snapshot", None)) - else catalog.pending_count() - ) + if snapshot_rows is not None: + pending_after = sum( + 1 for row in snapshot_rows if str(row.get("spec_id")) not in consumed_ids + ) + elif callable(getattr(catalog, "pending_snapshot", None)): + dropped_rows = sum( + 1 + for fam_specs in pending_by_family.values() + for row in fam_specs + if str(row.get("spec_id")) in newly_consumed + ) + pending_after = max(0, catalog_pending_total - dropped_rows) + else: + pending_after = catalog.pending_count() audit: dict[str, object] = { "requested_lanes": int(max_lanes), "admitted": len(selected), @@ -312,7 +352,7 @@ def emit_frontier_requests( family = str(item.get("family") or "") if family and family not in first_seed_by_family: first_seed_by_family[family] = item - pending_by_family, catalog_pending_total = _catalog_pending_index( + pending_by_family, _, catalog_pending_total = _catalog_pending_index( catalog, list(first_seed_by_family) ) families: list[dict[str, object]] = [] diff --git a/tests/capabilities/test_explore_harness_runtime_contract.py b/tests/capabilities/test_explore_harness_runtime_contract.py index 71cd6ad6bf..7fe03545ba 100644 --- a/tests/capabilities/test_explore_harness_runtime_contract.py +++ b/tests/capabilities/test_explore_harness_runtime_contract.py @@ -62,7 +62,7 @@ def test_harness_modules_satisfy_zero_any_and_loc_budgets() -> None: "loopx/capabilities/explore/harness_runtime.py": 650, "loopx/capabilities/explore/harness_frontier.py": 749, "loopx/capabilities/explore/harness_queue.py": 749, - "tests/capabilities/test_explore_harness_runtime_contract.py": 599, + "tests/capabilities/test_explore_harness_runtime_contract.py": 749, } for rel_path, max_lines in budgets.items(): source = (root / rel_path).read_text(encoding="utf-8") @@ -562,3 +562,92 @@ def execute( assert isinstance(gen_rec["adapter_error"], dict) assert gen_rec["adapter_error"]["type"] == "TypeError" assert plan_round_robin([MappingProxyType({"item_id": "x"})]) == [{"item_id": "x"}] + + +def test_cross_family_duplicate_spec_id_executes_once_and_counts_exact_remaining( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + catalog_path = tmp_path / "variant_catalog.json" + _write_json( + catalog_path, + { + "schema_version": VARIANT_CATALOG_SCHEMA_VERSION, + "specs": [ + {"spec_id": "dup-1", "seed_family": "beta", "intent": "b", "priority": 3}, + {"spec_id": "dup-1", "seed_family": "alpha", "intent": "a", "priority": 3}, + {"spec_id": "dup-1", "seed_family": "unseeded", "intent": "u", "priority": 1}, + {"spec_id": "uniq-2", "seed_family": "gamma", "intent": "g", "priority": 1}, + ], + }, + ) + + class CrossFamilyDupAdapter: + def list_seed_items(self) -> list[dict[str, object]]: + return [ + {"item_id": "seed-beta", "family": "beta", "text": "b", "concurrency_key": "beta"}, + {"item_id": "seed-alpha", "family": "alpha", "text": "a", "concurrency_key": "alpha"}, + {"item_id": "seed-gamma", "family": "gamma", "text": "g", "concurrency_key": "gamma"}, + ] + + def compile_variant( + self, spec: Mapping[str, object], seed_item: Mapping[str, object] + ) -> dict[str, object]: + return { + "item_id": f"v-{spec['spec_id']}-{seed_item['family']}", + "family": seed_item["family"], + } + + def execute( + self, item: Mapping[str, object], **_: object + ) -> dict[str, object]: + return { + "item_id": item["item_id"], + "family": item["family"], + "observation_keys": [f"obs:{item['item_id']}"], + "weighted_flags": {}, + "accepted": True, + "duration_minutes": 0.1, + } + + catalog_reads = 0 + real_read_json = _read_json + + def counting_read_json(path: Path) -> object: + nonlocal catalog_reads + if path == catalog_path: + catalog_reads += 1 + return real_read_json(path) + + monkeypatch.setattr(harness_frontier, "_read_json", counting_read_json) + + res = run_budget_arm( + CrossFamilyDupAdapter(), + arm_key="dup-arm", + run_root=tmp_path, + budget_minutes=10.0, + worker_count=2, + max_epochs=1, + use_router=True, + frontier_max_lanes=2, + variant_catalog_path=catalog_path, + duration_guard_factor=0.0, + ) + assert catalog_reads == 2 + assert res["variant_records_total"] == 2 + frontier = res["epochs"][0]["frontier"] + assert frontier is not None + assert frontier["admitted"] == 2 + assert frontier["catalog_pending_after"] == 0 + admitted_specs = frontier["specs"] + assert isinstance(admitted_specs, list) + assert sorted(str(row["spec_id"]) for row in admitted_specs) == ["dup-1", "uniq-2"] + assert _read_json(tmp_path / "variant_consumption_dup-arm.json") == ["dup-1", "uniq-2"] + variant_ids = [ + rec["item_id"] + for lane in res["epochs"][0]["lanes"] + for rec in lane["results"] + if rec.get("is_variant") + ] + assert len(variant_ids) == 2 + assert "v-uniq-2-gamma" in variant_ids + assert sum(1 for vid in variant_ids if str(vid).startswith("v-dup-1-")) == 1 From 8545135c24008da3ea9ffc8d967298eb57ee9ae2 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:31:37 +0800 Subject: [PATCH 3/3] fix(explore): persist unrounded elapsed minutes in arm checkpoints Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/explore/harness_runtime.py | 7 +- .../test_explore_harness_runtime_contract.py | 68 +++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/loopx/capabilities/explore/harness_runtime.py b/loopx/capabilities/explore/harness_runtime.py index 48a1a503b1..ea2c4e5e3d 100644 --- a/loopx/capabilities/explore/harness_runtime.py +++ b/loopx/capabilities/explore/harness_runtime.py @@ -299,7 +299,7 @@ def _record_epoch_outcomes( started: float, run_root: Path, arm_key: str, -) -> None: +) -> float: epoch_raw = 0.0 epoch_novel = 0.0 records: list[dict[str, object]] = [] @@ -372,6 +372,7 @@ def _record_epoch_outcomes( "lanes": lanes, } ) + return elapsed_after def run_budget_arm( @@ -534,7 +535,7 @@ def run_budget_arm( stagger_seconds=stagger_seconds, item_failure_policy=failure_policy, ) - _record_epoch_outcomes( + elapsed_after = _record_epoch_outcomes( state=state, lanes=lanes, seed_items=seed_items, @@ -558,7 +559,7 @@ def run_budget_arm( arm_key=arm_key, runtime_signature=runtime_signature, next_epoch=epoch + 1, - elapsed_minutes=state.checkpoints[-1]["elapsed_minutes"], + elapsed_minutes=elapsed_after, epochs=state.epochs, checkpoints=state.checkpoints, novelty_seen=sorted(ledger.seen), diff --git a/tests/capabilities/test_explore_harness_runtime_contract.py b/tests/capabilities/test_explore_harness_runtime_contract.py index 7fe03545ba..5db0fa1a15 100644 --- a/tests/capabilities/test_explore_harness_runtime_contract.py +++ b/tests/capabilities/test_explore_harness_runtime_contract.py @@ -651,3 +651,71 @@ def counting_read_json(path: Path) -> object: assert len(variant_ids) == 2 assert "v-uniq-2-gamma" in variant_ids assert sum(1 for vid in variant_ids if str(vid).startswith("v-dup-1-")) == 1 + + +@pytest.mark.parametrize( + ("first_min", "resume_min", "budget_min", "curve_min", "expect_stop", "expect_epochs"), + [ + (0.0004, 0.0004, 0.0007, 0.0, "budget_exhausted", 1), + (0.0006, 0.0001, 0.001, 0.001, "max_epochs", 2), + ], +) +def test_checkpoint_resume_preserves_unrounded_elapsed_minutes( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + first_min: float, + resume_min: float, + budget_min: float, + curve_min: float, + expect_stop: str, + expect_epochs: int, +) -> None: + ran_epoch = False + pre_resume = 0.0 + epoch_min = first_min + + class TinySeedAdapter: + def list_seed_items(self) -> list[dict[str, object]]: + return [{"item_id": "s1", "family": "fam", "text": "x", "concurrency_key": "k"}] + + def execute(self, item: Mapping[str, object], **_: object) -> dict[str, object]: + nonlocal ran_epoch + ran_epoch = True + return {"item_id": item["item_id"], "family": "fam", "observation_keys": ["o1"], "weighted_flags": {}, "accepted": True, "duration_minutes": 0.0} + + def fake_perf_minutes(_start: float) -> float: + return pre_resume + (epoch_min if ran_epoch else 0.0) + + monkeypatch.setattr(harness_runtime, "_now_perf_minutes", fake_perf_minutes) + run1 = run_budget_arm( + TinySeedAdapter(), + arm_key="clk", + run_root=tmp_path, + budget_minutes=budget_min, + worker_count=1, + max_epochs=1, + use_router=False, + resumable=True, + duration_guard_factor=0.0, + ) + assert run1["checkpoints"][0]["elapsed_minutes"] == curve_min + saved = _read_json(tmp_path / "arm_checkpoint_clk.json") + assert isinstance(saved, dict) and isinstance(saved["state"], dict) + assert saved["state"]["elapsed_minutes"] == pytest.approx(first_min, abs=1e-9) + + ran_epoch = False + pre_resume = resume_min + epoch_min = 0.0 + run2 = run_budget_arm( + TinySeedAdapter(), + arm_key="clk", + run_root=tmp_path, + budget_minutes=budget_min, + worker_count=1, + max_epochs=2, + use_router=False, + resume=True, + duration_guard_factor=0.0, + ) + assert run2["stop_reason"] == expect_stop + assert run2["epoch_count"] == expect_epochs