diff --git a/CHANGELOG.md b/CHANGELOG.md index 73a81137c..9ed27046a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,26 @@ ### Changed +- Import `run_session` and its operation-specific requests from `inferrsi.harness.manager`. + The former `inferrsi.harness.optimization_session.session_command` accepted parsed CLI + arguments. Python hosts now pass a request such as `StartProjectSession`, + `EvaluateSessionRound` or `SessionStatus` and supply the same ports as Apps. + For a retained plan, rounds and final assessment, use `manager.read_session_records` + in place of `inferrsi.harness.optimization.read_records`. + +- Import parallel round scheduling from `inferrsi.harness.manager`. The former + `inferrsi.harness.parallel_round` operations `prepare`, `submit`, `ticket_status`, + `serve_ticket` and `close_round` map to `prepare_parallel_round`, + `submit_parallel_ticket`, `parallel_ticket_status`, `serve_parallel_ticket` and + `close_parallel_round`. The command-line subcommands and persisted tickets keep their + existing names. + +- For native agent sessions, import `prepare_agent_session`, `bind_agent_session`, + `dispatch_agent_session`, `record_agent_session`, `agent_session_status` and + `AGENT_TERMINAL_STATES` from `inferrsi.harness.manager`. They replace `prepare`, + `bind`, `dispatch`, `record`, `status` and `TERMINAL` in `inferrsi.harness.agent_sessions`. +- Import `session_runtime_identity` from `inferrsi.harness.manager` to read the installed + source fingerprint used by ordinary sessions and benchmark comparisons. - For ordinary projects, import `prepare_project` and `execute_ordinary` from `inferrsi.harness.executor`. The former `inferrsi.harness.project` operations `prepare`, `steps`, `inspect_step` and `assess` are now `executor.prepare_project`, diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 773b5a209..f195dc525 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -228,7 +228,6 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/views/capture_delivery.py", "src/inferrsi/apps/views/optimization_story.py", - "src/inferrsi/harness/optimization_session.py", "tests/repository/check_installed.py", "tests/fixtures/dashboard_profile_review.py", "tests/fixtures/knowledge_retrieval.py", diff --git a/docs/architecture.md b/docs/architecture.md index 14b608986..13b50e323 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -11,12 +11,12 @@ and `apps/workflows/benchmark_operations.py` provide application assembly and la Each task retains its own protocol and task-specific code. The [current-Agent optimization session](benchmarks/optimization-benchmarks.md) assembles -the first complete handoff for the Qwen task. `harness/optimization.py` controls +the first complete handoff for the Qwen task. `harness/manager/_state.py` controls budget, attempts, feedback records, selection and independent final execution. Harness Executor freezes a supplied resource directory with `prepare_task_protocol` and starts its task-owned protocol in an isolated child with `run_task_protocol`. The CLI resolves task resources and supplies the task assessor, knowledge access and -capture callback to `harness/optimization_session.py`. +capture callback to `harness/manager/_session.py`. The external Agent chooses and edits candidates between round submissions. The same controller serves ordinary projects through `campaign start/round/final` and packaged tasks through `benchmarks session`. The diff --git a/docs/contracts/function-owners.md b/docs/contracts/function-owners.md index 1d0452a62..6e25e2e67 100644 --- a/docs/contracts/function-owners.md +++ b/docs/contracts/function-owners.md @@ -33,5 +33,5 @@ Any later split of a mixed function is accepted by real pytest/host/wheel/record The skill-evaluation split (#410) implements the `skill_evaluation`, `skill_eval_diagnostic`, `skill_eval_engineering` and `improvement` rows. H keeps `harness/executor/skill_evaluation.py`, `harness/executor/artifact_sandbox.py` and `harness/manager/search/improvement.py`; B holds `benchmark/skill_evaluation.py`, `benchmark/skill_eval_diagnostic.py`, `benchmark/skill_eval_engineering.py` and `benchmark/improvement.py`; Apps composes them in `apps/workflows/skill_evaluation.py`, `apps/workflows/skill_eval_engineering.py` and `apps/workflows/improvement.py`. Two points follow the tree as it stands after #338, not the row text: -- `usage_totals` stays in `harness/records/usage.py`, because `harness/optimization.py` consumes it for budget accounting. B `assessment` receives the baseline and candidate totals from Apps and does not import H. +- `usage_totals` stays in `harness/records/usage.py`, because `harness/manager/_state.py` consumes it for budget accounting. B `assessment` receives the baseline and candidate totals from Apps and does not import H. - `SelectionPolicy` holds only the two thresholds, so it lives whole in B. H `choose` receives the assessments, the validity block and the composition flag; it holds no threshold and no policy class. diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 00cb44d24..850341470 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -32,7 +32,7 @@ CLI `final` 返回后自动生成 `delivery//report.md`、离线 `rep ## 时序图 -以下是普通项目默认 AB/BA 模式的完整流程。CLI 接入既有入口,调用 Harness 的 `optimization_session.session_command()`。初始化、执行、判定和结算均在 Harness 内;CLI 注入 KnowledgeReader 和已有知识记录回调。知识记录回调在 `apps/workflows/campaign.py`,展示在 `apps/views`,记录由 `harness/records` 写入;Harness 仍负责优化状态与预算。 +以下是普通项目默认 AB/BA 模式的完整流程。CLI 将参数转为会话请求,调用 `inferrsi.harness.manager.run_session`。Manager 负责初始化、预算和结算,Executor 执行,Evaluator 判定。CLI 注入 KnowledgeReader 和 `apps/workflows/campaign.py` 的知识捕获回调。`apps/views` 展示结果,`harness/records` 保存记录。 先准备任务条件,再调用 start。start 内复制任务、脚本和基线并写入计划/状态,不执行测量。Agent 逐次调用 round,最后调用 final 独立重测已保存的最佳版本。 @@ -49,7 +49,7 @@ sequenceDiagram A->>A: 先读 RSI 入口,准备任务说明、输入、质量/性能脚本、指标和门槛 Note over A,H: 第一阶段:start 内保存任务与基线,初始化本次运行;此时不测量性能 A->>C: campaign start:提交文件、条件、源码范围、预算和停止规则 - C->>H: session_command:提交解析后的启动参数 + C->>H: run_session(StartProjectSession) H->>H: 检查新目录、项目范围及参数;project.prepare 保存 TASK.md、protocol 和文件哈希 H->>H: candidates.retain:保存 frozen/baseline/ 和源码身份 H->>H: initialize:建立计划、期限、空轮次和初始最佳候选 @@ -63,7 +63,7 @@ sequenceDiagram A->>C: campaign diagnose:记录瓶颈及其测量依据 opt 需要资料且知识开关允许 A->>C: campaign knowledge:提交查询、检索方式和上下文预算 - C->>H: session_command:传入查询、KnowledgeReader 和记录回调 + C->>H: run_session(QuerySessionKnowledge),注入 reader 和捕获回调 H->>H: 检查运行状态、预算和知识开关 H->>O: 调用注入的 capture_context,传入 reader 和查询 O->>K: reader.collect 检索 @@ -79,7 +79,7 @@ sequenceDiagram A->>C: campaign final:提交停止原因和可用用量 Note over A,H: final 使用留存的最佳版本;工作区未提交修改不参与 end - C->>H: session_command:提交 round/final 参数 + C->>H: run_session(EvaluateSessionRound 或 FinalizeSession) H->>H: evaluate_round:绑定 Executor 执行和 Evaluator 判定 H->>H: 核验文件、状态和预算,选择提交候选或留存最佳版本 H->>H: 保存到 rounds/… 或 final/…;state.pending 记录本次待完成尝试 @@ -104,7 +104,7 @@ sequenceDiagram Note over A,H: 第三阶段:读取实际完成的记录,展示并交付 A->>C: dashboard:读取实验目录 C->>O: Dashboard 读取实验目录 - O->>H: read_records:核验并读取同一套计划、轮次和 final + O->>H: read_session_records,核验并读取同一套计划、轮次和 final H-->>O: 返回验证后的记录与摘要 O-->>C: 页面/离线 HTML,含优化曲线、已观测用量与 final 结果 C-->>A: 返回展示产物;缺失数据保持未知 @@ -150,7 +150,7 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 | 一次测量 | 原有 `run` 或 `benchmarks run` | 保留独立使用方式;不会自动生成多轮候选 | | 旧式手动 campaign | 原有 `campaign init/record/decide` | 兼容已有记录;不允许写进新控制器管理的 campaign 形成第二套状态 | -两个优化入口都调用 `harness.optimization_session.session_command`,使用同一个 `harness.optimization` 控制器。AB/BA 与题包使用 `evaluate_round`;显式 service_reuse 使用该控制器内的 `service_command` 和模式分支,共用锁及单一控制记录。执行与评测适配也在 Harness 内;普通项目整个生命周期不导入 Benchmark。 +两个优化入口和直接调用的 Python 程序都向 `inferrsi.harness.manager.run_session` 提交同一组请求。Manager 在会话锁内登记轮次、预算和待恢复操作。AB/BA 与题包按普通会话指纹验收,service_reuse 按冻结的包版本和服务清理凭据恢复。普通项目从准备到判定均可独立于 Benchmark 运行。 题库 `start` 由 CLI 经 `benchmark.registry` 定位资源目录,再交给 `harness.executor.prepare_task_protocol` 固化;后续从冻结目录加载题包自己的 `optimization.py`,无需再次查询注册表。专用协议检查仍属于题包。两类 `assess` 都只读留存结果,不重新测量。KnowledgeReader 与 `apps/workflows/campaign.py` 的记录回调由 CLI 注入,Harness 不直接导入 Benchmark 或目标 Knowledge 模块,也不经记录模块间接引入知识实现。 diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 4bcbf1246..2ef4e82d6 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -6,9 +6,9 @@ existing protocol. Before search, supply the model, workload, quality task and numerical acceptance thresholds. To collect supplementary profiling evidence, include a profiler in the same protocol. -The existing `optimization_session` entry assembles the mode inside the shared -`harness.optimization` controller. There is one campaign lock, plan and state; -Apps projects those records without writing selection decisions. +The CLI sends typed operations to `inferrsi.harness.manager.run_session`. +Manager owns the campaign lock, frozen plan and session state. Apps reads these +records to present progress and results. ## Prepare the protocol diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index c319acb29..f5b12cdf7 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -6,7 +6,7 @@ import os import sqlite3 import sys -from dataclasses import replace +from dataclasses import fields, replace from importlib.resources import files from pathlib import Path @@ -32,9 +32,28 @@ def _round_provider(plan): return round_provider(plan) +def _session_request(args): + from ...harness import manager + + if args.session_action == "start": + operation = (manager.StartProjectSession if args.project_task + else manager.StartBenchmarkSession) + else: + operations = ( + manager.BaselineSession, manager.DiagnoseSession, manager.EvaluateSessionRound, + manager.FinalizeSession, manager.ProfileSession, manager.QuerySessionKnowledge, + manager.ReadSessionKnowledge, manager.RecoverSession, manager.RefreshSessionReferences, + manager.ResumeSession, manager.SessionStatus, + ) + operation = {request.action: request for request in operations}[args.session_action] + values = vars(args) + return operation(**{field.name: values[field.name] for field in fields(operation) + if field.name in values}) + + def _optimization_session(args, *, task_source=None, report_metadata=None): from ...harness.executor import assess_packaged_task - from ...harness.optimization_session import session_command + from ...harness.manager import run_session from ...knowledge.ranking_policy import managed_ranking_policy settings = None @@ -46,8 +65,8 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): settings = {"channel": CHANNEL_NAME, "backend": "ascend", "platform": args.cannbot_platform} external_project = freeze_project(args.repo if args.project_task else None) - return session_command( - args, task_source=task_source, prepare_context=prepare_context, + return run_session( + _session_request(args), task_source=task_source, prepare_context=prepare_context, assess_packaged=assess_packaged_task, ranking_policy_for=managed_ranking_policy, knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, @@ -492,25 +511,27 @@ def main(argv: list[str] | None = None) -> int: _print(result) return 0 if args.command == "agents": - from ...harness import agent_sessions + from ...harness import manager if args.agent_action == "prepare": - result = agent_sessions.prepare( + result = manager.prepare_agent_session( args.job, prompt=args.prompt_file.read_text(encoding="utf-8"), workspace=args.workspace, title=args.title, max_seconds=args.max_minutes * 60, model=args.model, effort=args.effort, plugin_ref=args.plugin_ref, ) elif args.agent_action == "bind": - result = agent_sessions.bind( + result = manager.bind_agent_session( args.job, host=args.host, session_id=args.session_id, host_id=args.host_id, receipt=args.receipt, ) elif args.agent_action == "record": - result = agent_sessions.record( + result = manager.record_agent_session( args.job, observation=args.observation, artifacts=args.artifact, ) + elif args.agent_action == "dispatch": + result = manager.dispatch_agent_session(args.job) else: - result = getattr(agent_sessions, args.agent_action)(args.job) + result = manager.agent_session_status(args.job) _print(result) return 0 if args.command == "search": diff --git a/src/inferrsi/apps/delivery/benchmark_usage.py b/src/inferrsi/apps/delivery/benchmark_usage.py index 6efe620a4..aa4fc9ed6 100644 --- a/src/inferrsi/apps/delivery/benchmark_usage.py +++ b/src/inferrsi/apps/delivery/benchmark_usage.py @@ -3,7 +3,7 @@ from pathlib import Path from ...benchmark.summary import POLICY, supported_policy, token_usage -from ...harness import agent_sessions +from ...harness import manager from ...harness.records.usage import normalize_usage from .schema import number from .snapshot import Snapshot, SnapshotChanged @@ -67,7 +67,7 @@ def attach_native_usage(snapshot, result, job): dependency.file(path.name, "native_frozen_input", record["sha256"]) # Include alongside the job: each source keeps its own root and stability probe. snapshot.include(dependency, f"agent-input-{index}:") - host = agent_sessions.status(job) + host = manager.agent_session_status(job) if (host["request"] != request or host["last_observation"] != state["last_observation"] or host["usage"] != state["usage"] or host["state"] != state["state"] or host["native_session"] != state["native_session"]): diff --git a/src/inferrsi/apps/views/dashboard_data.py b/src/inferrsi/apps/views/dashboard_data.py index cf5e3b24d..8922b33eb 100644 --- a/src/inferrsi/apps/views/dashboard_data.py +++ b/src/inferrsi/apps/views/dashboard_data.py @@ -724,12 +724,12 @@ def _managed_diagnoses(state: dict, submissions: list) -> list[dict]: def _managed_dashboard(root: Path, campaign: dict) -> dict: """Project the shared control record; do not manufacture legacy AB/BA runs.""" - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records from .optimization_story import build_story from .retrieval_projection import managed_knowledge - plan, state, summary = read_records(root) + plan, state, summary = read_session_records(root) pending = state["pending"] submissions = list(state["rounds"]) if pending and pending["kind"] == "round": @@ -854,11 +854,11 @@ def load_dashboard(source: Path) -> dict: or plan_header.get("schema_version") == 3 ) if service_mode: - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records from .retrieval_projection import public_value - _, _, summary = read_records(root) + _, _, summary = read_session_records(root) return { "campaign_id": sanitized_text(header["campaign_id"]), "evaluation_mode": "service_reuse", diff --git a/src/inferrsi/apps/views/round_citations.py b/src/inferrsi/apps/views/round_citations.py index ce1e5918f..0690133b9 100644 --- a/src/inferrsi/apps/views/round_citations.py +++ b/src/inferrsi/apps/views/round_citations.py @@ -40,11 +40,11 @@ def _managed_citations(root, number): citations = list(_citations([reason])) if isinstance(reason, str) else [] if not citations: return None - from inferrsi.harness.optimization import read_records + from inferrsi.harness.manager import read_session_records notes = {"citations": citations, "receipts": [], "hypothesis": reason} try: - plan, verified, _ = read_records(root) + plan, verified, _ = read_session_records(root) observation = verified["rounds"][number - 1] if observation["hypothesis"] == reason: notes["command"] = (("campaign", "round") if plan["task_source"] == "project" diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index 82e6b16e5..5a0c41323 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -29,9 +29,9 @@ from inferrsi.benchmark.registry import has_iterative_protocol, task_resources from inferrsi.benchmark.summary import POLICY, supported_policy from inferrsi.benchmark.summary import comparison as metrics_comparison -from inferrsi.harness import agent_sessions, optimization +from inferrsi.harness import manager from inferrsi.harness.executor import run_task_protocol -from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.harness.manager import session_runtime_identity from inferrsi.harness.records.artifact_primitives import digest, file_lock, sha256 from inferrsi.harness.records.atomic_json import atomic_write_json from inferrsi.harness.records.knowledge_capture import verify_capture @@ -275,7 +275,7 @@ def _prepare_at(config, sources, runtime, task_settings, root): "parameter_sources": sources, "task_settings": task_settings, "runtime_files": {key: value for key, value in runtime_files.items() if key not in knowledge_files}, - "session_runtime_identity": _runtime_identity(), + "session_runtime_identity": session_runtime_identity(), "knowledge_files": knowledge_files, "trials": trials, "knowledge_boundary": "isolated runtime corpus and session gate; native host " @@ -540,7 +540,7 @@ def _status(root, plan, state, *, host_views=None): job = _job(root, trial, number) if host_views is None: try: - view = agent_sessions.status(job) if job.exists() else None + view = manager.agent_session_status(job) if job.exists() else None except (OSError, ValueError) as error: # As in report: unverifiable job evidence blocks only this trial. view = {"state": "blocked", "native_session": None, @@ -575,7 +575,7 @@ def _status(root, plan, state, *, host_views=None): elif active["state"] == "blocked": action = {"operation": "inspect_retained_host_evidence", "trial": active["id"], "instructions": "Verify the original native job receipts before collection."} - elif active["state"] in agent_sessions.TERMINAL: + elif active["state"] in manager.AGENT_TERMINAL_STATES: action = {"operation": "collect", "trial": active["id"], "instructions": "Retain actual host metadata and campaign tree; collect. " "Host completion is separate from independent final acceptance."} @@ -617,7 +617,7 @@ def dispatch(root, trial_id, *, parallel=False): if current.get("trial") != trial_id or current["operation"] != "dispatch": raise ValueError("Dispatch the next declared trial or pass --parallel") job.parent.mkdir(exist_ok=True) - agent_sessions.prepare( + manager.prepare_agent_session( job, prompt=_prompt(root, plan, trial, workspace), workspace=workspace, title=trial_id if number == 1 else f"{trial_id} attempt {number}", max_seconds=plan["config"]["job_max_minutes"] * 60, @@ -625,11 +625,11 @@ def dispatch(root, trial_id, *, parallel=False): task_reference={"comparison": digest(plan), "trial": trial_id, "attempt": number}, frozen_inputs=(root / "experiment.json",), ) - return agent_sessions.dispatch(job) + return manager.dispatch_agent_session(job) def _host_payload(job, host): - if host is None or host["state"] not in agent_sessions.TERMINAL: + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: return None receipt = host["last_observation"] return _object(job / receipt["path"]) if receipt else None @@ -706,7 +706,7 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non result["attempt_window_missing"] = "native_job_evidence_not_verifiable" return result campaign = workspace / "campaign" - if host is None or host["state"] not in agent_sessions.TERMINAL: + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: result["status"] = "pending" if host is None else "running" result["gaps"].append("Native execution has not terminated") result["attempt_window_missing"] = "native_execution_not_terminated" @@ -742,7 +742,7 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non return result try: snapshot, delivery, _ = project(campaign, export_id="comparison-read") - campaign_plan, control, _ = optimization.read_records(campaign) + campaign_plan, control, _ = manager.read_session_records(campaign) result["campaign_window"] = {"started_at": control.get("started_at"), "ended_at": control.get("settled_at")} window = result["attempt_window"] @@ -863,8 +863,8 @@ def collect(root, trial_id): return {"trial": _retained(root, reference, trial_id, number), "already_collected": True, "collection": reference, "next": _status(root, plan, state)["next_action"]} job = _job(root, trial, number) - host = agent_sessions.status(job) if job.exists() else None - if host is None or host["state"] not in agent_sessions.TERMINAL: + host = manager.agent_session_status(job) if job.exists() else None + if host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: raise ValueError("Collect only after recording a terminal native host observation") result = _trial_result(root, plan, trial, host, _host_payload(job, host), workspace=_workspace(root, trial, number)) @@ -892,8 +892,8 @@ def retry(root, trial_id, *, parallel=False): number = _attempt_number(state, trial) job = _job(root, trial, number) reference = state["collections"].get(trial_id) - host = agent_sessions.status(job) if job.exists() else None - if reference is None or host is None or host["state"] not in agent_sessions.TERMINAL: + host = manager.agent_session_status(job) if job.exists() else None + if reference is None or host is None or host["state"] not in manager.AGENT_TERMINAL_STATES: raise ValueError("Retry only after collecting a terminal attempt of this trial") retained = _retained(root, reference, trial_id, number) if retained.get("status") == "completed" and retained.get("eligible") is True: @@ -944,7 +944,7 @@ def _reverify(root, plan, trial, number, *, collected=False, archived=False): if collected and not job.is_dir(): # A collected attempt had a terminal job: losing it is unverifiable, not "not run". raise FileNotFoundError("Collected native job is missing") - host = agent_sessions.status(job) if job.exists() else None + host = manager.agent_session_status(job) if job.exists() else None payload = _host_payload(job, host) except (OSError, ValueError) as error: host = {"state": "blocked", "native_session": None} @@ -1108,12 +1108,12 @@ def compare_command(args): other_job = _job(root, other, number) if other_job == job or not other_job.exists(): continue - native = agent_sessions.status(other_job)["native_session"] + native = manager.agent_session_status(other_job)["native_session"] if native and _session_key(native) == (args.host, args.session_id): raise ValueError("Native session is already bound to trial " f"{other['id']} attempt {number}") - return agent_sessions.bind(job, host=args.host, session_id=args.session_id, + return manager.bind_agent_session(job, host=args.host, session_id=args.session_id, host_id=args.host_id, receipt=args.receipt) if args.observation is None: raise ValueError("record requires --observation") - return agent_sessions.record(job, observation=args.observation) + return manager.record_agent_session(job, observation=args.observation) diff --git a/src/inferrsi/apps/workflows/parallel_round.py b/src/inferrsi/apps/workflows/parallel_round.py index 40ff13fea..af78be966 100644 --- a/src/inferrsi/apps/workflows/parallel_round.py +++ b/src/inferrsi/apps/workflows/parallel_round.py @@ -1,7 +1,7 @@ """Compose Harness parallel-round orchestration with Benchmark v0 gates. Harness owns prepare / submit / serve / close scheduling. This package binds the -legacy assess port so ``inferrsi.harness.parallel_round`` never imports Benchmark. +legacy assess port for the Manager. """ from collections.abc import Callable @@ -36,9 +36,9 @@ def serve_ticket( clock=None, ) -> dict: """Serve one ticket with the v0 assess composition.""" - from inferrsi.harness import parallel_round as harness + from inferrsi.harness.manager import serve_parallel_ticket - return harness.serve_ticket( + return serve_parallel_ticket( round_dir, ticket, incumbent, @@ -59,9 +59,9 @@ def close_round( clock=None, ) -> dict: """Close one round with the v0 assess composition.""" - from inferrsi.harness import parallel_round as harness + from inferrsi.harness.manager import close_parallel_round - return harness.close_round( + return close_parallel_round( round_dir, incumbent, backend=backend, diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index d56f8329c..bba49aca8 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -14,8 +14,10 @@ measurement and assessment rules. The [service observation reader](records/service_observations.py) reconstructs settled rounds, including older embedded profiles. Service readers and writers share the [path, JSON and diagnostic limits](records/service_io.py). -- [`optimization_session.py`](optimization_session.py) connects session - commands to the budget and recovery logic in [`optimization.py`](optimization.py). +- [Manager](manager/__init__.py) exposes `run_session` for typed requests such as + `StartProjectSession`, `StartBenchmarkSession`, `EvaluateSessionRound` and `RecoverSession`. + Apps resolves task resources and supplies the ranking policy, knowledge reader and assessor. + Hosts use `read_session_records` to read the retained plan, rounds and final assessment. [Executor](executor/__init__.py) exposes `prepare_task_protocol` to freeze task resources and `run_task_protocol` to run their operations in an [isolated child](executor/protocol_child.py). For an ordinary project, `prepare_project` freezes the checks and `execute_ordinary` runs each @@ -54,13 +56,14 @@ measurement and assessment rules. ## Managed optimization loop -`campaign` and `benchmarks session` enter through [session_command](optimization_session.py). +`campaign` and `benchmarks session` construct the same requests a Python host passes to +[`manager.run_session`](manager/__init__.py). The agent chooses a hypothesis and edits a candidate between rounds. - **Manager** owns the session ledger, round and time budgets, pending work, recovery and final - retests. These operations currently share the [round controller](optimization.py). + retests. These operations share the [round controller](manager/_state.py). - **Analyzer** [validates the reported bottleneck and measurement summary](analyzer/__init__.py). - [Manager](optimization.py) records the diagnosis ID, time and condition epoch. The performance-ceiling + [Manager](manager/__init__.py) records the diagnosis ID, time and condition epoch. The performance-ceiling analysis skill lives in Knowledge. - **Indexer** [checks managed deliveries](indexer/__init__.py) against the frozen ranking. Apps injects the ordinary in-memory capture callback or the service context reader. diff --git a/src/inferrsi/harness/manager/__init__.py b/src/inferrsi/harness/manager/__init__.py index 7ac17ee52..44e783b3e 100644 --- a/src/inferrsi/harness/manager/__init__.py +++ b/src/inferrsi/harness/manager/__init__.py @@ -1,6 +1,52 @@ """Manage Harness experiments, session progression and search budgets.""" +from ._agent_sessions import ( + AGENT_TERMINAL_STATES, + agent_session_status, + bind_agent_session, + dispatch_agent_session, + prepare_agent_session, + record_agent_session, +) +from ._parallel_round import ( + close_parallel_round, + parallel_ticket_status, + prepare_parallel_round, + serve_parallel_ticket, + submit_parallel_ticket, +) +from ._requests import ( + BaselineSession, + DiagnoseSession, + EvaluateSessionRound, + FinalizeSession, + ProfileSession, + QuerySessionKnowledge, + ReadSessionKnowledge, + RecoverSession, + RefreshSessionReferences, + ResumeSession, + SessionRequest, + SessionStatus, + StartBenchmarkSession, + StartProjectSession, +) from ._runner import run_experiment +from ._runtime import session_runtime_identity +from ._session import run_session +from ._state import read_session_records from .search._engine import EngineSearchPlan, read_engine_search, run_engine_search -__all__ = ["EngineSearchPlan", "read_engine_search", "run_engine_search", "run_experiment"] +__all__ = [ + "BaselineSession", "DiagnoseSession", "EvaluateSessionRound", + "FinalizeSession", "ProfileSession", "QuerySessionKnowledge", + "ReadSessionKnowledge", "RecoverSession", "RefreshSessionReferences", + "ResumeSession", "SessionRequest", "SessionStatus", + "StartBenchmarkSession", "StartProjectSession", + "read_session_records", "run_session", + "AGENT_TERMINAL_STATES", "agent_session_status", "bind_agent_session", + "dispatch_agent_session", "prepare_agent_session", "record_agent_session", + "EngineSearchPlan", "read_engine_search", "run_engine_search", "run_experiment", + "session_runtime_identity", "close_parallel_round", "parallel_ticket_status", + "prepare_parallel_round", "serve_parallel_ticket", "submit_parallel_ticket", +] diff --git a/src/inferrsi/harness/agent_sessions.py b/src/inferrsi/harness/manager/_agent_sessions.py similarity index 93% rename from src/inferrsi/harness/agent_sessions.py rename to src/inferrsi/harness/manager/_agent_sessions.py index 9297980b2..02d047ace 100644 --- a/src/inferrsi/harness/agent_sessions.py +++ b/src/inferrsi/harness/manager/_agent_sessions.py @@ -10,12 +10,12 @@ import uuid from pathlib import Path -from .records.artifact_primitives import digest, file_lock, sha256 -from .records.atomic_json import atomic_write_json -from .records.usage import normalize_usage +from ..records.artifact_primitives import digest, file_lock, sha256 +from ..records.atomic_json import atomic_write_json +from ..records.usage import normalize_usage -TERMINAL = {"completed", "failed", "cancelled"} -OBSERVED_STATES = {"running", "needs_attention", *TERMINAL} +AGENT_TERMINAL_STATES = {"completed", "failed", "cancelled"} +OBSERVED_STATES = {"running", "needs_attention", *AGENT_TERMINAL_STATES} MAX_EXPORT_BYTES = 2 * 1024 * 1024 @@ -94,7 +94,7 @@ def _view(root, request, state): "cost": None, "task_acceptance": "not_assessed", "next_action": ( "inspect_native_host_and_stop_if_still_running" if expired - and state["state"] not in TERMINAL else { + and state["state"] not in AGENT_TERMINAL_STATES else { "prepared": "dispatch_then_use_native_fresh_session_tool", "dispatching": "inspect_original_host_call_and_bind_without_relaunch", "running": "observe_native_session_and_record_receipt", @@ -107,7 +107,7 @@ def _view(root, request, state): } -def prepare(root: Path, *, prompt: str, workspace: Path, title: str, +def prepare_agent_session(root: Path, *, prompt: str, workspace: Path, title: str, max_seconds: float, model=None, effort=None, plugin_ref=None, task_reference=None, frozen_inputs=()) -> dict: """Freeze explicit task/configuration, without inheriting a parent conversation.""" @@ -145,13 +145,13 @@ def prepare(root: Path, *, prompt: str, workspace: Path, title: str, return _view(root, request, state) -def status(root: Path) -> dict: +def agent_session_status(root: Path) -> dict: root = root.resolve() with _locked(root): return _view(root, *_load(root)) -def dispatch(root: Path) -> dict: +def dispatch_agent_session(root: Path) -> dict: """Reserve exactly one native creation attempt before calling the host tool.""" root = root.resolve() with _locked(root): @@ -181,7 +181,9 @@ def dispatch(root: Path) -> dict: } -def bind(root: Path, *, host: str, session_id: str, receipt: Path, host_id=None) -> dict: +def bind_agent_session( + root: Path, *, host: str, session_id: str, receipt: Path, host_id=None, +) -> dict: """Associate a confirmed native ID with its opaque, caller-exported tool receipt.""" root = root.resolve() native = {"host": _text(host, "host"), "session_id": _text(session_id, "session_id"), @@ -202,7 +204,7 @@ def bind(root: Path, *, host: str, session_id: str, receipt: Path, host_id=None) return _view(root, request, state) -def record(root: Path, *, observation: Path, artifacts=()) -> dict: +def record_agent_session(root: Path, *, observation: Path, artifacts=()) -> dict: """Retain an explicit host observation; completed execution is not task acceptance.""" root = root.resolve() raw, value = _export(observation) @@ -231,7 +233,7 @@ def record(root: Path, *, observation: Path, artifacts=()) -> dict: _text(value.get("host"), "host") elif any(value.get(key) != native[key] for key in ("host", "session_id", "host_id")): raise ValueError("Observation does not identify the bound native session") - if state["state"] in TERMINAL and value["state"] != state["state"]: + if state["state"] in AGENT_TERMINAL_STATES and value["state"] != state["state"]: raise ValueError("A terminal native session cannot change state in this job") previous_usage = (state.get("last_observed_usage") or {}).get("usage") if usage is not None and previous_usage is not None and any( diff --git a/src/inferrsi/harness/attempt_recovery.py b/src/inferrsi/harness/manager/_attempt_recovery.py similarity index 97% rename from src/inferrsi/harness/attempt_recovery.py rename to src/inferrsi/harness/manager/_attempt_recovery.py index 36cad4287..0b8de8030 100644 --- a/src/inferrsi/harness/attempt_recovery.py +++ b/src/inferrsi/harness/manager/_attempt_recovery.py @@ -6,9 +6,9 @@ import uuid from pathlib import Path -from .executor.launch_records import observe -from .records.atomic_json import durable_write_json -from .records.evidence import bounded_record_bytes +from ..executor.launch_records import observe +from ..records.atomic_json import durable_write_json +from ..records.evidence import bounded_record_bytes _CLEAR = {"not_spawned", "recorded_empty", "observed_empty"} _FIELDS = ( diff --git a/src/inferrsi/harness/parallel_round.py b/src/inferrsi/harness/manager/_parallel_round.py similarity index 99% rename from src/inferrsi/harness/parallel_round.py rename to src/inferrsi/harness/manager/_parallel_round.py index 396a5ff1c..9d7af7062 100644 --- a/src/inferrsi/harness/parallel_round.py +++ b/src/inferrsi/harness/manager/_parallel_round.py @@ -71,9 +71,9 @@ confined_execute, ) from inferrsi.harness.executor.device_lease import DeviceLease, LeaseError -from inferrsi.harness.manager import run_experiment as run_experiment_loop from inferrsi.harness.records.artifact_primitives import digest -from inferrsi.harness.round_budget import ( + +from ._round_budget import ( Binding, BudgetError, Entry, @@ -86,6 +86,7 @@ ensure_open, seconds_remaining, ) +from ._runner import run_experiment as run_experiment_loop _TERMINAL = frozenset({"measured", "rejected", "unsettled", "failed"}) @@ -401,7 +402,7 @@ def _lane(plan: dict, lane_id: str) -> dict: return matches[0] -def prepare(spec: dict, incumbent: Path, round_dir: Path) -> dict: +def prepare_parallel_round(spec: dict, incumbent: Path, round_dir: Path) -> dict: """Validate lane scopes and write ``round-plan.json``. The digest covers the validated body.""" if not isinstance(spec, dict): raise RoundPlanError("round spec must be an object") @@ -545,7 +546,7 @@ def prepare(spec: dict, incumbent: Path, round_dir: Path) -> dict: return body -def submit( +def submit_parallel_ticket( round_dir: Path, lane_id: str, incumbent: Path, work: Path, *, now: datetime | None = None ) -> dict: """Copy in-glob changes to the outbox. The same manifest always returns the same ticket. @@ -1015,7 +1016,7 @@ def hold_devices(round_dir: Path, plan: dict, count: int) -> list[tuple[str, obj return held -def serve_ticket( +def serve_parallel_ticket( round_dir: Path, ticket: str, incumbent: Path, @@ -1244,7 +1245,7 @@ def _measure( ) -def ticket_status(round_dir: Path, ticket: str) -> dict: +def parallel_ticket_status(round_dir: Path, ticket: str) -> dict: path = round_dir / "results" / f"{ticket}.json" if path.exists(): return json.loads(path.read_text(encoding="utf-8")) @@ -1320,7 +1321,7 @@ def _receipts(round_dir: Path) -> dict[str, dict]: return {path.stem: json.loads(path.read_text(encoding="utf-8")) for path in root.glob("*.json")} -def close_round( +def close_parallel_round( round_dir: Path, incumbent: Path, *, diff --git a/src/inferrsi/harness/manager/_requests.py b/src/inferrsi/harness/manager/_requests.py new file mode 100644 index 000000000..c0a5b2002 --- /dev/null +++ b/src/inferrsi/harness/manager/_requests.py @@ -0,0 +1,155 @@ +"""Inputs for one managed campaign or packaged benchmark session operation.""" + +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import ClassVar, Literal + + +@dataclass(frozen=True, kw_only=True) +class _Session: + session: Path + + +@dataclass(frozen=True, kw_only=True) +class _StartSession(_Session): + action: ClassVar[str] = "start" + rounds: int + max_minutes: float + evaluation_timeout_seconds: float + condition: str + python: str = sys.executable + evaluation_prefix: str = "" + final_reserve_seconds: float | None = None + knowledge: Literal["on", "off"] = "on" + ranking_policy: str = "default" + + +@dataclass(frozen=True, kw_only=True) +class StartBenchmarkSession(_StartSession): + task: str + evaluation_args: str + round_mode: Literal["exact", "up_to"] = "exact" + + +@dataclass(frozen=True, kw_only=True) +class StartProjectSession(_StartSession): + repo: Path + include: list[str] + protocol: Path + instructions: Path + round_mode: Literal["exact", "up_to"] = "up_to" + evaluation_mode: Literal["abba", "service_reuse"] = "abba" + evaluation_config: Path | None = None + allow_final_continuation: bool = False + measure_command: str | None = None + quality_command: str | None = None + metric_key: str | None = None + metric_unit: str | None = None + quality_key: str | None = None + scope: str | None = None + direction: Literal["minimize", "maximize"] | None = None + min_improvement_pct: float | None = None + repetitions: int | None = None + warmups: int | None = None + decision: Literal["point", "paired"] = "point" + require_explanation: bool = False + + +@dataclass(frozen=True, kw_only=True) +class SessionStatus(_Session): + action: ClassVar[str] = "status" + + +@dataclass(frozen=True, kw_only=True) +class DiagnoseSession(_Session): + action: ClassVar[str] = "diagnose" + bottleneck: str + evidence: Path + + +@dataclass(frozen=True, kw_only=True) +class QuerySessionKnowledge(_Session): + action: ClassVar[str] = "knowledge" + query: str + context_bytes: int + relevance_method: str | None = None + scenario: str | None = None + limit: int = 5 + + +@dataclass(frozen=True, kw_only=True) +class ReadSessionKnowledge(_Session): + action: ClassVar[str] = "knowledge-read" + search_ref: str + locator: str + page: int = 1 + + +@dataclass(frozen=True, kw_only=True) +class _Retryable(_Session): + retry_of: str | None = None + repair_protocol: Path | None = None + repair_reason: str | None = None + cleanup_receipt: Path | None = None + + +@dataclass(frozen=True, kw_only=True) +class BaselineSession(_Retryable): + action: ClassVar[str] = "baseline" + + +@dataclass(frozen=True, kw_only=True) +class EvaluateSessionRound(_Retryable): + action: ClassVar[str] = "round" + candidate: Path + hypothesis: str + strategy: str | None = None + alternative: list[str] | None = None + selection_reason: str | None = None + knowledge_ref: list[str] | None = None + mechanism_file: Path | None = None + usage_export: Path | None = None + continue_after_final: str | None = None + continuation_reason: str | None = None + + +@dataclass(frozen=True, kw_only=True) +class FinalizeSession(_Session): + action: ClassVar[str] = "final" + usage_export: Path | None = None + reason: str | None = None + + +@dataclass(frozen=True, kw_only=True) +class RecoverSession(_Session): + action: ClassVar[str] = "recover" + confirm_domain_empty: bool = False + cleanup_receipt: Path | None = None + + +@dataclass(frozen=True, kw_only=True) +class ProfileSession(_Session): + action: ClassVar[str] = "profile" + round: int + + +@dataclass(frozen=True, kw_only=True) +class RefreshSessionReferences(_Retryable): + action: ClassVar[str] = "refresh-references" + conditions: Path + reason: str + + +@dataclass(frozen=True, kw_only=True) +class ResumeSession(_Session): + action: ClassVar[str] = "resume" + reason: str + cleanup_receipt: Path | None = None + + +SessionRequest = ( + StartProjectSession | StartBenchmarkSession | SessionStatus | DiagnoseSession + | QuerySessionKnowledge | ReadSessionKnowledge | BaselineSession | EvaluateSessionRound + | FinalizeSession | RecoverSession | ProfileSession | RefreshSessionReferences | ResumeSession +) diff --git a/src/inferrsi/harness/round_budget.py b/src/inferrsi/harness/manager/_round_budget.py similarity index 100% rename from src/inferrsi/harness/round_budget.py rename to src/inferrsi/harness/manager/_round_budget.py diff --git a/src/inferrsi/harness/session_runtime.py b/src/inferrsi/harness/manager/_runtime.py similarity index 90% rename from src/inferrsi/harness/session_runtime.py rename to src/inferrsi/harness/manager/_runtime.py index e82a93299..89f665bce 100644 --- a/src/inferrsi/harness/session_runtime.py +++ b/src/inferrsi/harness/manager/_runtime.py @@ -6,7 +6,11 @@ """ import ast +from importlib.resources import files from importlib.util import resolve_name +from pathlib import Path + +from ..records.artifact_primitives import sha256 _KNOWLEDGE_ROOTS = ( "inferrsi.knowledge.context_projection", @@ -14,7 +18,7 @@ "inferrsi.knowledge.ranking_policy", ) _ROOTS = ( - "inferrsi.harness.optimization_session", + "inferrsi.harness.manager._session", "inferrsi.apps.workflows.campaign", *_KNOWLEDGE_ROOTS, ) @@ -90,3 +94,9 @@ def source_files(root): sources.add(relative) pending.extend(_imports(ast.parse(path.read_bytes(), relative), package, relative)) return sorted(sources) + + +def session_runtime_identity() -> dict[str, str]: + """Hash the installed source files that define an ordinary session.""" + root = Path(str(files("inferrsi"))) + return {name: sha256(root / name) for name in source_files(root)} diff --git a/src/inferrsi/harness/service_backfill.py b/src/inferrsi/harness/manager/_service_backfill.py similarity index 98% rename from src/inferrsi/harness/service_backfill.py rename to src/inferrsi/harness/manager/_service_backfill.py index 3be0ac3e9..470ddcccc 100644 --- a/src/inferrsi/harness/service_backfill.py +++ b/src/inferrsi/harness/manager/_service_backfill.py @@ -4,9 +4,10 @@ import time import uuid -from . import executor, optimization -from .records import service_io -from .records.atomic_json import atomic_write_json +from .. import executor +from ..records import service_io +from ..records.atomic_json import atomic_write_json +from . import _state as optimization def _target(state, number): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/manager/_session.py similarity index 52% rename from src/inferrsi/harness/optimization_session.py rename to src/inferrsi/harness/manager/_session.py index 7c2f9145b..88cf6326f 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/manager/_session.py @@ -6,58 +6,68 @@ import json import shlex +import sys from functools import partial -from importlib.resources import files from pathlib import Path +from ._requests import SessionRequest, StartBenchmarkSession, StartProjectSession -def _runtime_identity(): - from inferrsi.harness.records.artifact_primitives import sha256 - from inferrsi.harness.session_runtime import source_files - root = Path(str(files("inferrsi"))) - return {name: sha256(root / name) for name in source_files(root)} - - -def session_command(args, *, ranking_policy_for, assess_packaged, task_source: Path | None = None, - knowledge_reader=None, - prepare_context=None, external_knowledge=None, external_provider=None, - external_project=None, external_provider_for=None, - report_metadata=None) -> dict: - """Run one operation; discovery and knowledge access are supplied by the caller.""" - from inferrsi.harness import evaluator, executor, indexer, optimization - - root = args.session.resolve() - if args.session_action == "start": - import math +def run_session( + request: SessionRequest, *, ranking_policy_for, assess_packaged, + task_source: Path | None = None, + knowledge_reader=None, prepare_context=None, external_knowledge=None, external_provider=None, + external_project=None, external_provider_for=None, report_metadata=None, +) -> dict: + """Run one typed session operation with dependencies supplied by the host.""" + from .. import evaluator, executor, indexer + from . import _state as state + from ._runtime import session_runtime_identity + if not isinstance(request, SessionRequest): + raise TypeError("run_session requires a managed session request") + root = request.session.resolve() + if isinstance(request, (StartProjectSession, StartBenchmarkSession)): + project = isinstance(request, StartProjectSession) from inferrsi.harness.executor import prepare_task_protocol from inferrsi.harness.executor.candidates import identity, retain from inferrsi.harness.records.artifact_primitives import sha256 - if args.rounds < 1 or any(not math.isfinite(value) or value <= 0 for value in ( - args.max_minutes, args.evaluation_timeout_seconds - )) or not args.condition.strip() or not args.python.strip(): + budgets = (request.max_minutes, request.evaluation_timeout_seconds) + if (type(request.rounds) is not int or request.rounds < 1 + or any(type(value) not in (int, float) or not 0 < value <= sys.float_info.max + for value in budgets) + or not request.condition.strip() or not request.python.strip()): raise ValueError("A positive round/time budget and condition label are required") + max_seconds = request.max_minutes * 60 + if max_seconds > sys.float_info.max: + raise ValueError("The session time budget must be finite in seconds") + if request.round_mode not in ("exact", "up_to") or request.knowledge not in ("on", "off"): + raise ValueError("Choose a supported round mode and knowledge setting") + if project and (request.evaluation_mode not in ("abba", "service_reuse") + or request.decision not in ("point", "paired") + or type(request.allow_final_continuation) is not bool + or type(request.require_explanation) is not bool): + raise ValueError("Choose valid project evaluation settings") if root.exists(): raise ValueError("Session directory must be new") - ranking_policy = ranking_policy_for(args.ranking_policy) - reserve = (args.final_reserve_seconds if args.final_reserve_seconds is not None - else args.evaluation_timeout_seconds) - if not math.isfinite(reserve) or not 0 < reserve < args.max_minutes * 60: + ranking_policy = ranking_policy_for(request.ranking_policy) + reserve = (request.final_reserve_seconds if request.final_reserve_seconds is not None + else request.evaluation_timeout_seconds) + if type(reserve) not in (int, float) or not 0 < reserve < max_seconds: raise ValueError("Reserve time for final within the total budget") - evaluation_prefix = shlex.split(args.evaluation_prefix) - if external_knowledge and args.knowledge != "on": + evaluation_prefix = shlex.split(request.evaluation_prefix) + if external_knowledge and request.knowledge != "on": raise ValueError("External knowledge requires --knowledge on") - if (external_knowledge and args.project_task - and args.evaluation_mode == "service_reuse"): + if (external_knowledge and project + and request.evaluation_mode == "service_reuse"): raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") - allow_continuation = getattr(args, "allow_final_continuation", False) + allow_continuation = getattr(request, "allow_final_continuation", False) if allow_continuation and ( - args.evaluation_mode != "service_reuse" or args.round_mode != "up_to" + request.evaluation_mode != "service_reuse" or request.round_mode != "up_to" ): raise ValueError("Final continuation requires an up-to-budget service-reuse campaign") - if args.project_task: + if project: names = ( "metric_key", "metric_unit", @@ -70,38 +80,38 @@ def session_command(args, *, ranking_policy_for, assess_packaged, task_source: P "measure_command", "quality_command", ) - if args.evaluation_mode == "service_reuse": + if request.evaluation_mode == "service_reuse": from inferrsi.harness.executor import prepare_service - if args.evaluation_config is None or any( - getattr(args, key) is not None for key in names + if request.evaluation_config is None or any( + getattr(request, key) is not None for key in names ): raise ValueError( "Service reuse requires --evaluation-config without AB/BA options" ) - if args.decision != "point" or args.require_explanation: + if request.decision != "point" or request.require_explanation: # Both switches read AB/BA pairs and per-measurement breakdown/counters; # this mode's optional profiling stage does not produce those inputs. raise ValueError( "--decision paired and --require-explanation apply to AB/BA campaigns" ) - settings = prepare_service(root, args) + settings = prepare_service(root, request) plan = { "schema_version": 3, - "condition": args.condition, - "round_limit": args.rounds, - "max_seconds": args.max_minutes * 60, - "round_mode": args.round_mode, + "condition": request.condition, + "round_limit": request.rounds, + "max_seconds": max_seconds, + "round_mode": request.round_mode, "final_reserve_seconds": reserve, - "knowledge_allowed": args.knowledge == "on", + "knowledge_allowed": request.knowledge == "on", "ranking_policy": ranking_policy.configuration(), - "evaluation_timeout_seconds": args.evaluation_timeout_seconds, + "evaluation_timeout_seconds": request.evaluation_timeout_seconds, "evaluation_prefix": evaluation_prefix, - "python": args.python, + "python": request.python, **({"allow_final_continuation": True} if allow_continuation else {}), **settings, } - result = optimization.initialize(root, plan) + result = state.initialize(root, plan) result["instructions"] = ( "Run campaign baseline before candidate search. Record the measured " "bottleneck with campaign diagnose before knowledge or rounds. " @@ -110,68 +120,68 @@ def session_command(args, *, ranking_policy_for, assess_packaged, task_source: P "Finish with campaign final; final does not collect a profile." ) return result - if args.evaluation_config is not None or any( - getattr(args, key) is None for key in names + if request.evaluation_config is not None or any( + getattr(request, key) is None for key in names ): raise ValueError( "AB/BA requires its existing metric, quality, command and sampling options" ) from inferrsi.harness.executor import prepare_project - repo = args.repo.resolve() + repo = request.repo.resolve() if not repo.is_dir() or root.is_relative_to(repo): raise ValueError("Campaign output must be outside the editable project") - identity(repo, args.include) # Reject invalid inputs before preparation writes. - specification = {key: getattr(args, key) for key in ( + identity(repo, request.include) # Reject invalid inputs before preparation writes. + specification = {key: getattr(request, key) for key in ( "metric_key", "metric_unit", "quality_key", "scope", "direction", "min_improvement_pct", "repetitions", "warmups", "decision", "require_explanation")} - specification.update(measure_command=shlex.split(args.measure_command), - quality_command=shlex.split(args.quality_command)) - settings = prepare_project(root / "frozen", args.protocol.resolve(), - args.instructions.resolve(), specification) - retain(repo, root / "frozen/baseline", args.include) + specification.update(measure_command=shlex.split(request.measure_command), + quality_command=shlex.split(request.quality_command)) + settings = prepare_project(root / "frozen", request.protocol.resolve(), + request.instructions.resolve(), specification) + retain(repo, root / "frozen/baseline", request.include) settings["frozen_files"].update({p.relative_to(root / "frozen").as_posix(): sha256(p) for p in (root / "frozen/baseline").rglob("*") if p.is_file()}) candidate = {"task": "project:" + repo.name, "task_source": "project", "candidate_kind": "directory", "candidate_name": "candidate", - "candidate_includes": args.include, "baseline_path": "frozen/baseline", + "candidate_includes": request.include, "baseline_path": "frozen/baseline", "working_candidate": str(repo), "selection": ( # Paired mode ranks by the speedup its decision reads. {"direction": "maximize", "initial_score": 1.0, "metric": "paired_median_speedup"} - if args.decision == "paired" else - {"direction": args.direction, "initial_score": None, - "metric": args.metric_key})} + if request.decision == "paired" else + {"direction": request.direction, "initial_score": None, + "metric": request.metric_key})} else: if task_source is None: raise ValueError("A resolved task resource directory is required to start") settings = prepare_task_protocol( - task_source, root / "frozen", shlex.split(args.evaluation_args) + task_source, root / "frozen", shlex.split(request.evaluation_args) ) (root / "work").mkdir() (root / "work/candidate.py").write_bytes((root / "frozen/baseline.py").read_bytes()) - candidate = {"task": args.task, "task_source": "benchmark", "candidate_kind": "file", + candidate = {"task": request.task, "task_source": "benchmark", "candidate_kind": "file", "candidate_name": "candidate.py", "baseline_path": "frozen/baseline.py", "working_candidate": "work/candidate.py", "selection": {"direction": "maximize", "initial_score": 1.0, "metric": "speedup"}} - plan = {"schema_version": 2, "condition": args.condition, - "round_limit": args.rounds, "max_seconds": args.max_minutes * 60, - "round_mode": args.round_mode, "final_reserve_seconds": reserve, - "knowledge_allowed": args.knowledge == "on", + plan = {"schema_version": 2, "condition": request.condition, + "round_limit": request.rounds, "max_seconds": max_seconds, + "round_mode": request.round_mode, "final_reserve_seconds": reserve, + "knowledge_allowed": request.knowledge == "on", "ranking_policy": ranking_policy.receipt(), - "evaluation_timeout_seconds": args.evaluation_timeout_seconds, - "evaluation_prefix": evaluation_prefix, "python": args.python, - "runtime_identity": _runtime_identity(), **candidate, **settings} + "evaluation_timeout_seconds": request.evaluation_timeout_seconds, + "evaluation_prefix": evaluation_prefix, "python": request.python, + "runtime_identity": session_runtime_identity(), **candidate, **settings} if external_knowledge: plan["external_knowledge"] = external_knowledge plan["external_knowledge_project"] = external_project if report_metadata is not None: plan["report_metadata"] = report_metadata - result = optimization.initialize(root, plan) - operation = "campaign" if args.project_task else "benchmarks session" + result = state.initialize(root, plan) + operation = "campaign" if project else "benchmarks session" result["instructions"] = ( f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " f"diagnose first. Use {operation} knowledge when needed and permitted. " @@ -197,54 +207,55 @@ def session_command(args, *, ranking_policy_for, assess_packaged, task_source: P or plan.get("schema_version") == 3 or manifest.get("evaluation_mode") == "service_reuse" ): - if getattr(args, "confirm_domain_empty", False): + if getattr(request, "confirm_domain_empty", False): raise ValueError("Service-reuse cleanup requires --cleanup-receipt") - if args.session_action == "profile": + if request.action == "profile": try: - return optimization.service_command( - root, args, ranking_policy_for=ranking_policy_for, + return state.service_command( + root, request, ranking_policy_for=ranking_policy_for, ) except (ValueError, OSError) as exc: message = "Campaign lock is busy" if isinstance(exc, BlockingIOError) else str(exc) return { "exit_code": 2, - "round": args.round, + "round": request.round, "profiling_error": { "status": "failed", "stage": "campaign", "message": message, }, } - if args.session_action == "knowledge-read": + if request.action == "knowledge-read": raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") - if getattr(args, "mechanism_file", None) is not None: + if getattr(request, "mechanism_file", None) is not None: raise ValueError("Mechanism checks apply to AB/BA project campaign rounds only") - if getattr(args, "alternative", None) is not None or getattr( - args, "selection_reason", None) is not None: + if getattr(request, "alternative", None) is not None or getattr( + request, "selection_reason", None) is not None: raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") - return optimization.service_command(root, args, knowledge_reader=knowledge_reader, - ranking_policy_for=ranking_policy_for) + return state.service_command( + root, request, knowledge_reader=knowledge_reader, ranking_policy_for=ranking_policy_for, + ) if ( - args.session_action in ("baseline", "refresh-references", "resume", "profile") - or getattr(args, "retry_of", None) - or getattr(args, "repair_reason", None) - or getattr(args, "cleanup_receipt", None) - or getattr(args, "repair_protocol", None) - or getattr(args, "continue_after_final", None) is not None - or getattr(args, "continuation_reason", None) is not None + request.action in ("baseline", "refresh-references", "resume", "profile") + or getattr(request, "retry_of", None) + or getattr(request, "repair_reason", None) + or getattr(request, "cleanup_receipt", None) + or getattr(request, "repair_protocol", None) + or getattr(request, "continue_after_final", None) is not None + or getattr(request, "continuation_reason", None) is not None ): raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") - if plan["runtime_identity"] != _runtime_identity(): + if plan["runtime_identity"] != session_runtime_identity(): raise ValueError("Optimization runtime changed, use its frozen runtime to resume") ranking_policy = indexer.resolve_frozen_ranking( - plan, ranking_policy_for, read_only=args.session_action == "status", + plan, ranking_policy_for, read_only=request.action == "status", ) - if args.session_action == "status": - return optimization.status(root) - if args.session_action == "diagnose": - return optimization.record_diagnosis(root, args.bottleneck, args.evidence) - if args.session_action == "knowledge": + if request.action == "status": + return state.status(root) + if request.action == "diagnose": + return state.record_diagnosis(root, request.bottleneck, request.evidence) + if request.action == "knowledge": if knowledge_reader is None or prepare_context is None: raise ValueError("A knowledge reader and capture callback are required") - return optimization.capture_context( + return state.capture_context( root, knowledge_reader, prepare_context=prepare_context, @@ -252,31 +263,31 @@ def session_command(args, *, ranking_policy_for, assess_packaged, task_source: P external_provider=external_provider, external_provider_for=external_provider_for, query="", - relevance=args.query, - relevance_method=args.relevance_method, - scenario=getattr(args, "scenario", None), - context_bytes=args.context_bytes, - limit=args.limit, + relevance=request.query, + relevance_method=request.relevance_method, + scenario=getattr(request, "scenario", None), + context_bytes=request.context_bytes, + limit=request.limit, ) - if args.session_action == "knowledge-read": - return optimization.read_external_context( - root, external_provider, search_ref=args.search_ref, locator=args.locator, - page=args.page, external_provider_for=external_provider_for, + if request.action == "knowledge-read": + return state.read_external_context( + root, external_provider, search_ref=request.search_ref, locator=request.locator, + page=request.page, external_provider_for=external_provider_for, ) assess = partial(evaluator.assess_ordinary, assess_packaged=assess_packaged) - if args.session_action == "recover": - return optimization.recover( - root, assess, confirm_domain_empty=getattr(args, "confirm_domain_empty", False) + if request.action == "recover": + return state.recover( + root, assess, confirm_domain_empty=getattr(request, "confirm_domain_empty", False) ) - final = args.session_action == "final" + final = request.action == "final" mechanism = None - if not final and getattr(args, "mechanism_file", None) is not None: + if not final and getattr(request, "mechanism_file", None) is not None: if plan.get("task_source") != "project": raise ValueError("Mechanism checks apply to project campaign rounds only") from inferrsi.harness.evaluator import CONFIDENCE, min_pairs, validate_mechanism mechanism = validate_mechanism( - json.loads(Path(args.mechanism_file).read_text(encoding="utf-8"))) + json.loads(Path(request.mechanism_file).read_text(encoding="utf-8"))) settings = plan["evaluation_settings"] needed = min_pairs(1 - (1 - CONFIDENCE) / len(mechanism["expect"])) if settings.get("require_explanation") and needed > settings["repetitions"]: @@ -285,14 +296,14 @@ def session_command(args, *, ranking_policy_for, assess_packaged, task_source: P f"{len(mechanism['expect'])} expectations need {needed} repetitions under " f"--require-explanation; the campaign froze {settings['repetitions']}. " "Declare fewer expectations") - return optimization.evaluate_round( - root, candidate=None if final else args.candidate, - hypothesis="Independent final of the selected candidate" if final else args.hypothesis, - usage=args.usage_export, execute=executor.execute_ordinary, assess=assess, final=final, - reason=getattr(args, "reason", None), - strategy=getattr(args, "strategy", None), - alternatives=getattr(args, "alternative", None), - selection_reason=getattr(args, "selection_reason", None), - knowledge_refs=getattr(args, "knowledge_ref", None), + return state.evaluate_round( + root, candidate=None if final else request.candidate, + hypothesis="Independent final of the selected candidate" if final else request.hypothesis, + usage=request.usage_export, execute=executor.execute_ordinary, assess=assess, final=final, + reason=getattr(request, "reason", None), + strategy=getattr(request, "strategy", None), + alternatives=getattr(request, "alternative", None), + selection_reason=getattr(request, "selection_reason", None), + knowledge_refs=getattr(request, "knowledge_ref", None), mechanism=mechanism, ) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/manager/_state.py similarity index 96% rename from src/inferrsi/harness/optimization.py rename to src/inferrsi/harness/manager/_state.py index 7a73f57c6..119ffac01 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/manager/_state.py @@ -9,13 +9,14 @@ from functools import cache from pathlib import Path -from . import analyzer, attempt_recovery, evaluator, indexer -from .executor import TaskProtocolError, candidates -from .records import knowledge_capture, service_io -from .records.artifact_primitives import digest, file_lock, sha256 -from .records.atomic_json import atomic_write_json, durable_write_json -from .records.evidence import sanitized_text -from .records.usage import normalize_usage, usage_totals +from .. import analyzer, evaluator, indexer +from ..executor import TaskProtocolError, candidates +from ..records import knowledge_capture, service_io +from ..records.artifact_primitives import digest, file_lock, sha256 +from ..records.atomic_json import atomic_write_json, durable_write_json +from ..records.evidence import sanitized_text +from ..records.usage import normalize_usage, usage_totals +from . import _attempt_recovery as attempt_recovery def _locked(root): @@ -817,12 +818,12 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, return _settle(root, plan, state, pending, execution, assess) -def read_records(root: Path) -> tuple[dict, dict, dict]: +def read_session_records(root: Path) -> tuple[dict, dict, dict]: """Read one validated state for status, dashboard and reconstructable summaries.""" plan, state = _load(root, read_only=True) summary = _summary(root, plan, state) if plan.get("evaluation_mode") == "service_reuse": - from .records import service_observations + from ..records import service_observations state = service_observations.selection_view(state, state["attempts"]) return plan, state, summary @@ -953,7 +954,7 @@ def recover(root: Path, assess, *, confirm_domain_empty=False) -> dict: def _service_initialize(root, plan): - from . import executor + from .. import executor executor.validate_service_settings(plan["evaluation_settings"]) if ( @@ -1016,8 +1017,8 @@ def _service_runtime_matches(plan): def _service_load(root, plan, state, *, read_only=False): - from . import executor - from .records import service_observations + from .. import executor + from ..records import service_observations if not read_only and not _service_runtime_matches(plan): raise ValueError("Runtime package version changed; use the recorded version to resume") @@ -1051,7 +1052,8 @@ def _service_load(root, plan, state, *, read_only=False): def _service_profiling(root, attempt, *, published=None): - from . import executor, service_backfill + from .. import executor + from . import _service_backfill as service_backfill profile = ( published @@ -1064,7 +1066,7 @@ def _service_profiling(root, attempt, *, published=None): def _service_round_view(root, attempt, *, profiling=None): - from .records import service_observations + from ..records import service_observations if attempt["kind"] == "round": if profiling is None: @@ -1074,7 +1076,7 @@ def _service_round_view(root, attempt, *, profiling=None): def _service_account_capture(root, state, pending, execution): - from . import executor + from .. import executor capture = execution.get("capture") attempt_id = pending["attempt_id"] @@ -1187,7 +1189,7 @@ def _service_final_reason(plan, state, reference_reason, *, budget_time=None): def _service_status(root, plan, state): - from .records import service_observations + from ..records import service_observations reference_reason = _service_final_reference_reason(root, plan, state) now = time.time() @@ -1255,7 +1257,7 @@ def _service_status(root, plan, state): def _service_summary(root, plan, state, *, attempts=None, budget_time=None): - from .records import service_observations + from ..records import service_observations if attempts is None: attempts = [_service_round_view(root, attempt) for attempt in state["attempts"]] @@ -1301,7 +1303,7 @@ def _service_summary(root, plan, state, *, attempts=None, budget_time=None): def _service_settle(root, plan, state, pending, execution): - from . import executor + from .. import executor directory = service_io.safe_path(root, pending["path"]) checkpoint = execution.get("checkpoint") @@ -1470,12 +1472,12 @@ def _service_command_result(root, plan, state, execution): def _service_execute(root, directory, plan, state, deadline): - from . import executor + from .. import executor pending = state["pending"] if pending["kind"] != "refresh": return executor.execute_service_attempt(root, directory, plan, pending, deadline) - from .records import service_observations + from ..records import service_observations references, runs = [], [] started = time.monotonic() @@ -1545,7 +1547,7 @@ def _service_cleanup_confirmed(state, attempt): def _service_cleanup_receipt(root, state, path): - from .executor import process_group_empty + from ..executor import process_group_empty latest = state["pending"] or (state["attempts"][-1] if state["attempts"] else None) proof = service_io.read(path) @@ -1599,29 +1601,29 @@ def _service_cleanup_receipt(root, state, path): atomic_write_json(root / "state.json", state) -def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=None): +def service_command(root, request, *, ranking_policy_for=None, knowledge_reader=None): """Service-mode operations inside the shared controller's lock and control record.""" - from . import executor + from .. import executor with _locked(root): - action = args.session_action + action = request.action if action == "profile": - from . import service_backfill + from . import _service_backfill as service_backfill plan, _ = _control(root) indexer.resolve_frozen_ranking(plan, ranking_policy_for) - return service_backfill.run(root, args) + return service_backfill.run(root, request) plan, state = _load(root, read_only=action == "status") ranking_policy = indexer.resolve_frozen_ranking( plan, ranking_policy_for, read_only=action == "status" ) - after_final = getattr(args, "continue_after_final", None) - continuation_reason = getattr(args, "continuation_reason", None) + after_final = getattr(request, "continue_after_final", None) + continuation_reason = getattr(request, "continuation_reason", None) continuation = None if after_final is not None or continuation_reason is not None: if ( action != "round" or not after_final or not (continuation_reason or "").strip() - or any(getattr(args, name, None) is not None for name in ( + or any(getattr(request, name, None) is not None for name in ( "retry_of", "repair_reason", "repair_protocol", "cleanup_receipt", )) ): @@ -1635,8 +1637,8 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non if after_final != state["final"]["attempt_id"]: raise ValueError("Continuation must name the current failed final") continuation = {"after_final": after_final, "reason": continuation_reason.strip()} - if getattr(args, "cleanup_receipt", None) is not None: - _service_cleanup_receipt(root, state, args.cleanup_receipt) + if getattr(request, "cleanup_receipt", None) is not None: + _service_cleanup_receipt(root, state, request.cleanup_receipt) if action == "status": result = _service_status(root, plan, state) latest_by_round = { @@ -1653,12 +1655,12 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ] return result if action == "diagnose": - return _retain_diagnosis(root, plan, state, args.bottleneck, args.evidence) + return _retain_diagnosis(root, plan, state, request.bottleneck, request.evidence) if action == "recover": if state["pending"] and state["pending"]["kind"] == "profile": - from . import service_backfill + from . import _service_backfill as service_backfill - return service_backfill.recover(root, plan, state, args) + return service_backfill.recover(root, plan, state, request) if state["pending"] is None: atomic_write_json(root / "summary.json", _service_summary(root, plan, state)) return _service_command_result( @@ -1706,12 +1708,12 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ticket = _knowledge_request(plan, state) delivery = indexer.service_delivery( plan, context_id=ticket.context_id, binding=ticket.binding, reader=knowledge_reader, - query=args.query, relevance_method=args.relevance_method, limit=args.limit, - context_bytes=args.context_bytes, ranking_policy=ranking_policy, + query=request.query, relevance_method=request.relevance_method, limit=request.limit, + context_bytes=request.context_bytes, ranking_policy=ranking_policy, ) return _commit_knowledge(root, ticket, delivery) if action == "resume": - if not args.reason.strip() or state["pending"] is not None: + if not request.reason.strip() or state["pending"] is not None: raise ValueError( "Record investigation before resume; resolve pending execution first" ) @@ -1721,7 +1723,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non and state["recovery_events"] and ( state["recovery_events"][-1].get("kind") == "resume" - and state["recovery_events"][-1].get("reason") == args.reason + and state["recovery_events"][-1].get("reason") == request.reason ) ): return _service_status(root, plan, state) @@ -1733,14 +1735,14 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ): raise ValueError("Cannot resume without verified cleanup and usable references") state["recovery_events"].append( - {"kind": "resume", "reason": args.reason, "attempt_id": latest["attempt_id"]} + {"kind": "resume", "reason": request.reason, "attempt_id": latest["attempt_id"]} ) state["state"] = "active" atomic_write_json(root / "state.json", state) return _service_status(root, plan, state) - retry = getattr(args, "retry_of", None) - repair = getattr(args, "repair_reason", None) - repaired_protocol = getattr(args, "repair_protocol", None) + retry = getattr(request, "retry_of", None) + repair = getattr(request, "repair_reason", None) + repaired_protocol = getattr(request, "repair_protocol", None) if repaired_protocol and not retry: raise ValueError("Execution script repairs require an explicit --retry-of") old = next((item for item in state["attempts"] if item["attempt_id"] == retry), None) @@ -1805,21 +1807,21 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non raise ValueError("Refresh both incompatible performance references first") diagnosis = _diagnosis_reference(plan, state) number = old["round_number"] if old else len(state["rounds"]) + 1 - if number > plan["round_limit"] or not args.hypothesis.strip(): + if number > plan["round_limit"] or not request.hypothesis.strip(): raise ValueError("Round budget exhausted or hypothesis missing") - if args.candidate.is_symlink(): + if request.candidate.is_symlink(): raise ValueError("Candidate root cannot be symbolic") - source = args.candidate.resolve() + source = request.candidate.resolve() commit = executor.service_revision(source, plan["candidate_includes"]) candidate_id = f"candidate-{number:03d}" if not old: state["rounds"].append({"number": number, "terminal": False, "attempt_ids": []}) elif kind == "refresh": - if initial is None or parent is None or not args.reason.strip(): + if initial is None or parent is None or not request.reason.strip(): raise ValueError("Initial references and a change reason required") if len(state["rounds"]) >= plan["round_limit"]: raise ValueError("No round budget for current-conditions acceptance") - conditions = service_io.read(args.conditions) + conditions = service_io.read(request.conditions) executor.validate_service_conditions(conditions) if not old: if conditions == state["conditions"]: @@ -1838,7 +1840,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non source, commit = root / plan["baseline_path"], plan["baseline_revision"] candidate_id, number = "reference-refresh", None else: - if plan["round_mode"] == "up_to" and not (args.reason or "").strip(): + if plan["round_mode"] == "up_to" and not (request.reason or "").strip(): raise ValueError("Record why search stopped") admission = _service_final_reason( plan, state, _service_final_reference_reason(root, plan, state), @@ -1868,7 +1870,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non candidates.retain(repaired_protocol, directory / "protocol", fingerprint=False) protocol_path = relative + "/protocol" state["protocol_path"] = protocol_path - observations, raw = _usage_record(getattr(args, "usage_export", None), fingerprint=False) + observations, raw = _usage_record(getattr(request, "usage_export", None), fingerprint=False) if raw is not None: (directory / "agent-usage.json").write_bytes(raw) if kind == "round": @@ -1894,8 +1896,8 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non "source_repo": source_repo, "round_number": number, "started_at": time.time(), - "hypothesis": getattr(args, "hypothesis", None) - or getattr(args, "reason", None) + "hypothesis": getattr(request, "hypothesis", None) + or getattr(request, "reason", None) or "Initial baseline", "retry_of": retry, "repair_reason": repair, diff --git a/tests/apps/test_agent_sessions.py b/tests/apps/test_agent_sessions.py index c79c366e8..e5063b3e0 100644 --- a/tests/apps/test_agent_sessions.py +++ b/tests/apps/test_agent_sessions.py @@ -1,12 +1,13 @@ """Native handoffs retain identity and evidence without launching a second Agent.""" import json +import time from concurrent.futures import ThreadPoolExecutor import pytest from inferrsi.apps.cli import main -from inferrsi.harness import agent_sessions +from inferrsi.harness import manager @pytest.fixture @@ -14,7 +15,7 @@ def job(tmp_path): workspace = tmp_path / "workspace" workspace.mkdir() root = tmp_path / "job" - agent_sessions.prepare(root, prompt="Read the entry skill and produce a patch.", + manager.prepare_agent_session(root, prompt="Read the entry skill and produce a patch.", workspace=workspace, title="Native session control", max_seconds=120) return root @@ -26,8 +27,8 @@ def export(root, name, value): def bind(job): - agent_sessions.dispatch(job) - return agent_sessions.bind( + manager.dispatch_agent_session(job) + return manager.bind_agent_session( job, host="test-host", session_id="session-1", host_id="host-1", receipt=export(job, "creation.json", {"native_result": "session-1"}), ) @@ -41,12 +42,12 @@ def observation(job, state="running", **fields): def test_dispatch_can_be_consumed_only_once_even_after_interruption(job): - first = agent_sessions.dispatch(job) + first = manager.dispatch_agent_session(job) assert first["may_create"] is True assert first["handoff"]["context_mode"] == "fresh" assert "Read the entry skill" in first["handoff"]["prompt"] # Reopening the job after a caller crash never authorizes another launch. - second = agent_sessions.dispatch(job) + second = manager.dispatch_agent_session(job) assert second["may_create"] is False assert "handoff" not in second assert "without_relaunch" in second["next_action"] @@ -55,7 +56,7 @@ def test_dispatch_can_be_consumed_only_once_even_after_interruption(job): def test_concurrent_dispatch_allows_only_one_creation(job): def attempt(): try: - return agent_sessions.dispatch(job).get("may_create", False) + return manager.dispatch_agent_session(job).get("may_create", False) except OSError: # OS lock contention is an explicit refusal, not another launch. return False with ThreadPoolExecutor(max_workers=2) as executor: @@ -66,53 +67,53 @@ def test_binding_is_idempotent_but_cannot_be_replaced(job): first = bind(job) assert first["state"] == "running" receipt = export(job, "creation.json", {"native_result": "session-1"}) - same = agent_sessions.bind(job, host="test-host", session_id="session-1", + same = manager.bind_agent_session(job, host="test-host", session_id="session-1", host_id="host-1", receipt=receipt) assert same["native_session"] == first["native_session"] with pytest.raises(ValueError, match="another native session"): - agent_sessions.bind(job, host="test-host", session_id="session-2", receipt=receipt) + manager.bind_agent_session(job, host="test-host", session_id="session-2", receipt=receipt) wrong = observation(job, session_id="session-2") with pytest.raises(ValueError, match="bound native session"): - agent_sessions.record(job, observation=wrong) + manager.record_agent_session(job, observation=wrong) def test_definite_creation_failure_is_retained_without_inventing_a_session(job): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = export(job, "creation-error.json", { "host": "test-host", "session_id": None, "state": "failed", "creation_outcome": "not_created", "native_receipt": {"error": "invalid_project"}, }) - result = agent_sessions.record(job, observation=receipt) + result = manager.record_agent_session(job, observation=receipt) assert result["state"] == "failed" and result["native_session"] is None - assert agent_sessions.dispatch(job)["may_create"] is False + assert manager.dispatch_agent_session(job)["may_create"] is False def test_ambiguous_creation_error_cannot_be_treated_as_definite_failure(job): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = export(job, "creation-error.json", { "host": "test-host", "state": "failed", "native_receipt": {"error": "disconnected"}, }) with pytest.raises(ValueError, match="definite not_created"): - agent_sessions.record(job, observation=receipt) - assert agent_sessions.status(job)["state"] == "dispatching" + manager.record_agent_session(job, observation=receipt) + assert manager.agent_session_status(job)["state"] == "dispatching" def test_changed_entry_resource_prevents_dispatch(tmp_path): entry = tmp_path / "SKILL.md" entry.write_text("Original entry", encoding="utf-8") root = tmp_path / "job" - agent_sessions.prepare(root, prompt="Read the entry", workspace=tmp_path, + manager.prepare_agent_session(root, prompt="Read the entry", workspace=tmp_path, title="Frozen entry", max_seconds=120, frozen_inputs=[entry]) entry.write_text("Different procedure", encoding="utf-8") with pytest.raises(ValueError, match="Frozen Agent input"): - agent_sessions.dispatch(root) + manager.dispatch_agent_session(root) def test_native_completion_is_not_acceptance_and_deliverable_is_snapshotted(job): bind(job) artifact = job.parent / "workspace/candidate.py" artifact.write_text("result = 42\n", encoding="utf-8") - result = agent_sessions.record(job, observation=observation(job, "completed"), + result = manager.record_agent_session(job, observation=observation(job, "completed"), artifacts=[artifact]) assert result["state"] == "completed" assert result["task_acceptance"] == "not_assessed" @@ -120,29 +121,29 @@ def test_native_completion_is_not_acceptance_and_deliverable_is_snapshotted(job) retained = job / result["artifacts"][0]["path"] artifact.write_text("changed later", encoding="utf-8") assert retained.read_text() == "result = 42\n" - assert agent_sessions.status(job)["state"] == "completed" + assert manager.agent_session_status(job)["state"] == "completed" with pytest.raises(ValueError, match="terminal"): - agent_sessions.record(job, observation=observation(job)) + manager.record_agent_session(job, observation=observation(job)) retained.write_text("tampered", encoding="utf-8") with pytest.raises(ValueError, match="artifact changed"): - agent_sessions.status(job) + manager.agent_session_status(job) def test_usage_snapshots_are_not_summed_and_cannot_decrease(job): bind(job) for tokens in (100, 100, 120): - result = agent_sessions.record(job, observation=observation( + result = manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": tokens, "output_tokens": 20, "cached_input_tokens": 10}, )) assert result["usage"]["input_tokens"] == 120 assert result["usage"]["output_tokens"] == 20 with pytest.raises(ValueError, match="cannot decrease"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": 1, "output_tokens": 1}, )) with pytest.raises(ValueError, match="valid session_total"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="turn", usage={"input_tokens": 200, "output_tokens": 40}, )) @@ -153,15 +154,15 @@ def test_terminal_observations_allow_late_usage_and_preserve_deliveries(job): artifact.write_text("first delivery", encoding="utf-8") usage = {"input_tokens": 100, "output_tokens": 20} receipt = observation(job, "completed", usage_scope="session_total", usage=usage) - first = agent_sessions.record(job, observation=receipt, artifacts=[artifact]) - repeated = agent_sessions.record(job, observation=receipt, artifacts=[artifact]) + first = manager.record_agent_session(job, observation=receipt, artifacts=[artifact]) + repeated = manager.record_agent_session(job, observation=receipt, artifacts=[artifact]) assert repeated["usage"] == first["usage"] == usage assert repeated["last_observation"] != first["last_observation"] # Observations append; record is not a deduplication API. assert len(repeated["artifacts"]) == 2 artifact.write_text("later delivery", encoding="utf-8") latest_usage = {"input_tokens": 120, "output_tokens": 25} - result = agent_sessions.record(job, observation=observation( + result = manager.record_agent_session(job, observation=observation( job, "completed", usage_scope="session_total", usage=latest_usage), artifacts=[artifact]) assert result["usage"] == latest_usage assert result["state"] == "completed" and result["task_acceptance"] == "not_assessed" @@ -169,32 +170,32 @@ def test_terminal_observations_allow_late_usage_and_preserve_deliveries(job): assert (job / result["artifacts"][-1]["path"]).read_text() == "later delivery" for state in ("running", "failed", "cancelled"): with pytest.raises(ValueError, match="terminal"): - agent_sessions.record(job, observation=observation(job, state)) + manager.record_agent_session(job, observation=observation(job, state)) with pytest.raises(ValueError, match="cannot decrease"): - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, "completed", usage_scope="session_total", usage=usage)) - missing = agent_sessions.record(job, observation=observation(job, "completed")) + missing = manager.record_agent_session(job, observation=observation(job, "completed")) assert missing["usage"] is None assert missing["last_observed_usage"]["usage"] == latest_usage - assert agent_sessions.dispatch(job)["may_create"] is False + assert manager.dispatch_agent_session(job)["may_create"] is False def test_deadline_does_not_claim_that_native_host_was_stopped(job, monkeypatch): - monkeypatch.setattr(agent_sessions.time, "time", lambda: 10**12) - view = agent_sessions.status(job) + monkeypatch.setattr(time, "time", lambda: 10**12) + view = manager.agent_session_status(job) assert view["deadline_exceeded"] is True assert view["state"] == "prepared" assert view["deadline_enforcement"] == "native_host_not_enforced" with pytest.raises(ValueError, match="deadline exhausted"): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) def test_missing_final_usage_does_not_relabel_an_earlier_partial_meter(job): bind(job) - agent_sessions.record(job, observation=observation( + manager.record_agent_session(job, observation=observation( job, usage_scope="session_total", usage={"input_tokens": 100, "output_tokens": 20}, )) - result = agent_sessions.record(job, observation=observation(job, "completed")) + result = manager.record_agent_session(job, observation=observation(job, "completed")) assert result["usage"] is None assert result["last_observed_usage"]["usage"]["input_tokens"] == 100 assert result["last_observed_usage"]["receipt"] != result["last_observation"] @@ -210,7 +211,7 @@ def test_frozen_input_changes_are_rejected(job, name): else: path.write_text("changed", encoding="utf-8") with pytest.raises(ValueError, match="Frozen Agent"): - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) def test_unrelated_files_cannot_be_collected(job): @@ -218,7 +219,7 @@ def test_unrelated_files_cannot_be_collected(job): outside = job.parent / "outside.txt" outside.write_text("unrelated", encoding="utf-8") with pytest.raises(ValueError, match="declared workspace"): - agent_sessions.record(job, observation=observation(job), artifacts=[outside]) + manager.record_agent_session(job, observation=observation(job), artifacts=[outside]) def test_cli_prepares_and_dispatches_but_does_not_claim_a_launched_session(tmp_path, capsys): diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index d2fdbba65..1d198968a 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1,5 +1,6 @@ """Run the current-Agent protocol using real child processes and synthetic work.""" +import errno import hashlib import json import os @@ -14,8 +15,10 @@ from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import evaluator, executor, optimization, optimization_session -from inferrsi.harness.optimization import _locked +from inferrsi.harness import evaluator, executor, manager +from inferrsi.harness.manager import _runtime, session_runtime_identity +from inferrsi.harness.manager import _state as optimization +from inferrsi.harness.manager._state import _locked from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -90,6 +93,72 @@ def round_arguments(root, factor): "--candidate", str(candidate), "--hypothesis", f"Test factor {factor}"] +def test_manager_round_and_cli_status_share_the_committed_observation(session, capsys, monkeypatch): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + command = round_arguments(session, 2) + candidate = session / "work/candidate.py" + + def retained(*, lock_held=False): + return {path.relative_to(session): path.read_bytes() for path in session.rglob("*") + if path.is_file() and not (lock_held and path.name == ".session.lock")} + + def assess_while_cli_competes(root, directory, plan, execution): + before = retained(lock_held=True) + package_root = str(Path(manager.__file__).resolve().parents[3]) + child_path = os.pathsep.join(filter(None, [package_root, os.environ.get("PYTHONPATH")])) + competing = subprocess.run( + [sys.executable, "-m", "inferrsi", *command], cwd=session.parent, + env={**os.environ, "PYTHONPATH": child_path}, + capture_output=True, text=True, timeout=30, + ) + assert competing.returncode == 2, competing.stderr + assert f"[Errno {errno.EAGAIN}]" in competing.stderr, competing.stderr + assert retained(lock_held=True) == before + return executor.assess_packaged_task(root, directory, plan, execution) + + ports = {"assess_packaged": assess_while_cli_competes, + "ranking_policy_for": managed_ranking_policy} + result = manager.run_session( + manager.EvaluateSessionRound( + session=session, candidate=candidate, hypothesis="Test factor 2", + ), + **ports, + ) + observation = result["latest_observation"] + assert observation["assessment"]["score"] == 2 + assert (session / "calls.log").read_text().splitlines() == ["2"] + + before = retained() + instant = time.time() + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: instant)) + direct = manager.run_session(manager.SessionStatus(session=session), **ports) + assert main(["benchmarks", "session", "status", "--session", str(session)]) == 0 + assert json.loads(capsys.readouterr().out) == direct + plan, state, _ = manager.read_session_records(session) + assert plan["round_limit"] == 3 and len(state["rounds"]) == 1 + assert direct["latest_observation"] == observation + assert retained() == before + + +@pytest.mark.parametrize(("field", "value"), [ + ("rounds", True), ("rounds", False), ("rounds", 1.5), ("rounds", "2"), + ("max_minutes", float("nan")), ("max_minutes", 1e308), + ("evaluation_timeout_seconds", 10**400), ("final_reserve_seconds", -1), +]) +def test_manager_rejects_invalid_budget_before_creating_session(task, tmp_path, field, value): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + root = tmp_path / "new-session" + budget = {"rounds": 3, "max_minutes": 5, "evaluation_timeout_seconds": 15, field: value} + request = manager.StartBenchmarkSession(session=root, task=task.name, evaluation_args="", + condition="test", **budget) + with pytest.raises(ValueError, match="budget"): + manager.run_session(request, task_source=task, ranking_policy_for=managed_ranking_policy, + assess_packaged=executor.assess_packaged_task) + assert not root.exists() + + def test_started_task_uses_frozen_protocol_without_registry(session, capsys, monkeypatch): def unavailable(*args): raise AssertionError("The running campaign must not rediscover its task") @@ -760,14 +829,15 @@ def test_child_system_exit_settles_as_a_protocol_failure( ]) def test_reserve_status_agrees_with_final_eligibility(task, tmp_path, capsys, monkeypatch, mode, rounds, can_finalize): + from inferrsi.apps.cli import _session_request from inferrsi.apps.cli.arguments import parser from inferrsi.knowledge.ranking_policy import managed_ranking_policy root = tmp_path / "session" args = parser().parse_args(start_args(task, root)) args.round_mode = mode - optimization_session.session_command( - args, ranking_policy_for=managed_ranking_policy, task_source=task, + manager.run_session( + _session_request(args), ranking_policy_for=managed_ranking_policy, task_source=task, assess_packaged=executor.assess_packaged_task, ) diagnose(root, capsys) @@ -1377,7 +1447,7 @@ def test_unbound_benchmark_cannot_borrow_another_checkout( ): from inferrsi.apps.integrations import external_channels from inferrsi.apps.views.dashboard import dashboard_snapshot - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization origin = tmp_path / "outside-git" origin.mkdir() @@ -1428,7 +1498,7 @@ def legacy_plan(root, plan): def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor() -> None: from importlib.resources import files - identity = optimization_session._runtime_identity() + identity = session_runtime_identity() root = Path(str(files("inferrsi"))) assert "harness/executor/local_process.py" in identity # #412 R2: the Harness-owned primitives replace infra.artifacts in six modules. @@ -1469,8 +1539,8 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo def test_runtime_identity_rejects_computed_dynamic_imports(tmp_path, monkeypatch): - identity = optimization_session._runtime_identity() - installed = Path(str(optimization_session.files("inferrsi"))) + identity = session_runtime_identity() + installed = Path(str(_runtime.files("inferrsi"))) for name in identity: target = tmp_path / name target.parent.mkdir(parents=True, exist_ok=True) @@ -1482,9 +1552,9 @@ def test_runtime_identity_rejects_computed_dynamic_imports(tmp_path, monkeypatch " from importlib import import_module as load\n" " return load('inferrsi.' + name)\n" ) - monkeypatch.setattr(optimization_session, "files", lambda _: tmp_path) + monkeypatch.setattr(_runtime, "files", lambda _: tmp_path) with pytest.raises(ValueError, match="Session runtime import must name a literal module"): - optimization_session._runtime_identity() + session_runtime_identity() PRE_SERVING = (Path(__file__).resolve().parents[1] / "fixtures" / "optimization-session" @@ -1550,7 +1620,7 @@ def test_a_session_planned_before_a_runtime_change_is_refused_and_left_unchanged assert receipt["status"] == "completed" and receipt["returncode"] == 0 assert before["calls.log"].splitlines() == [b"2"] assert removed_file in json.loads(before["plan.json"])["runtime_identity"] - assert removed_file not in optimization_session._runtime_identity() + assert removed_file not in session_runtime_identity() for action in ("status", "recover"): output = _refused(session, capsys, action) assert "Optimization runtime changed" in output.out + output.err, action @@ -1565,10 +1635,10 @@ def test_changed_transitive_runtime_bytes_refuse_an_untouched_plan( installed = Path(str(files("inferrsi"))) copy = tmp_path / "install" / "inferrsi" - for name in optimization_session._runtime_identity(): + for name in session_runtime_identity(): (copy / name).parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(installed / name, copy / name) - monkeypatch.setattr(optimization_session, "files", lambda package: copy) + monkeypatch.setattr(_runtime, "files", lambda package: copy) path = session / "plan.json" before = path.read_bytes() capsys.readouterr() @@ -1621,10 +1691,10 @@ def test_pinned_pre_move_wheel_recovers_its_original_plan( sys.path.insert(0, sys.argv[1]) from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import optimization_session registry._library_root = lambda: Path(sys.argv[2]) arguments = sys.argv[3:] if arguments[0] == 'interrupt': + from inferrsi.harness import optimization_session # pinned pre-move wheel arguments.pop(0) execute = optimization_session._session_execute def interrupt(*args): diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index 1a8621f67..dcb86c979 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -9,7 +9,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard_data import load_dashboard from inferrsi.apps.views.optimization_chart import render_result -from inferrsi.harness.optimization import read_records +from inferrsi.harness.manager import read_session_records from inferrsi.harness.records.artifact_primitives import digest from tests.fixtures.diagnosis import diagnosis_args @@ -121,7 +121,7 @@ def test_confirmed_mechanism_is_adopted_and_rechecked_at_final(project, capsys): assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["final"]["assessment"]["explanation"]["status"] == "explained" assert state["final"]["assessment"]["verdict"] == "PASS" @@ -142,7 +142,7 @@ def test_unexplained_gain_is_not_adopted_and_search_continues( assessment = submit(project, capsys, FUSED, mechanism) assert assessment["explanation"]["status"] == status assert assessment["verdict"] == verdict and assessment["eligible"] is False - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["best"]["kind"] == "baseline" and state["state"] == "active" assessment = submit(project, capsys, FUSED, FUSION) assert assessment["verdict"] == "PASS" @@ -167,7 +167,7 @@ def test_paired_decision_is_inconclusive_within_noise_without_blocking(project, assert assessment["verdict"] == "INCONCLUSIVE" and assessment["reason"] == "within_noise" assert assessment["eligible"] is False assert assessment["paired_statistics"]["report_only"] is False - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["state"] == "active" and state["best"]["kind"] == "baseline" assessment = submit(project, capsys, FUSED) assert assessment["verdict"] == "PASS" @@ -262,7 +262,7 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, (repo / "config.json").write_text(json.dumps( {"side": "baseline", "series": [5.0, *baseline]}), encoding="utf-8") assert start(project, capsys, "--decision", "paired", repetitions=9) == 0 - plan, _, _ = read_records(root) + plan, _, _ = read_session_records(root) assert plan["selection"] == {"direction": "maximize", "initial_score": 1.0, "metric": "paired_median_speedup"} first = submit(project, capsys, {"side": "candidate", "series": [5.0, *outlier]}) @@ -270,7 +270,7 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, assert first["point_estimate"]["improvement_pct"] == pytest.approx(-50) assert first["paired_statistics"]["interval"] == pytest.approx([1 / 0.9, 1 / 0.9]) assert first["verdict"] == "PASS" and first["score"] == pytest.approx(1 / 0.9) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["best"]["kind"] == "candidate" assert state["rounds"][0]["selection"] == { "outcome": "adopted", "metric": "paired_median_speedup", @@ -279,14 +279,14 @@ def test_paired_decision_also_selects_the_candidate_that_final_retests(project, second = submit(project, capsys, {"side": "candidate", "series": [5.0, *(b / 1.05 for b in baseline)]}) assert second["verdict"] == "PASS" and second["score"] == pytest.approx(1.05) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["rounds"][1]["selection"]["outcome"] == "not_better_than_best" assert state["best"]["candidate_id"] == state["rounds"][0]["candidate_id"] # Final retests the retained copy of the selected candidate, not the working tree. assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) assert state["final"]["assessment"]["verdict"] == "PASS" assert summary["selected_candidate"]["candidate_id"] == state["rounds"][0]["candidate_id"] assert summary["optimization_speedup"] == pytest.approx(1 / 0.9) @@ -329,7 +329,7 @@ def test_unavailable_paired_statistics_neither_block_nor_borrow_a_point_score( assert first["score"] is None and first["speedup"] is None assert first["score_basis"] is None assert first["point_estimate"]["speedup"] == pytest.approx(10 / 9) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["best"]["kind"] == "baseline" assert state["rounds"][0]["selection"]["outcome"] == "not_eligible" second = submit(project, capsys, {"side": "candidate", "series": [*plain, *plain, *huge]}) @@ -337,7 +337,7 @@ def test_unavailable_paired_statistics_neither_block_nor_borrow_a_point_score( assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) final = state["final"]["assessment"] assert state["state"] == "completed" and final["verdict"] == "INCONCLUSIVE" assert final["score"] is None and summary["optimization_speedup"] is None @@ -367,7 +367,7 @@ def test_extreme_paired_speedup_settles_without_a_nonfinite_improvement(project, assert assessment["score"] == pytest.approx(1e-307) assert assessment["improvement_pct"] is None assert assessment["verdict"] == "INCONCLUSIVE" and assessment["reason"] == "within_noise" - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["pending"] is None @@ -387,7 +387,7 @@ def test_unrepresentable_point_estimate_does_not_block_a_paired_decision(project assessment = submit(project, capsys, {"metric": 1e307}) assert assessment["point_estimate"] == {"improvement_pct": None, "speedup": 1e307} assert assessment["verdict"] == "PASS" and assessment["score"] == pytest.approx(1e307) - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["best"]["kind"] == "candidate" @@ -413,7 +413,7 @@ def test_uncheckable_declaration_is_rejected_before_it_spends_a_round(project, c assert start(project, capsys, "--require-explanation", repetitions=6) == 0 with pytest.raises(SystemExit): submit(project, capsys, FUSED, FUSION) - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["rounds"] == [] and state["state"] == "active" one = {"mechanism": "Fewer launches", "expect": [ {"counter": "kernel_launches", "direction": "decrease"}]} @@ -434,7 +434,7 @@ def test_invalid_mechanism_is_rejected_before_execution(project, capsys): with pytest.raises(SystemExit): submit(project, capsys, FUSED, {"mechanism": "x", "expect": [ {"region": "norm", "direction": "faster"}]}) - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["rounds"] == [] @@ -510,7 +510,7 @@ def forge_then_crash(root, directory, plan, deadline): monkeypatch.setattr(executor, "execute_ordinary", original) assert main(["campaign", "recover", "--directory", str(project[3])]) == 0 capsys.readouterr() - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) record = state["rounds"][-1] assert record["mechanism_unverified_after_recovery"] is True assert record["assessment"]["explanation"]["status"] == "not_declared" @@ -531,7 +531,7 @@ def explode(*args, **kwargs): assert assessment["verdict"] == "PASS" and assessment["eligible"] is True assert assessment["profile_evidence"]["status"] == "unavailable" assert assessment["explanation"]["status"] == "unverifiable" - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["state"] == "active" and state["best"]["kind"] == "candidate" @@ -552,7 +552,7 @@ def test_overflowing_even_medians_leave_a_recorded_inconclusive_round(project, c assert assessment["metrics"]["candidate"] is None assert assessment["paired_statistics"]["status"] == "unavailable" assert assessment["verdict"] == "INCONCLUSIVE" and assessment["score"] is None - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "active" and state["pending"] is None @@ -569,7 +569,7 @@ def test_point_decision_project_rounds_must_still_be_scored(project, capsys, mon assert main(["campaign", "round", "--directory", str(root), "--candidate", str(repo), "--hypothesis", "Scoreless point-mode control"]) == 2 capsys.readouterr() - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["state"] == "blocked" and state["pending"] is None assessment = state["rounds"][0]["assessment"] assert assessment["status"] == "infrastructure_failure" and assessment["score"] is None @@ -595,7 +595,7 @@ def test_scoreless_baseline_final_reports_no_speedup_in_the_delivery(project, ca assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic unavailable statistics control"]) == 0 view = json.loads(capsys.readouterr().out) - _, state, summary = read_records(root) + _, state, summary = read_session_records(root) assert state["best"]["kind"] == "baseline" assert state["final"]["assessment"]["score"] is None assert summary["optimization_speedup"] is None @@ -624,7 +624,7 @@ def test_strategy_knowledge_refs_and_mechanism_are_kept_together(project, capsys "--knowledge-ref", refs[0], "--knowledge-ref", refs[1], "--mechanism-file", str(declaration)]) == 0 capsys.readouterr() - _, state, _ = read_records(root) # Revalidates the round against its observation. + _, state, _ = read_session_records(root) # Revalidates the round against its observation. record = state["rounds"][0] assert record["strategy"] == "Fuse kernels" and record["knowledge_refs"] == refs assert record["diagnosis_id"] == state["diagnoses"][0]["id"] @@ -642,6 +642,6 @@ def test_strategy_knowledge_refs_and_mechanism_are_kept_together(project, capsys assert main(["campaign", "final", "--directory", str(root), "--reason", "Synthetic search completed"]) == 0 capsys.readouterr() - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) assert state["final"]["mechanism"] == FUSION assert state["final"]["assessment"]["explanation"]["status"] == "explained" diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 45fa3771b..a181c91dc 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -10,7 +10,7 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard -from inferrsi.harness.optimization import read_records +from inferrsi.harness.manager import read_session_records from tests.fixtures.diagnosis import diagnosis_args from tests.fixtures.session_process import kill_controller, target_python @@ -143,13 +143,13 @@ def find_spec(self, fullname, path=None, target=None): raise AssertionError('Ordinary optimization imported ' + fullname) sys.meta_path.insert(0, NoBenchmark()) from inferrsi.apps.cli import main -from inferrsi.harness.optimization import read_records +from inferrsi.harness.manager import read_session_records config = json.loads(sys.stdin.read()) assert main(config['start']) == 0 Path(config['repo'], 'config.json').write_text('{"metric":20}', encoding='utf-8') for command in config['commands']: assert main(command) == 0 -plan, state, summary = read_records(Path(config['root'])) +plan, state, summary = read_session_records(Path(config['root'])) assert not any(name.startswith('benchmark/') for name in plan['runtime_identity']) assert state['final']['assessment']['verdict'] == 'PASS' assert summary['optimization_speedup'] == 2 @@ -197,7 +197,7 @@ def test_project_runs_shared_rounds_and_final_from_retained_multifile_candidate( assert delivery["completion"]["status"] == "completed" assert delivery["outcome"]["kind"] == "improved" assert delivery["acceptance"]["delivery_accepted"] is True - plan, state, summary = read_records(root) + plan, state, summary = read_session_records(root) assert plan["round_mode"] == "up_to" and summary["completed_rounds"] == 1 assert state["final"]["assessment"]["verdict"] == "PASS" assert summary["optimization_speedup"] == 2 @@ -278,7 +278,7 @@ def test_dashboard_rejects_identical_bytes_when_earlier_round_remains_best( assert submit(project, capsys, 20)[0] == 0 assert submit(project, capsys, 20)[0] == 0 root = project[3] - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) first, second = state["rounds"] assert first["candidate_sha256"] == second["candidate_sha256"] assert second["assessment"]["quality_passed"] is not quality_failed @@ -345,7 +345,7 @@ def unavailable(*args, **kwargs): def test_cannbot_timeout_keeps_local_ranking_and_final_budget(project, capsys, monkeypatch): from inferrsi.apps.integrations.cannbot import project as channel from inferrsi.apps.integrations.cannbot.read_worker import _WORKER_CLEANUP_SECONDS - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization source, protocol, instructions, root = project (source / ".git").mkdir() @@ -436,7 +436,7 @@ def test_changed_retained_assessment_is_rejected(project, capsys): path = project[3] / view["latest_observation"]["path"] / "observation.json" path.write_text("{}", encoding="utf-8") with pytest.raises(ValueError, match="assessment record changed"): - read_records(project[3]) + read_session_records(project[3]) def test_candidate_directory_identity_includes_new_files(tmp_path): @@ -475,19 +475,19 @@ def test_record_read_verifies_each_distinct_candidate_again_on_next_read(project start(project, capsys) root = project[3] with patch.object(candidates, "identity", wraps=candidates.identity) as identity: - read_records(root) + read_session_records(root) assert [call.args[0] for call in identity.call_args_list] == [root / "frozen/baseline"] submit(project, capsys, 20) with patch.object(candidates, "identity", wraps=candidates.identity) as identity: - _, state, _ = read_records(root) + _, state, _ = read_session_records(root) selected = root / state["best"]["path"] paths = [call.args[0] for call in identity.call_args_list] assert paths == [root / "frozen/baseline", selected] (selected / "config.json").write_text("{}") with pytest.raises(ValueError, match="Selected candidate changed"): - read_records(root) + read_session_records(root) def test_shared_candidate_path_still_checks_each_recorded_digest(project, capsys): @@ -505,7 +505,7 @@ def test_shared_candidate_path_still_checks_each_recorded_digest(project, capsys with patch.object(candidates, "identity", wraps=candidates.identity) as identity: with pytest.raises(ValueError, match="Selected candidate changed"): - read_records(root) + read_session_records(root) identity.assert_called_once_with(root / "frozen/baseline") @@ -515,7 +515,7 @@ def test_frozen_input_additions_are_rejected_even_after_candidate_wins(project, submit(project, capsys, 20) (project[3] / "frozen" / relative).write_text("{}", encoding="utf-8") with pytest.raises(ValueError, match="file set"): - read_records(project[3]) + read_session_records(project[3]) def test_bad_candidate_exception_is_classified_by_frozen_wrapper(project, capsys): @@ -543,7 +543,7 @@ def test_bad_candidate_exception_is_classified_by_frozen_wrapper(project, capsys assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Keep the measured best after a rejected experiment"]) == 0 capsys.readouterr() - _, state, summary = read_records(project[3]) + _, state, summary = read_session_records(project[3]) assert state["final"]["candidate_sha256"] == before["best"]["sha256"] assert summary["final_assessment"]["verdict"] == "PASS" assert failed_record.read_bytes() == failed_bytes @@ -572,7 +572,7 @@ def test_project_cwd_logs_leave_frozen_inputs_usable(project, capsys): capsys.readouterr() assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Scratch output control complete"]) == 0 - assert read_records(project[3])[2]["optimization_speedup"] == 2 + assert read_session_records(project[3])[2]["optimization_speedup"] == 2 def test_project_execution_copy_source_changes_are_rejected(project, capsys): @@ -620,13 +620,13 @@ def drift(root, *args): main(["campaign", operation, "--directory", str(project[3])]) assert json.loads(capsys.readouterr().out)["state"] == "blocked" with pytest.raises(ValueError, match="file set"): - read_records(project[3]) # Rejected data cannot become a valid report. + read_session_records(project[3]) # Rejected data cannot become a valid report. def test_final_freezes_elapsed_time_and_dashboard_redacts_private_text( project, capsys, monkeypatch, ): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization start(project, capsys, extra=("--condition", "token=condition-secret")) repo, _, _, root = project @@ -637,9 +637,9 @@ def test_final_freezes_elapsed_time_and_dashboard_redacts_private_text( assert main(["campaign", "final", "--directory", str(root), "--reason", "token=stop-secret"]) == 0 assert not json.loads(capsys.readouterr().out)["can_finalize"] - original = read_records(root)[2]["wall_elapsed_seconds"] + original = read_session_records(root)[2]["wall_elapsed_seconds"] monkeypatch.setattr(optimization.time, "time", lambda: 10**12) - assert read_records(root)[2]["wall_elapsed_seconds"] == original + assert read_session_records(root)[2]["wall_elapsed_seconds"] == original html = render_dashboard(dashboard_snapshot(root)) for private in ("condition-secret", "hypothesis-secret", "stop-secret", "C:/private/file"): assert private not in html @@ -670,11 +670,11 @@ def test_dashboard_shows_failed_independent_final_separately_from_search( def test_final_reserve_blocks_search_but_allows_final(project, capsys, monkeypatch): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization start(project, capsys) submit(project, capsys, 20) - plan, state, _ = read_records(project[3]) + plan, state, _ = read_session_records(project[3]) monkeypatch.setattr(optimization.time, "time", lambda: state["deadline"] - 10) with pytest.raises(SystemExit): submit(project, capsys, 30) @@ -704,7 +704,7 @@ def test_assessment_reports_paired_statistics_without_changing_the_verdict( assert main(["campaign", "final", "--directory", str(project[3]), "--reason", "Synthetic search done"]) == 0 capsys.readouterr() - _, state, summary = read_records(project[3]) + _, state, summary = read_session_records(project[3]) final = state["final"]["assessment"] assert final["verdict"] == "PASS" and summary["optimization_speedup"] == 2 assert final["paired_statistics"]["gate_relation"] == "above_gate" @@ -720,7 +720,7 @@ def test_unreachable_gate_keeps_the_original_fail_and_strict_json_records(projec assert assessment["verdict"] == "FAIL" and assessment["eligible"] is False paired = assessment["paired_statistics"] assert paired["gate_speedup"] is None and paired["gate_relation"] == "gate_unreachable" - json.dumps(read_records(project[3])[1], allow_nan=False) + json.dumps(read_session_records(project[3])[1], allow_nan=False) def test_records_without_paired_statistics_remain_readable(project, capsys, monkeypatch): @@ -738,7 +738,7 @@ def legacy_assess(*args, **kwargs): start(project, capsys) code, result = submit(project, capsys, 20) assert code == 0 and "paired_statistics" not in result["latest_observation"]["assessment"] - _, state, _ = read_records(project[3]) + _, state, _ = read_session_records(project[3]) assert state["best"]["kind"] == "candidate" snapshot = dashboard_snapshot(project[3]) assert snapshot["data"]["candidates"][0]["verdict"] == "PASS" diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index b286acd8c..c6bbff567 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -14,8 +14,9 @@ from inferrsi.apps.cli import main from inferrsi.apps.cli.arguments import parser from inferrsi.apps.delivery import project, read_bundle -from inferrsi.harness import executor, optimization +from inferrsi.harness import executor, manager from inferrsi.harness.executor.serving import _attempt +from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records import service_io from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings, submit from tests.fixtures.service_reuse import campaign as campaign @@ -63,7 +64,7 @@ def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): state["contexts"][0]["diagnosis_id"] = new["diagnosis"]["id"] state_path.write_text(json.dumps(state), encoding="utf-8") with pytest.raises(ValueError, match="Knowledge diagnosis differs from the retained capture"): - optimization.read_records(campaign["root"]) + optimization.read_session_records(campaign["root"]) def events(campaign, attempt): @@ -71,6 +72,28 @@ def events(campaign, attempt): return [json.loads(line) for line in path.read_text().splitlines()] +def test_manager_baseline_and_cli_status_share_one_service_attempt(campaign, monkeypatch): + from inferrsi.knowledge.ranking_policy import managed_ranking_policy + + call(campaign, "start") + root = campaign["root"] + ports = {"ranking_policy_for": managed_ranking_policy, + "assess_packaged": executor.assess_packaged_task} + measured = manager.run_session(manager.BaselineSession(session=root), **ports) + attempt = measured["latest_observation"] + assert attempt["kind"] == "baseline" and attempt["assessment"]["verdict"] == "PASS" + retained_events = events(campaign, attempt) + instant = time.time() + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: instant)) + direct = manager.run_session(manager.SessionStatus(session=root), **ports) + assert direct == call(campaign, "status") + assert direct["latest_observation"] == attempt + assert direct["allocated_rounds"] == 0 + _, state, _ = manager.read_session_records(root) + assert [record["attempt_id"] for record in state["attempts"]] == [attempt["attempt_id"]] + assert events(campaign, attempt) == retained_events + + def test_one_service_order_and_independent_final_ignores_workspace(campaign): begin(campaign) result = submit(campaign, version="accepted", a=95, b=102) @@ -97,7 +120,7 @@ def test_one_service_order_and_independent_final_ignores_workspace(campaign): assert final["final"]["assessment"]["verdict"] == "PASS" assert {row["version"] for row in events(campaign, final["final"])} == {"accepted"} assert "profile" not in [row["stage"] for row in events(campaign, final["final"])] - service_io.no_fingerprints(optimization.read_records(campaign["root"])[2]) + service_io.no_fingerprints(optimization.read_session_records(campaign["root"])[2]) assert call(campaign, "status")["state"] == "completed" # Call the projection directly so schema errors are visible before CLI redaction. project(campaign["root"], export_id="service-projection") @@ -1044,11 +1067,11 @@ def test_round_usage_export_is_retained_without_fingerprint(campaign): "--usage-export", export, ) - summary = optimization.read_records(campaign["root"])[2] + summary = optimization.read_session_records(campaign["root"])[2] assert summary["usage"]["total_tokens"] == 12 assert result["latest_observation"]["observations"]["usage_source"] == {"kind": "caller_export"} call(campaign, "recover") - assert optimization.read_records(campaign["root"])[2]["usage"]["total_tokens"] == 12 + assert optimization.read_session_records(campaign["root"])[2]["usage"]["total_tokens"] == 12 def test_exact_round_policy_and_legacy_argument_validation(campaign): @@ -1354,7 +1377,7 @@ def test_backfill_after_final_preserves_original_evidence_and_selection(campaign final = call(campaign, "final", "--reason", "Search complete") original_files.append(root / final["final"]["path"] / "observation.json") originals = {p: p.read_bytes() for p in original_files} - usage = optimization.read_records(root)[2]["usage"] + usage = optimization.read_session_records(root)[2]["usage"] published = call(campaign, "profile", "--round", "1") assert published["target_attempt_id"] == attempt["attempt_id"] @@ -1414,7 +1437,7 @@ def interrupt_capture(command, *args, **kwargs): assert status["best"] == final["best"] and status["final"] == final["final"] assert status["best"]["profile"] == inline assert status["allocated_rounds"] == final["allocated_rounds"] - _, state_view, summary = optimization.read_records(root) + _, state_view, summary = optimization.read_session_records(root) assert state_view["best"] == status["best"] assert summary["usage"] == usage current = next(r for r in summary["attempts"] if r["attempt_id"] == attempt["attempt_id"]) @@ -1498,7 +1521,9 @@ def test_legacy_round_availability_is_derived_without_changing_history(campaign, ) assert obs.read_bytes() == old_bytes if damage is None: - final = SimpleNamespace(session_action="final", reason="done") + from inferrsi.harness.manager import FinalizeSession + + final = FinalizeSession(session=root, reason="done") with pytest.raises(ValueError, match="Runtime package version changed"): optimization.service_command(root, final) @@ -1691,7 +1716,7 @@ def test_effective_deadline_after_profiling_crosses_original_wall_deadline(campa assert first["latest_observation"]["elapsed_seconds"] >= 620 state = service_io.read(root / "state.json") assert clock.time() > state["deadline"] - assert optimization.read_records(root)[2]["wall_elapsed_seconds"] >= 620 + assert optimization.read_session_records(root)[2]["wall_elapsed_seconds"] >= 620 status = call(campaign, "status") assert 0 < status["remaining_search_seconds"] < status["remaining_seconds"] assert status["remaining_seconds"] - status["remaining_search_seconds"] == pytest.approx(30) diff --git a/tests/apps/test_result_delivery.py b/tests/apps/test_result_delivery.py index 34e490929..f7e260cea 100644 --- a/tests/apps/test_result_delivery.py +++ b/tests/apps/test_result_delivery.py @@ -13,7 +13,7 @@ from inferrsi.apps.storage import archive from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 from inferrsi.apps.storage.result import preparation_result -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization from tests.fixtures.diagnosis import diagnosis_evidence @@ -233,7 +233,7 @@ def test_damaged_evidence_does_not_rewrite_history_or_accept_different_code(tmp_ assert result["completion"]["status"] == "completed" assert "Current gaps" in (output / "report.md").read_text() with pytest.raises((ValueError, FileNotFoundError)): - optimization.read_records(root) # Normal execution reader remains strict. + optimization.read_session_records(root) # Normal execution reader remains strict. @pytest.mark.parametrize("verdict", ["PASS", "FAIL", "INCONCLUSIVE"]) @@ -776,17 +776,17 @@ def test_offline_html_remains_readable_without_scripts_or_network( @pytest.fixture def standalone_native_usage(tmp_path, request): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager job = tmp_path / "agent-job" frozen_input = tmp_path / "native-task.txt" frozen_input.write_text("Frozen synthetic task", encoding="utf-8") - agent_sessions.prepare(job, prompt="Synthetic Benchmark task", workspace=tmp_path, + manager.prepare_agent_session(job, prompt="Synthetic Benchmark task", workspace=tmp_path, title="Synthetic", max_seconds=600, frozen_inputs=(frozen_input,)) - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) creation = tmp_path / "creation.json" atomic_write_json(creation, {"synthetic_creation": True}) - agent_sessions.bind(job, host="synthetic", session_id="native-session", receipt=creation) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=creation) root = make_campaign(tmp_path, benchmark=True, usage=True, metrics_policy=getattr(request, "param", None)) control = state(root) @@ -807,11 +807,11 @@ def standalone_native_usage(tmp_path, request): def record_native_usage(job, observation): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager path = job.parent / "terminal.json" atomic_write_json(path, observation) - agent_sessions.record(job, observation=path) + manager.record_agent_session(job, observation=path) def test_single_benchmark_complete_native_usage_through_export_cli( @@ -893,14 +893,16 @@ def test_single_benchmark_incomplete_or_mismatched_receipt_stays_unknown( observation["state"] = "running" elif fault == "workspace": # A different valid job cannot lend its counters to this campaign. - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager other = tmp_path / "other" other.mkdir() job = tmp_path / "other-job" - agent_sessions.prepare(job, prompt="Other", workspace=other, title="Other", max_seconds=600) - agent_sessions.dispatch(job) - agent_sessions.bind(job, host="synthetic", session_id="native-session", + manager.prepare_agent_session( + job, prompt="Other", workspace=other, title="Other", max_seconds=600 + ) + manager.dispatch_agent_session(job) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=tmp_path / "creation.json") record_native_usage(job, observation) _, result, _ = delivery.project(root, export_id="incomplete-usage", agent_job=job) @@ -949,33 +951,33 @@ def test_native_job_preserves_unsupported_policy_reason(standalone_native_usage) def test_native_frozen_input_change_after_status_prevents_complete_export( standalone_native_usage, tmp_path, monkeypatch, ): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager root, job, observation = standalone_native_usage record_native_usage(job, observation) - original = agent_sessions.status + original = manager.agent_session_status def changed_after_read(path): host = original(path) (tmp_path / "native-task.txt").write_text("Changed after status", encoding="utf-8") return host - monkeypatch.setattr(agent_sessions, "status", changed_after_read) + monkeypatch.setattr(manager, "agent_session_status", changed_after_read) output = tmp_path / "changed-native-input" result = delivery.export_bundle(root, output, agent_job=job) assert result["status"] == "error" and not output.exists() def test_progress_without_native_observation_preserves_campaign_usage_source(tmp_path): - from inferrsi.harness import agent_sessions + from inferrsi.harness import manager job = tmp_path / "job" - agent_sessions.prepare(job, prompt="Synthetic", workspace=tmp_path, + manager.prepare_agent_session(job, prompt="Synthetic", workspace=tmp_path, title="Synthetic", max_seconds=600) - agent_sessions.dispatch(job) + manager.dispatch_agent_session(job) receipt = tmp_path / "creation.json" atomic_write_json(receipt, {"synthetic_creation": True}) - agent_sessions.bind(job, host="synthetic", session_id="native-session", receipt=receipt) + manager.bind_agent_session(job, host="synthetic", session_id="native-session", receipt=receipt) root = make_campaign(tmp_path, benchmark=True, usage=True, final=False) _, original, _ = delivery.project(root, export_id="progress-original") _, result, _ = delivery.project(root, export_id="progress-native", agent_job=job) diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index ca020fe50..1391378ee 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -9,8 +9,8 @@ from inferrsi.apps import cli from inferrsi.apps.cli import main -from inferrsi.harness import optimization from inferrsi.harness.executor import _task_protocol +from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records import service_io from inferrsi.knowledge import ranking_policy from inferrsi.knowledge.knowledge_operations import KnowledgeReader diff --git a/tests/benchmark/test_benchmark_compare.py b/tests/benchmark/test_benchmark_compare.py index a310a665d..1e77f936b 100644 --- a/tests/benchmark/test_benchmark_compare.py +++ b/tests/benchmark/test_benchmark_compare.py @@ -14,8 +14,8 @@ from inferrsi.apps.cli import main from inferrsi.apps.workflows import benchmark_compare as compare from inferrsi.benchmark import registry -from inferrsi.harness import agent_sessions -from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.harness import manager +from inferrsi.harness.manager import session_runtime_identity @pytest.fixture @@ -25,7 +25,7 @@ def experiment(tmp_path, monkeypatch, capsys, request): from importlib.resources import files actual = Path(str(files("inferrsi"))) - for name in _runtime_identity(): + for name in session_runtime_identity(): target = source / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(actual / name, target) @@ -106,7 +106,7 @@ def finish(experiment, trial, *, factor=2, final=True, model="synthetic-model", session_id = session_id or legacy_session_id or trial if legacy_session_id: suffix = "" if legacy_attempt == 1 else f"-attempt-{legacy_attempt:03d}" - agent_sessions.bind(root / "jobs" / (trial + suffix), host="synthetic", + manager.bind_agent_session(root / "jobs" / (trial + suffix), host="synthetic", session_id=session_id, receipt=receipt) else: operation(experiment, "bind", trial, "--host", "synthetic", "--session-id", session_id, @@ -349,18 +349,18 @@ def test_new_metrics_missing_tokens_does_not_remove_valid_performance(experiment def test_boolean_child_schema_cannot_upgrade_unknown_tokens(experiment, monkeypatch): - from inferrsi.harness import optimization_session + from inferrsi.harness import manager - original = optimization_session.session_command + original = manager.run_session - def boolean_policy(args, **kwargs): - if args.session_action == "start": + def boolean_policy(request, **kwargs): + if request.action == "start": metadata = kwargs["report_metadata"]["benchmark_metrics"] kwargs["report_metadata"] = {"benchmark_metrics": { **metadata, "metrics_schema_version": True}} - return original(args, **kwargs) + return original(request, **kwargs) - monkeypatch.setattr(optimization_session, "session_command", boolean_policy) + monkeypatch.setattr(manager, "run_session", boolean_policy) trial = experiment[1]["trials"][0]["id"] _, result = finish(experiment, trial, token_coverage=True) assert result["benchmark_metrics"]["token_usage"]["total_tokens"] is None @@ -1086,7 +1086,8 @@ def test_repeated_collect_keeps_first_record_and_refuses_retry(experiment): snapshots = sorted(path.name for path in (root / "collections").iterdir()) # Campaign evidence is lost while the native job still records a terminal session. shutil.rmtree(campaign) - assert agent_sessions.status(root / "jobs" / on)["state"] in agent_sessions.TERMINAL + state = manager.agent_session_status(root / "jobs" / on)["state"] + assert state in manager.AGENT_TERMINAL_STATES again = operation(experiment, "collect", on) # The first record is returned; no snapshot is written and the pointer is unchanged. assert again["already_collected"] is True and again["trial"] == collected diff --git a/tests/campaigns/test_qwen21_task.py b/tests/campaigns/test_qwen21_task.py index 31ccc35bb..fa664dcbb 100644 --- a/tests/campaigns/test_qwen21_task.py +++ b/tests/campaigns/test_qwen21_task.py @@ -983,7 +983,7 @@ def test_harness_continues_only_after_attributed_contract_rejection(tmp_path, fa """Round 1 is the real CPU worker and Qwen assessor; later rows are synthetic stand-ins.""" pytest.importorskip("torch") from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization from tests.diagnosis_support import diagnosis_evidence root = tmp_path / "campaign" diff --git a/tests/harness/session_lock_probe.py b/tests/harness/session_lock_probe.py index 709f28883..ec116ccd3 100644 --- a/tests/harness/session_lock_probe.py +++ b/tests/harness/session_lock_probe.py @@ -3,7 +3,7 @@ Run by tests/harness/test_session_lock_across_processes.py once per interpreter: against the checkout in the test run, and against an installed wheel in tests/repository/check_installed.py. It builds a valid managed session that is not final, starts a child process that -holds ``/.session.lock`` through ``harness.optimization``'s own lock, and exports the +holds ``/.session.lock`` through Manager's session lock, and exports the session through the Apps ``export_bundle`` from this process. While the child holds the lock the export must be refused and publish nothing; after it releases, the same export must publish a bundle whose ``export.kind`` is ``progress``. @@ -20,7 +20,7 @@ import inferrsi from inferrsi.apps import delivery from inferrsi.apps.storage.artifacts import atomic_write_json, sha256 -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization # The child runs with -I and imports inferrsi from the same location as this process. HOLDER = """ @@ -29,7 +29,7 @@ from pathlib import Path sys.path.insert(0, sys.argv[4]) -from inferrsi.harness.optimization import _locked +from inferrsi.harness.manager._state import _locked root, ready, release = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) with _locked(root): diff --git a/tests/harness/test_harness_measurement.py b/tests/harness/test_harness_measurement.py index 2f9980dd0..dba784118 100644 --- a/tests/harness/test_harness_measurement.py +++ b/tests/harness/test_harness_measurement.py @@ -7,7 +7,6 @@ import pytest -from inferrsi.harness import optimization_session from inferrsi.harness.evaluator import ( MIN_PAIRS, assess_ordinary, @@ -21,6 +20,7 @@ profile_evidence, validate_mechanism, ) +from inferrsi.harness.manager import session_runtime_identity BASE = [10.0, 10.1, 9.9, 10.05, 9.95, 10.02] GAIN = [8.0, 8.1, 7.9, 8.02, 7.98, 8.01] @@ -251,7 +251,7 @@ def test_aa_pass_rate_at_the_gate_stays_within_the_exact_bound(pairs): def test_measurement_module_is_part_of_runtime_identity(): - assert "harness/evaluator/_measurement.py" in optimization_session._runtime_identity() + assert "harness/evaluator/_measurement.py" in session_runtime_identity() def profiles(rows, jitter=None): diff --git a/tests/harness/test_parallel_round.py b/tests/harness/test_parallel_round.py index 3d661e0af..a3b437fa3 100644 --- a/tests/harness/test_parallel_round.py +++ b/tests/harness/test_parallel_round.py @@ -12,7 +12,6 @@ import pytest from inferrsi.apps.workflows.parallel_round import close_round, serve_ticket -from inferrsi.harness import parallel_round from inferrsi.harness.executor.confinement import ( ConfinementUnavailable, FixtureBackend, @@ -21,16 +20,25 @@ namespaces_available, ) from inferrsi.harness.executor.device_lease import DeviceLease, LeaseError -from inferrsi.harness.parallel_round import ( +from inferrsi.harness.manager import ( + _parallel_round as parallel_round, +) +from inferrsi.harness.manager import ( + parallel_ticket_status as ticket_status, +) +from inferrsi.harness.manager import ( + prepare_parallel_round as prepare, +) +from inferrsi.harness.manager import ( + submit_parallel_ticket as submit, +) +from inferrsi.harness.manager._parallel_round import ( RoundPlanError, _read_nofollow, _ticket_metadata_path, _tree_digest, hold_devices, materialize, - prepare, - submit, - ticket_status, ) WHEN = datetime(2026, 10, 30, tzinfo=timezone.utc) diff --git a/tests/harness/test_round_budget.py b/tests/harness/test_round_budget.py index 4f08cb32f..735a7b19a 100644 --- a/tests/harness/test_round_budget.py +++ b/tests/harness/test_round_budget.py @@ -5,7 +5,7 @@ import pytest -from inferrsi.harness.round_budget import ( +from inferrsi.harness.manager._round_budget import ( BudgetError, admit_from_path, advance, diff --git a/tests/harness/test_service_backfill_recovery.py b/tests/harness/test_service_backfill_recovery.py index 3ca563999..67915f92f 100644 --- a/tests/harness/test_service_backfill_recovery.py +++ b/tests/harness/test_service_backfill_recovery.py @@ -6,7 +6,9 @@ import pytest -from inferrsi.harness import executor, optimization, service_backfill +from inferrsi.harness import executor +from inferrsi.harness.manager import _service_backfill as service_backfill +from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records import service_io from inferrsi.harness.records.atomic_json import atomic_write_json from tests.fixtures.service_reuse import begin, call, settings, submit diff --git a/tests/harness/test_service_profile_diagnostics.py b/tests/harness/test_service_profile_diagnostics.py index 48d8f5010..a826d7e13 100644 --- a/tests/harness/test_service_profile_diagnostics.py +++ b/tests/harness/test_service_profile_diagnostics.py @@ -170,7 +170,7 @@ def test_large_backfill_prerequisite_failure_retains_inline_capture(campaign, fa def test_settled_legacy_large_error_is_readable_through_next_round_and_final(campaign): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records.atomic_json import atomic_write_json begin(campaign) @@ -214,18 +214,18 @@ def test_settled_legacy_large_error_is_readable_through_next_round_and_final(cam assert ( call(campaign, "final", "--reason", "Complete")["final"]["assessment"]["verdict"] == "PASS" ) - assert len(json.dumps(optimization.read_records(root)[2])) < len(ERROR_TEXT) + assert len(json.dumps(optimization.read_session_records(root)[2])) < len(ERROR_TEXT) assert observation.read_bytes() == original assert json.loads((root / "state.json").read_text())["attempts"][1] == old with observation.open("ab") as stream: stream.write(b" ") with pytest.raises(ValueError, match="control record disagree"): - optimization.read_records(root) + optimization.read_session_records(root) def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(campaign): - from inferrsi.harness import optimization + from inferrsi.harness.manager import _state as optimization from inferrsi.harness.records.atomic_json import atomic_write_json begin(campaign) @@ -281,4 +281,4 @@ def test_settled_legacy_large_profile_is_readable_through_next_round_and_final(c old["selected"] = False atomic_write_json(observation, old) with pytest.raises(ValueError, match="control record disagree"): - optimization.read_records(root) + optimization.read_session_records(root) diff --git a/tests/harness/test_service_reference_evidence.py b/tests/harness/test_service_reference_evidence.py index 1f1e1fbfc..98c9bd33f 100644 --- a/tests/harness/test_service_reference_evidence.py +++ b/tests/harness/test_service_reference_evidence.py @@ -5,7 +5,7 @@ import pytest -from inferrsi.harness import optimization +from inferrsi.harness.manager import _state as optimization from tests.fixtures.service_reuse import begin, call, rejected, settings, submit from tests.fixtures.service_reuse import campaign as campaign diff --git a/tests/repository/_gate_policy_support.py b/tests/repository/_gate_policy_support.py index a0a416fa2..b430cdd2a 100644 --- a/tests/repository/_gate_policy_support.py +++ b/tests/repository/_gate_policy_support.py @@ -102,7 +102,7 @@ # so the two package names are retired as a whole. # #558 moved ``inferrsi.harness.scenarios`` to ``inferrsi.harness.trials``, with no # forwarder, so the old package name is retired as a whole too. -# #702 moved the root-level runner and ten search modules under Manager and serving under Executor. +# #702 moved session, runner and search modules under Manager and service execution under Executor. RETIRED_MODULES = frozenset({ "inferrsi.infra", "inferrsi.model", @@ -111,6 +111,13 @@ "inferrsi.harness.project_service", "inferrsi.harness.service_evidence", "inferrsi.harness.runner", + "inferrsi.harness.agent_sessions", + "inferrsi.harness.attempt_recovery", + "inferrsi.harness.optimization", + "inferrsi.harness.optimization_session", + "inferrsi.harness.parallel_round", + "inferrsi.harness.service_backfill", + "inferrsi.harness.session_runtime", "inferrsi.harness.trials", "inferrsi.harness.local_process", "inferrsi.harness.launch_records", diff --git a/tests/repository/check_harness_freeze.py b/tests/repository/check_harness_freeze.py index cf281ba32..dc8d7f570 100644 --- a/tests/repository/check_harness_freeze.py +++ b/tests/repository/check_harness_freeze.py @@ -9,6 +9,7 @@ import tempfile import zipfile from email.parser import BytesParser +from importlib import import_module from importlib.metadata import distribution from pathlib import Path @@ -210,14 +211,15 @@ def wheel_version(archive): def check_install(manifest, wheel): from inferrsi import __file__ as package_file - from inferrsi.harness.optimization_session import _runtime_identity from inferrsi.resources.repository_packs import REPO_TYPES, repository_pack package = Path(package_file).resolve().parent dist = distribution("inferrsi") assert package == dist.locate_file("inferrsi").resolve(), "Install a non-editable wheel" assert dist.version == manifest["runtime_version"], (dist.version, manifest["runtime_version"]) - assert _runtime_identity() == read(FIXTURES / "runtime-sources.json"), ( + # The frozen wheel exposes its fingerprint through the original session module. + frozen_session = import_module("inferrsi.harness.optimization_session") + assert frozen_session._runtime_identity() == read(FIXTURES / "runtime-sources.json"), ( "Ordinary plan fingerprint differs" ) packs = manifest["repository_packs"] diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 153ff80aa..008b28d97 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -1010,7 +1010,11 @@ def assess(baseline, candidate, validation, integrity, error): assert json.loads((run_dir / "evaluation.json").read_bytes()) == {"verdict": "INCONCLUSIVE"} -assert_not_importable("inferrsi.harness.runner") +for retired_name in ( + "runner", "agent_sessions", "attempt_recovery", "optimization", "optimization_session", + "parallel_round", "service_backfill", "session_runtime", +): + assert_not_importable(f"inferrsi.harness.{retired_name}") check_installed_abba_runner() # #498 slice 1: the metric contract and the quality validators ship only under diff --git a/tests/repository/check_session_imports.py b/tests/repository/check_session_imports.py index 45dc17bf3..b7e303bfd 100644 --- a/tests/repository/check_session_imports.py +++ b/tests/repository/check_session_imports.py @@ -22,12 +22,12 @@ def observe(case, output): import pytest - from inferrsi.harness import optimization_session - from inferrsi.harness.session_runtime import included_module + from inferrsi.harness.manager import _session + from inferrsi.harness.manager._runtime import included_module - path = Path(optimization_session.__file__).resolve() + path = Path(_session.__file__).resolve() assert path.is_relative_to(sysconfig.get_path("purelib")), path - root = path.parents[1] + root = path.parents[2] modules, phases = set(), set() active = None @@ -39,9 +39,9 @@ def profile(frame, event, _): return name = frame.f_globals.get("__name__", "") function = frame.f_code.co_name - if (name, function) == ("inferrsi.harness.optimization_session", "session_command"): + if (name, function) == ("inferrsi.harness.manager._session", "run_session"): active = frame - phases.add(frame.f_locals["args"].session_action) + phases.add(frame.f_locals["request"].action) if (name, function) == ("inferrsi.apps.delivery", "export_bundle"): phases.add("export") if active is not None and included_module(name): @@ -65,7 +65,7 @@ def profile(frame, event, _): def check(cases): - from inferrsi.harness.optimization_session import _runtime_identity + from inferrsi.harness.manager import session_runtime_identity union = set() with TemporaryDirectory() as directory: @@ -74,7 +74,7 @@ def check(cases): subprocess.run([sys.executable, "-I", __file__, "--observe", case, str(output)], cwd=ROOT, check=True) union.update(json.loads(output.read_text(encoding="utf-8"))) - missing = union.difference(_runtime_identity()) + missing = union.difference(session_runtime_identity()) assert not missing, f"Installed session modules outside the frozen identity: {sorted(missing)}" print(f"{len(union)} observed session modules covered across {', '.join(cases)}") diff --git a/tests/repository/test_first_wave_isolation_policy.py b/tests/repository/test_first_wave_isolation_policy.py index 71b665f04..2249877d8 100644 --- a/tests/repository/test_first_wave_isolation_policy.py +++ b/tests/repository/test_first_wave_isolation_policy.py @@ -422,7 +422,7 @@ def test_another_importer_fails(self) -> None: line = "from inferrsi.resources.repository_packs import repository_pack\n" paths = ( "infra/other.py", "infra/inspection_helpers.py", "infra/__init__.py", - "infra/platforms/__init__.py", "harness/api.py", "harness/parallel_round.py", + "infra/platforms/__init__.py", "harness/api.py", "harness/manager/_parallel_round.py", "benchmark/probe.py", "apps/main.py", "apps/inspection.py", "apps/host/prepared_environment.py", "model/probe.py", "cli.py", "arguments.py", "apps/cli/__init__.py", "apps/cli/arguments.py", @@ -1007,17 +1007,17 @@ def test_entry_labels_are_not_inferred_as_paths(self) -> None: def test_non_entry_harness_module_cannot_reach_an_old_leaf(self) -> None: cases = ( ( - "from ..knowledge_operations import KnowledgeReader\n", - "inferrsi.harness.parallel_round reaches inferrsi.knowledge_operations", + "from ...knowledge_operations import KnowledgeReader\n", + "inferrsi.harness.manager._parallel_round reaches inferrsi.knowledge_operations", ), ( "from inferrsi.catalog import search_knowledge\n", - "inferrsi.harness.parallel_round reaches inferrsi.catalog", + "inferrsi.harness.manager._parallel_round reaches inferrsi.catalog", ), ) for source, expected in cases: with self.subTest(expected=expected): - report = _report({"harness/parallel_round.py": source}) + report = _report({"harness/manager/_parallel_round.py": source}) self.assertTrue(_violated(report, expected), report.violations) def test_former_residual_edge_fails_for_its_importer_and_dependents(self) -> None: @@ -1076,7 +1076,7 @@ def test_submodule_import_traverses_parent_package_init(self) -> None: def test_transitive_path_through_root_helpers_fails(self) -> None: report = _report( { - "harness/parallel_round.py": "from inferrsi import helper_a\n", + "harness/manager/_parallel_round.py": "from inferrsi import helper_a\n", "helper_a.py": "from inferrsi import helper_b\n", "helper_b.py": ( "from inferrsi.knowledge_operations import KnowledgeReader\n" @@ -1084,8 +1084,8 @@ def test_transitive_path_through_root_helpers_fails(self) -> None: } ) self.assertIn( - "inferrsi.harness.parallel_round reaches inferrsi.knowledge_operations: " - "inferrsi.harness.parallel_round -> inferrsi.helper_a -> inferrsi.helper_b" + "inferrsi.harness.manager._parallel_round reaches inferrsi.knowledge_operations: " + "inferrsi.harness.manager._parallel_round -> inferrsi.helper_a -> inferrsi.helper_b" " -> inferrsi.knowledge_operations", report.violations, ) @@ -1104,12 +1104,12 @@ def test_old_leaf_detection_is_not_sort_dependent(self) -> None: **direct, "knowledge_operations.py": _shell("inferrsi.knowledge_operations"), f"{name}.py": "from . import knowledge_operations\n", - "harness/parallel_round.py": ( - f"from .executor import skill_evaluation\nfrom .. import {name}\n" + "harness/manager/_parallel_round.py": ( + f"from ..executor import skill_evaluation\nfrom ... import {name}\n" ), } ) - for module in ("parallel_round", "executor.skill_evaluation"): + for module in ("manager._parallel_round", "executor.skill_evaluation"): self.assertTrue( _violated( report, @@ -1154,11 +1154,11 @@ def test_non_entry_own_parent_init_is_walked(self) -> None: "from ...knowledge_operations import KnowledgeReader\n" ), "harness/__init__.py": "from .executor import skill_evaluation\n", - "harness/parallel_round.py": "VALUE = 1\n", + "harness/manager/_parallel_round.py": "VALUE = 1\n", "harness/api.py": "VALUE = 1\n", } ) - for module in ("parallel_round", "api"): + for module in ("manager._parallel_round", "api"): self.assertIn( f"inferrsi.harness.{module} reaches inferrsi.knowledge_operations: " f"inferrsi.harness.{module} -> inferrsi.harness -> " @@ -1253,8 +1253,8 @@ def test_returning_r2_harness_infra_edges_fail(self) -> None: "model/metrics.py": "VALUE = 1\n"} primitives = {"harness/records/artifact_primitives.py": "VALUE = 1\n", "harness/records/atomic_json.py": "VALUE = 1\n"} - modules = ("agent_sessions", "executor.candidates", "optimization", "optimization_session", - "project", "executor._task_protocol") + modules = ("manager._agent_sessions", "executor.candidates", "manager._state", + "manager._session", "executor._project", "executor._task_protocol") paths = {name: "harness/" + name.replace(".", "/") + ".py" for name in modules} clean = {path: "from inferrsi.harness.records.artifact_primitives import VALUE\n" for path in paths.values()} @@ -1288,7 +1288,7 @@ def test_returning_r2_harness_infra_edges_fail(self) -> None: def test_mixed_harness_tree_is_not_an_isolated_core(self) -> None: tree = { "__init__.py": "", "harness/__init__.py": "", - "harness/parallel_round.py": "VALUE = 1\n", + "harness/manager/_parallel_round.py": "VALUE = 1\n", } report = _report({}, base=tree) self.assertEqual(report.violations, ()) @@ -1329,23 +1329,25 @@ def test_each_trigger_alone_keeps_overall_false(self) -> None: EMPTY_ALLOWLIST, ), ( - "harness reaches model/infra: inferrsi.harness.parallel_round -> inferrsi.infra", + "harness reaches model/infra: inferrsi.harness.manager._parallel_round" + " -> inferrsi.infra", { "infra/__init__.py": "", "infra/local.py": "", - "harness/parallel_round.py": "from inferrsi.infra import local\n", + "harness/manager/_parallel_round.py": "from inferrsi.infra import local\n", }, EMPTY_ALLOWLIST, ), ( - "harness reaches model/infra: inferrsi.harness.parallel_round -> inferrsi.bridge" + "harness reaches model/infra: inferrsi.harness.manager._parallel_round" + " -> inferrsi.bridge" " -> inferrsi.model", { # A root helper that is not a retired name: the path alone blocks. "bridge.py": "from inferrsi.model import metrics\n", "model/__init__.py": "", "model/metrics.py": "", - "harness/parallel_round.py": "from inferrsi import bridge\n", + "harness/manager/_parallel_round.py": "from inferrsi import bridge\n", }, EMPTY_ALLOWLIST, ), diff --git a/tests/repository/test_target_module_import_gate.py b/tests/repository/test_target_module_import_gate.py index 2b3c1504a..709acc36d 100644 --- a/tests/repository/test_target_module_import_gate.py +++ b/tests/repository/test_target_module_import_gate.py @@ -48,6 +48,15 @@ def _module(relative): return "inferrsi." + relative.removesuffix(".py").replace("/", ".") +def test_harness_root_exposes_the_accepted_component_layout(): + root = ROOT / "harness" + assert {p.name for p in root.iterdir() if p.is_dir() and p.name != "__pycache__"} == { + "analyzer", "api", "evaluator", "executor", "indexer", "manager", "records", + } + assert {p.name for p in root.glob("*.py")} == {"__init__.py"} + assert (root / "README.md").is_file() + + def test_retired_loader_tables_do_not_return(): # R3 admits by file location, so no table names a task, a function or a module. for name in ("RESOURCE_LOADERS", "EVALUATOR_LOADERS"): diff --git a/tools/parallel_round.py b/tools/parallel_round.py index 5d7677c78..083d658f4 100644 --- a/tools/parallel_round.py +++ b/tools/parallel_round.py @@ -8,7 +8,11 @@ from inferrsi.apps.workflows.parallel_round import close_round, serve_ticket from inferrsi.harness.executor.confinement import select_backend -from inferrsi.harness.parallel_round import prepare, submit, ticket_status +from inferrsi.harness.manager import ( + parallel_ticket_status, + prepare_parallel_round, + submit_parallel_ticket, +) def _load(path: str) -> dict: @@ -48,9 +52,9 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if args.command == "prepare": - result = prepare(_load(args.spec), args.incumbent, args.round_dir) + result = prepare_parallel_round(_load(args.spec), args.incumbent, args.round_dir) elif args.command == "submit": - result = submit( + result = submit_parallel_ticket( args.round_dir, args.lane, args.incumbent, @@ -71,7 +75,7 @@ def main(argv: list[str] | None = None) -> int: backend=select_backend(), ) else: - result = ticket_status(args.round_dir, args.ticket) + result = parallel_ticket_status(args.round_dir, args.ticket) json.dump(result, sys.stdout, indent=2) sys.stdout.write("\n") return 0