diff --git a/agents/forge/README.md b/agents/forge/README.md index 741607754..9d8771edd 100644 --- a/agents/forge/README.md +++ b/agents/forge/README.md @@ -101,18 +101,21 @@ entering the ordinary performance search: timing through the public baseline actions. Start from the workspace's unimplemented template at the candidate entry; an empty file is created only if the entry is missing. -2. Run `kernelforge.orchestrator.agent.make_agent_fn` with the target backend's +2. Run the engine's published implementer, + `kernelforge.workflows.forge_loop.api.make_agent_fn`, with the target backend's expertise prompt, normal configured provider/model, real SDK session execution, workspace guard and correctness-only in-session gate. README.md, `_aka_eval/CANDIDATE.md` and the read-only baseline supply the contract. - Both the keyword interface and the grouped `ImplementerSetup` interface are - supported, preserving the same protected paths, correctness gate and session - limit. The grouped gate receives the validation limit for both stage and + Its `ImplementerSetup` carries the protected paths, the correctness gate and + the session limit; the gate receives the validation limit for both stage and benchmark timeouts. - For grouped engines, new helper files are allowed inside declared trees in - directories present at session startup. That engine's nonrecursive new-file - allowlist rejects helpers in newly created directories; Arena does not widen - the allowlist outside the task's declared trees. + New helper files are allowed inside declared trees in directories present at + session startup. The engine's nonrecursive new-file allowlist rejects helpers + in newly created directories; Arena does not widen the allowlist outside the + task's declared trees. The loop that follows, and the loop of an + optimize-only run, are handed the same allowlist as `--commit-new-path`, so a + session that adds a module to a declared tree has it committed with its KEEP + rather than having the whole change rolled back. After initialization, the loop receives the remaining campaign budget and, when supported by its CLI, the same absolute deadline. 3. After each session, independently run candidate compile and complete @@ -334,13 +337,23 @@ backfills a solution. ## Installed KernelForge runtime The command line and the measurement driver are the whole interface to the -engine. The adapter patches no engine symbol and pins no engine module, so the -two release cadences are independent; [engine.py](engine.py) exists for the two -jobs that genuinely need the engine importable. `--arena-probe` reports what the -installed engine accepts, in the exact interpreter the campaign will use, and -checks that both commands still take the options the adapter builds. +engine for optimize and rewrite campaigns, and the adapter patches no engine +symbol. [engine.py](engine.py) exists for the two jobs that genuinely need the +engine importable, and refuses anything else. + +`--arena-probe` reports what the installed engine accepts, in the exact +interpreter the campaign will use. It checks that both commands still take the +options the adapter builds, reads the capability handshake the rewrite command +prints (`forge-rewrite-by-flydsl --capabilities-json`), and imports the library +names initialization is built from. + `--arena-initialize` runs the correctness-only implementer the engine publishes -only as a library. It refuses anything else. +only as a library. It is built from `kernelforge.workflows.forge_loop.api`, the +interface the engine publishes for callers outside its loop, with +`kernelforge.config.Config` and the usage ledger in +`kernelforge.agent_backends.usage`. An engine without them, which is any +Hyperloom revision before `05e67da61`, fails the probe before campaign work +starts. Upstream owns its GPU DSL/compiler support and SDKs. Install the `forge` extra in the GPU runtime environment (it also pulls the agent SDK dependencies). Through @@ -382,9 +395,9 @@ A dedicated interpreter can be selected with run-level `agent.python`. Backend selection follows the run's target language. The operator name comes from the task contract, and the engine's KB framework identity (`aiter`, `sglang`, `vllm`, else `standalone`) from the baseline's recorded provenance -source. The probe reports the rewrite's accepted source languages from -`kernelforge.rewrite_by_flydsl.protocol`; an engine that does not publish them -cannot run a FlyDSL rewrite. TileLang is a baseline language only and never a +source. The probe reports the rewrite's accepted source languages from the +capability handshake the rewrite command prints; an engine that does not publish +them cannot run a FlyDSL rewrite. TileLang is a baseline language only and never a Forge target. New scratch repositories start on `codex/arena-forge`, independently of the @@ -397,10 +410,18 @@ Search defaults live in [agent_config.yaml](agent_config.yaml); the run may override `workflow`, `model`, `agent_backend`, `permission_mode`, `timeout_seconds`, `session_timeout_seconds`, `max_port_attempts`, `initialization_max_attempts`, `initialization_budget_fraction`, -`supervisor_backend`, and `python`. An empty supervisor follows the selected -backend. Lane count, task preparation, profiling, planning probes and knowledge -warm starts follow the engine defaults. Arena publishes the task and leaves the -search policy to Forge. Two consequences are load bearing. The public task +`supervisor_backend`, `lanes`, and `python`. An empty supervisor follows the +selected backend. `lanes` is the engine's implementer lane count per round: +empty follows the engine default, and the value is passed to `forge-loop` as +`--lanes`, so what a given count means is the engine's to say. A rewrite's +nested loop is not given it. Task preparation, profiling and +knowledge warm starts follow the engine defaults. One thing about scoring is +not left to the engine: Arena's speedup is the geometric mean of per-case +speedups, so an engine whose `forge-loop` accepts `--case-aggregate` is told +`geometric` and judges its own KEEPs by the mean that grades its result. An +engine without the option still runs and searches by its own aggregate; the +probe reports which under `case_aggregate`. Arena publishes the task and +leaves the rest of the search policy to Forge. Two consequences are load bearing. The public task protocol exposes no profiler invocation, so the bridge answers `--profile-run` with an explicit unsupported capability. A single-file upstream recipe cannot describe a multi-file candidate, so a `solution/` tree with helper files may @@ -425,13 +446,12 @@ Most tests drive the adapter with a replaced engine subprocess: they cover the protocol, the delivery selection and the recovery paths, and their CPU timing fixtures are not GPU measurements or actual optimization runs. The tests gated on `AKA_FORGE_PROBE_PYTHON` use the installed engine for real — that a driver's -failure diagnostics are never read as a benchmark or a correctness pass, that the -scratch branch survives campaign preflight under a `main` or `master` Git -default, and that HIP/Triton initialization runs the real Forge implementer, -session execution, workspace guard and correctness gate. They cover rejected -attempts, an unedited workspace, harness tampering, session timeouts and a -failing loop. The provider is scripted throughout, so they prove neither model -quality nor GPU compiler compatibility. Real LLM/GPU qualification on +failure diagnostics are never read as a benchmark or a correctness pass, and +that HIP/Triton initialization runs the real Forge implementer, session +execution and correctness gate. They cover rejected attempts, an unedited +workspace, harness tampering, session timeouts and a failing loop. The provider +is scripted throughout and enters through the engine's provider registry, so +they prove neither model quality nor GPU compiler compatibility. Real LLM/GPU qualification on schema-v3 tasks remains a required integration gate for every target language; Gluon initialization and the v3 workflows have not yet run on a GPU. diff --git a/agents/forge/adapter.py b/agents/forge/adapter.py index a6fbb3f07..d281ce9d2 100644 --- a/agents/forge/adapter.py +++ b/agents/forge/adapter.py @@ -19,7 +19,8 @@ from agents.forge import bridge from agents.forge.common import _read_forge_result, _resolve_gpu_arch, _resolve_gpu_type, run_forge_subprocess from agents.forge.task_context import TaskContext -from agents.forge.bundles import allow_candidate_paths, candidate_files, committed_candidate, copy_workspace, install_candidate +from agents.forge.bundles import (allow_candidate_paths, candidate_files, committed_candidate, copy_workspace, + install_candidate, new_path_patterns) from src.task_contract import BASELINE_DIR from src.task_spec import resolve_task_path from src.tools.agent_cost import report_agent_usage @@ -128,7 +129,7 @@ def _config(eval_config: dict) -> dict: raise ValueError("agent run configuration must be a mapping") allowed = {"workflow", "model", "timeout_seconds", "permission_mode", "agent_backend", "python", "max_port_attempts", "supervisor_backend", "session_timeout_seconds", - "initialization_max_attempts", "initialization_budget_fraction"} + "initialization_max_attempts", "initialization_budget_fraction", "lanes"} config.update({key: value for key, value in overrides.items() if key in allowed}) if overrides.get("agent_backend") not in (None, "claude") and "model" not in overrides: # A Claude default is not a model ID for another provider. Let upstream @@ -140,6 +141,9 @@ def _config(eval_config: dict) -> dict: for field in ("max_port_attempts", "session_timeout_seconds", "initialization_max_attempts"): if type(config[field]) is not int or config[field] < 1: raise ValueError(f"Forge {field} must be a positive integer") + # Empty leaves the lane count to the engine, which also owns its upper bound. + if config.get("lanes") is not None and (type(config["lanes"]) is not int or config["lanes"] < 1): + raise ValueError("Forge lanes must be a positive integer") fraction = config["initialization_budget_fraction"] if type(fraction) not in (int, float) or not 0 < fraction < 1: raise ValueError("Forge initialization_budget_fraction must be between zero and one") @@ -286,6 +290,10 @@ def recover_timeout_candidate(plan: dict, engine: Path, result, fallback: str = return "", "" +#: How src.testcases.calculate_average_speedup combines per-case speedups, in the +#: engine's vocabulary. +ARENA_CASE_AGGREGATE = "geometric" + #: The engine dates its own budget from the moment its process is up, which #: trails the moment this argv is built by interpreter start, the capability #: probe and the engine import. Measured at 42s on MI355X; keep room to spare. @@ -341,6 +349,19 @@ def build_command(plan: dict, context: TaskContext, config: dict, *, gpu_arch: s "--baseline-json", plan["baseline"], "--program-md-file", plan["program"], "--agent-backend", config["agent_backend"], "--session-timeout-sec", str(config["session_timeout_seconds"])] + # The task lets a candidate add files to its solution tree, and the + # engine commits a created file only where it was told one may appear. + # Without this a session that splits the kernel into a new module has + # its whole change rolled back. + for pattern in new_path_patterns(context.spec, root): + command += ["--commit-new-path", pattern] + if config.get("lanes") is not None: + command += ["--lanes", str(config["lanes"])] + if plan.get("case_aggregate"): + # Arena's speedup is the geometric mean of per-case speedups. An + # engine searching by another mean keeps candidates Arena scores + # lower, so it is told which one grades its result. + command += ["--case-aggregate", ARENA_CASE_AGGREGATE] else: command += ["--source-kernel", plan["source"], "--flydsl-kernel-name", plan["anchor"], "--logical-op-name", context.operator, "--no-prepare-driver", @@ -434,6 +455,7 @@ def launch(eval_config: dict, task_config_dir: str, workspace: str) -> str: capabilities = json.loads(probe.stdout) status["engine"] = capabilities plan["applyback_optional"] = bool(capabilities.get("applyback_optional")) + plan["case_aggregate"] = bool(capabilities.get("case_aggregate")) require_supported_backend(context.spec, capabilities) candidate = context.spec.candidate initially_target = candidate.initial_state == "implemented" and candidate.initial_language == candidate.language diff --git a/agents/forge/agent_config.yaml b/agents/forge/agent_config.yaml index 8a3c19e43..89115541d 100644 --- a/agents/forge/agent_config.yaml +++ b/agents/forge/agent_config.yaml @@ -7,6 +7,9 @@ permission_mode: acceptEdits # Shared wall-clock cap: setup, checks, PORT and nested OPTIMIZE together. timeout_seconds: 87300 session_timeout_seconds: 3600 +# Implementer lanes per round. Empty follows the engine's default; 1 runs one +# implementer session per round. +lanes: max_port_attempts: 3 # HIP/Triton/Gluon initialization uses Forge's own correctness-only implementer. # Reserve the remaining campaign budget for the ordinary optimization loop. diff --git a/agents/forge/bundles.py b/agents/forge/bundles.py index 9204cd4bf..bca709911 100644 --- a/agents/forge/bundles.py +++ b/agents/forge/bundles.py @@ -34,6 +34,20 @@ def allow_candidate_paths(engine: Path, spec: TaskSpec, *, prefix: str = "") -> stream.write("\n".join(lines) + "\n") +def new_path_patterns(spec: TaskSpec, root: Path) -> list[str]: + """Authorize new files only in declared trees and existing directories.""" + patterns = [] + for scope in spec.candidate.editable: + if scope.scope != "tree": + continue + tree = resolve_task_path(root, scope.path, must_exist=True) + for directory in [tree, *sorted(path for path in tree.rglob("*") if path.is_dir())]: + relative = directory.relative_to(root).as_posix() + resolve_task_path(root, relative, must_exist=True) + patterns.append(relative + "/*") + return patterns + + def copy_workspace(source: Path, destination: Path) -> None: """Copy, without hardlinks, and refuse external symlinks before copying.""" for path in source.rglob("*"): diff --git a/agents/forge/engine.py b/agents/forge/engine.py index aa270c26f..a522fd070 100644 --- a/agents/forge/engine.py +++ b/agents/forge/engine.py @@ -14,7 +14,9 @@ from __future__ import annotations import asyncio +import contextlib import importlib.metadata +import io import json import os from pathlib import Path @@ -28,18 +30,29 @@ ADAPTER_API = 1 +def _rewrite_handshake(cli) -> dict: + """What ``forge-rewrite-by-flydsl --capabilities-json`` prints for the rewrite's consumers.""" + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + cli.main(args=["forge-rewrite-by-flydsl", "--capabilities-json"], standalone_mode=False) + return json.loads(printed.getvalue()) + + def probe() -> dict: - """Check the published command line the adapter builds, nothing deeper.""" + """Check the published command line the adapter builds and the library names initialization imports.""" from kernelforge import cli from kernelforge.kernel_backends.constants import KERNEL_BACKENDS + from agents.forge.initialization import engine_library + # An engine that moved one of these fails here, before any campaign work. + engine_library() try: version = importlib.metadata.version("hyperloom-inference_optimizer") except importlib.metadata.PackageNotFoundError: version = "source-checkout" required = { "forge-loop": {"kernel", "driver", "workspace_dir", "max_hours", - "source_files", "target_functions", "baseline_json"}, + "source_files", "target_functions", "baseline_json", "commit_new_paths"}, "forge-rewrite-by-flydsl": {"source_kernel", "driver", "workspace_dir", "max_hours", "prepare_driver", "flydsl_kernel_name"}, } @@ -54,20 +67,21 @@ def probe() -> dict: # adapter asks for the standalone kernel only where the engine accepts that. rewrite = cli.main.commands["forge-rewrite-by-flydsl"] applyback_optional = "applyback" in {parameter.name for parameter in rewrite.params} + # Optional as well: an engine that cannot be told how Arena aggregates + # per-case speedups still runs, scoring its search by its own aggregate. + loop = cli.main.commands["forge-loop"] + case_aggregate = "case_aggregate" in {parameter.name for parameter in loop.params} # The PORT states which source languages it ingests. An engine that does # not publish them cannot be told the baseline's language, so the adapter # refuses a FlyDSL rewrite there instead of letting the engine guess. - try: - from kernelforge.rewrite_by_flydsl.protocol import SUPPORTED_SOURCE_LANGUAGES - rewrite_sources = sorted(str(name) for name in SUPPORTED_SOURCE_LANGUAGES) - except ImportError: - rewrite_sources = None + languages = _rewrite_handshake(cli).get("source_languages") + rewrite_sources = sorted(map(str, languages)) if isinstance(languages, list) else None from agents.forge.adapter import INITIALIZATION_LANGUAGES return {"adapter_api": ADAPTER_API, "version": version, "initialization_targets": sorted([*INITIALIZATION_LANGUAGES, "flydsl"]), "backends": sorted(KERNEL_BACKENDS), "rewrite_target": "flydsl", "rewrite_source_languages": rewrite_sources, - "applyback_optional": applyback_optional} + "applyback_optional": applyback_optional, "case_aggregate": case_aggregate} def main(argv=None): @@ -80,7 +94,7 @@ def main(argv=None): plan = load_plan(Path(os.environ["ARENA_FORGE_PLAN"])) probe() # Refuse an engine whose published command line moved. from kernelforge.cli import main as cli - from agents.forge.initialization import initialize, prepare_loop + from agents.forge.initialization import engine_library, initialize, prepare_loop from agents.forge.process_tree import managed_children with managed_children(): initialization = asyncio.run(initialize(plan)) @@ -89,7 +103,7 @@ def main(argv=None): # mode. Preserve a failed engine exit, even if it wrote partial JSON. if isinstance(exit_code, int) and exit_code != 0: raise SystemExit(exit_code) - from kernelforge.tracker.usage import combine_usage_totals + combine_usage_totals = engine_library().usage.combine_usage_totals result_path = Path(plan["result"]) result = json.loads(result_path.read_text()) result["initialization"] = initialization diff --git a/agents/forge/initialization.py b/agents/forge/initialization.py index 368fd3a4d..77870b62b 100644 --- a/agents/forge/initialization.py +++ b/agents/forge/initialization.py @@ -7,16 +7,16 @@ import asyncio import hashlib -import inspect import json import os from pathlib import Path import stat import subprocess import time +from types import SimpleNamespace from agents.forge import bridge -from agents.forge.bundles import candidate_files, protected_paths +from agents.forge.bundles import candidate_files, new_path_patterns, protected_paths from agents.forge.task_context import TaskContext from src.task_spec import resolve_task_path @@ -70,54 +70,46 @@ def _save(path, value): temporary.replace(path) -def _new_path_patterns(spec, root: Path) -> list[str]: - """Authorize new files only in declared trees and existing directories.""" - patterns = [] - for scope in spec.candidate.editable: - if scope.scope != "tree": - continue - tree = resolve_task_path(root, scope.path, must_exist=True) - for directory in [tree, *sorted(path for path in tree.rglob("*") if path.is_dir())]: - relative = directory.relative_to(root).as_posix() - resolve_task_path(root, relative, must_exist=True) - patterns.append(relative + "/*") - return patterns - - -def _make_initialization_agent(config, *, new_path_patterns=(), **options): - """Bind either published implementer API without dropping gate settings.""" - from kernelforge.orchestrator import agent - - if "setup" not in inspect.signature(agent.make_agent_fn).parameters: - return agent.make_agent_fn(config=config, **options) - from kernelforge.loop.gate_settings import GateMeasurement - - task_keys = ("program_md", "kernel_backend_name", "profiling_enabled", "task_type", - "source_files", "target_functions", "extra_protected_paths") - session_keys = ("session_timeout_sec", "permission_mode", "insession_gate") - task = agent.ImplementerTask(**{key: options.pop(key) for key in task_keys}, - commit_new_paths=list(new_path_patterns)) - session = agent.SessionOptions(**{key: options.pop(key) for key in session_keys}) - timeout = options.pop("validation_timeout_sec") - measurement = GateMeasurement( - driver_script=options.pop("driver_script"), - interposed_driver_path=options.pop("interposed_driver_path"), - correctness_only=options.pop("correctness_only"), - stage_timeout_sec=timeout, bench_timeout_sec=timeout, +def engine_library() -> SimpleNamespace: + """The engine names this phase is built from, in one place so the probe checks the same ones. + + ``forge_loop.api`` is the interface the engine publishes for callers outside + its loop. The usage ledger a session reports into has no published home, so + it is named by its module. + """ + from kernelforge.agent_backends import usage + from kernelforge.config import Config + from kernelforge.workflows.forge_loop import api + + return SimpleNamespace(api=api, Config=Config, usage=usage) + + +def _implementer_setup(api, plan: dict, spec, root: Path, *, timeout: int, protected): + """The engine's implementer on this task, held to correctness alone by its in-session gate.""" + from agents.forge.program import program_text + + driver = str(root / "arena_forge_driver.py") + task = api.ImplementerTask( + program_md=program_text(plan, initialize=True), + kernel_backend_name=spec.candidate.language, + profiling_enabled=False, + task_type="repository", + source_files=list(map(str, candidate_files(spec, root).values())), + target_functions=[entry.symbol for entry in spec.candidate.entrypoints if entry.symbol], + extra_protected_paths=[str(root / name) for name in protected], + commit_new_paths=new_path_patterns(spec, root), ) - usage = options.pop("usage") - if options: - raise ValueError(f"Unmapped Forge implementer settings: {sorted(options)}") - return agent.make_agent_fn(config=config, - setup=agent.ImplementerSetup(task=task, measurement=measurement, session=session), - usage=usage) + # The gate runs the task's complete validation, so both of its limits are the session's. + measurement = api.GateMeasurement(driver_script=driver, correctness_only=True, + stage_timeout_sec=timeout, bench_timeout_sec=timeout) + session = api.SessionOptions(session_timeout_sec=timeout, insession_gate=True, + permission_mode=plan["agent_config"]["permission_mode"]) + return api.ImplementerSetup(task=task, measurement=measurement, session=session) async def initialize(plan: dict) -> dict: # Caller checks the pinned upstream before entering this phase. - from kernelforge.config import Config - from kernelforge.tracker.usage import UsageAccumulator - from agents.forge.program import program_text + library = engine_library() context = TaskContext.load(plan["context"]) spec, root = context.spec, Path(plan["engine_root"]) @@ -128,13 +120,13 @@ async def initialize(plan: dict) -> dict: + ", ".join(INITIALIZATION_LANGUAGES)) settings = plan["agent_config"] report = {"status": "RUNNING", "target_language": spec.candidate.language, - "mechanism": "kernelforge.orchestrator.agent.make_agent_fn", + "mechanism": "kernelforge.workflows.forge_loop.api.make_agent_fn", "attempts": [], "arena_verdict": "pending"} report_path = plan["initialization_result"] def checkpoint(totals=None): report["llm_usage"] = totals if totals is not None else usage.totals() _save(report_path, report) - usage = UsageAccumulator(on_update=checkpoint) + usage = library.usage.UsageAccumulator(on_update=checkpoint) checkpoint() remaining = plan["deadline_unix"] - time.time() phase_deadline = time.time() + remaining * settings["initialization_budget_fraction"] @@ -155,19 +147,9 @@ def checkpoint(totals=None): agent_backend=settings["agent_backend"], agent_timeout_sec=timeout) if settings.get("model"): kwargs["agent_model"] = settings["model"] - config = Config.from_env(**kwargs) - files = candidate_files(spec, root) - agent = _make_initialization_agent(config=config, new_path_patterns=_new_path_patterns(spec, root), - program_md=program_text(plan, initialize=True), - kernel_backend_name=spec.candidate.language, usage=usage, - insession_gate=True, correctness_only=True, - driver_script=str(root / "arena_forge_driver.py"), - interposed_driver_path=str(root / "arena_forge_driver.py"), - session_timeout_sec=timeout, validation_timeout_sec=timeout, - permission_mode=settings["permission_mode"], profiling_enabled=False, - task_type="repository", source_files=list(map(str, files.values())), - target_functions=[entry.symbol for entry in spec.candidate.entrypoints if entry.symbol], - extra_protected_paths=[str(root / name) for name in protected]) + config = library.Config.from_env(**kwargs) + setup = _implementer_setup(library.api, plan, spec, root, timeout=timeout, protected=protected) + agent = library.api.make_agent_fn(config=config, setup=setup, usage=usage) row = {"attempt": attempt, "status": "RUNNING", "backend": agent.backend_name, "model": agent.backend_model, "requested_backend": agent.requested_backend} report["attempts"].append(row) diff --git a/tests/test_forge_initialization.py b/tests/test_forge_initialization.py index 32fb19aae..74dab592d 100644 --- a/tests/test_forge_initialization.py +++ b/tests/test_forge_initialization.py @@ -13,8 +13,9 @@ from test_forge_v2 import ROOT, fixture_task, mock_engine from agents.forge import adapter, bridge -from agents.forge.bundles import allow_candidate_paths -from agents.forge.initialization import materialize_targets, _make_initialization_agent, _new_path_patterns, prepare_loop +from agents.forge.bundles import allow_candidate_paths, candidate_files, new_path_patterns +from agents.forge.initialization import materialize_targets, _implementer_setup, prepare_loop +from agents.forge.program import program_text @pytest.mark.parametrize("language", ["hip", "triton", "gluon"]) @@ -80,46 +81,25 @@ def test_initialization_cannot_take_the_entire_loop_budget(value): adapter._config({"agent": {"initialization_budget_fraction": value}}) -@pytest.mark.parametrize("grouped", [False, True]) -def test_implementer_api_preserves_all_initialization_controls(monkeypatch, grouped): - options = dict(program_md="INITIALIZE", kernel_backend_name="hip", profiling_enabled=False, - task_type="repository", source_files=["kernel.hip"], target_functions=["forward"], - extra_protected_paths=["driver.py"], session_timeout_sec=23, - permission_mode="acceptEdits", insession_gate=True, validation_timeout_sec=17, - driver_script="driver.py", interposed_driver_path="driver.py", - correctness_only=True, usage=object()) - received = {} - if grouped: - def factory(config, setup, *, usage): - received.update(config=config, setup=setup, usage=usage) - else: - def factory(config, program_md, **kwargs): - received.update(config=config, program_md=program_md, **kwargs) - engine = SimpleNamespace(make_agent_fn=factory, ImplementerTask=SimpleNamespace, - SessionOptions=SimpleNamespace, ImplementerSetup=SimpleNamespace) - package = ModuleType("kernelforge") - package.__path__ = [] - monkeypatch.setitem(sys.modules, "kernelforge", package) - monkeypatch.setitem(sys.modules, "kernelforge.orchestrator", SimpleNamespace(agent=engine)) - monkeypatch.setitem(sys.modules, "kernelforge.loop", ModuleType("kernelforge.loop")) - monkeypatch.setitem(sys.modules, "kernelforge.loop.gate_settings", - SimpleNamespace(GateMeasurement=SimpleNamespace)) - config = object() - _make_initialization_agent(config, new_path_patterns=["solution/*", "solution/nested/*"], **options) - assert received["config"] is config - if not grouped: - assert received == dict(config=config, **options) - return - setup = received["setup"] - assert vars(setup.task) == dict({key: options[key] for key in - ("program_md", "kernel_backend_name", "profiling_enabled", "task_type", "source_files", - "target_functions", "extra_protected_paths")}, commit_new_paths=["solution/*", "solution/nested/*"]) +def test_implementer_setup_carries_every_initialization_control(tmp_path): + context, plan, _ = fixture_task(tmp_path, language="hip", initial_state="unimplemented") + spec, root = context.spec, Path(plan["engine_root"]) + (root / "solution/nested").mkdir() + plan["agent_config"] = {"permission_mode": "acceptEdits"} + api = SimpleNamespace(ImplementerTask=SimpleNamespace, SessionOptions=SimpleNamespace, + GateMeasurement=SimpleNamespace, ImplementerSetup=SimpleNamespace) + setup = _implementer_setup(api, plan, spec, root, timeout=23, protected=["runner.py", "README.md"]) + driver = str(root / "arena_forge_driver.py") + assert vars(setup.task) == dict( + program_md=program_text(plan, initialize=True), kernel_backend_name="hip", profiling_enabled=False, + task_type="repository", source_files=list(map(str, candidate_files(spec, root).values())), + target_functions=["run"], extra_protected_paths=[str(root / "runner.py"), str(root / "README.md")], + commit_new_paths=["solution/*", "solution/nested/*"]) + assert "INITIALIZE" in setup.task.program_md + assert str(root / "solution/kernel.hip") in setup.task.source_files assert vars(setup.session) == dict(session_timeout_sec=23, permission_mode="acceptEdits", insession_gate=True) - assert vars(setup.measurement) == dict(driver_script="driver.py", interposed_driver_path="driver.py", - correctness_only=True, stage_timeout_sec=17, bench_timeout_sec=17) - assert received["usage"] is options["usage"] - with pytest.raises(ValueError, match="Unmapped Forge implementer settings"): - _make_initialization_agent(config, **options, unsupported_setting=True) + assert vars(setup.measurement) == dict(driver_script=driver, correctness_only=True, + stage_timeout_sec=23, bench_timeout_sec=23) def test_new_file_patterns_stay_inside_declared_tree_directories(tmp_path): @@ -127,7 +107,7 @@ def test_new_file_patterns_stay_inside_declared_tree_directories(tmp_path): root = Path(plan["engine_root"]) (root / "solution/nested").mkdir() (root / "unrelated").mkdir() - assert _new_path_patterns(context.spec, root) == ["solution/*", "solution/nested/*"] + assert new_path_patterns(context.spec, root) == ["solution/*", "solution/nested/*"] @pytest.mark.parametrize("absolute,existing", [(False, False), (True, False), (True, True)]) @@ -153,21 +133,18 @@ def test_loop_handoff_refreshes_budget_without_extending_deadline(tmp_path, monk # This program runs inside the real, pinned Hyperloom interpreter. Only the -# provider response and the final loop callback are scripted. The real Forge -# implementer factory, backend prompts, API session loop, workspace guard, -# in-session correctness gate, CLI parsing and public task actions all execute. +# provider response and the final loop callback are scripted, and the provider +# enters through the engine's own registry. The real Forge implementer factory, +# backend prompts, session loop, in-session correctness gate, CLI parsing and +# public task actions all execute. UPSTREAM_INITIALIZATION = r''' -import asyncio, json, os, subprocess +import asyncio, json, os from pathlib import Path -from types import SimpleNamespace -from agents.forge import engine, bridge +from agents.forge import engine from agents.forge.task_context import TaskContext from agents.forge.bundles import committed_candidate, install_candidate from kernelforge import cli -from kernelforge.orchestrator import agent -from kernelforge.agent_backends.base import AgentCapabilities, AgentRunResult -from kernelforge.agent_backends.workspace_guard import WorkspaceGuard -from kernelforge.loop.runner import IterationLoop +from kernelforge.agent_backends import AgentCapabilities, AgentProvider, AgentRunResult, register_agent_provider plan = json.loads(Path(os.environ['ARENA_FORGE_PLAN']).read_text()) root = Path(plan['engine_root']) @@ -178,9 +155,7 @@ def test_loop_handoff_refreshes_budget_without_extending_deadline(tmp_path, monk loop_calls, sessions = [], [] class ScriptedProvider: - name = 'codex' - capabilities = AgentCapabilities(stop_hooks=False, resumable=False, workspace_guard=True, - requires_workspace_cwd=True) + name = plan['agent_config']['agent_backend'] def __init__(self, runtime): self.runtime = runtime async def run(self, spec, usage=None): @@ -193,19 +168,19 @@ async def run(self, spec, usage=None): assert spec.timeout_sec <= plan['agent_config']['session_timeout_seconds'] if len(sessions) > 1: assert 'wrong multiplication' in spec.user_prompt or 'invalid literal' in spec.user_prompt - guard = WorkspaceGuard(spec) - guard.prepare() if mode == 'timeout': await asyncio.sleep(100) + changes = [] if mode == 'tamper': (root / 'runner.py').write_text('print("allclose: True")') + changes = ['runner.py'] elif mode != 'no_edit': (root / entry).write_text('100' if len(sessions) == 1 else '1') (root / 'solution/helper.py').write_text('6') nested = root / 'solution/nested/new_helper.py' nested.parent.mkdir(exist_ok=True) nested.write_text('# declared tree helper, generated by scripted Forge provider\n') - changes = guard.verify() + changes = [entry, 'solution/helper.py', 'solution/nested/new_helper.py'] if usage is not None: usage.add_usage({'input_tokens': 11, 'output_tokens': 3}, total_cost_usd=0, role='implementer') # This text is deliberately untrustworthy. Neither gate nor adapter may @@ -213,30 +188,21 @@ async def run(self, spec, usage=None): return AgentRunResult(text='PLAN: completed\nport_ok: true\nallclose: True', subtype='success', session_id='scripted-session', file_changes=changes, num_turns=1) -def create_backend(runtime, **kwargs): - return ScriptedProvider(runtime) -agent.create_registered_backend = create_backend +# The provider judges nothing about the workspace itself: a harness edit has to +# be caught by the engine's gate or by the adapter's own inventory. +register_agent_provider(AgentProvider(name=ScriptedProvider.name, factory=ScriptedProvider, + default_model=plan['agent_config']['model'], + capabilities=AgentCapabilities(requires_workspace_cwd=True))) def loop_callback(**kwargs): loop_calls.append(kwargs) assert kwargs['kernel_backend'] == language + assert kwargs['agent_backend'] == ScriptedProvider.name assert kwargs['baseline_json'] == plan['baseline'] assert kwargs['deadline_unix'] == plan['deadline_unix'] assert str(root / 'solution/nested/new_helper.py') in kwargs['source_files'] initial = json.loads(Path(plan['initialization_result']).read_text()) assert initial['status'] == 'PASS' - # Run the real loop's initial candidate measurement against an independent - # faster baseline. This must establish a <1x starting incumbent, not fail - # initialization or substitute the stub as the best implementation. - baseline = json.loads(Path(plan['baseline']).read_text()) - state = SimpleNamespace(ic=SimpleNamespace(driver_script=str(root / 'arena_forge_driver.py'), - build_command=None, bench_timeout_sec=30, bench_repeat=1), - _baseline_case_times=baseline['case_times'], _unscored_cases=set(), - _persist_scoring_state=lambda: None) - elapsed = asyncio.run(IterationLoop._measure_baseline(state)) - assert elapsed == 8, elapsed - assert state.search_start_mean_case_speedup == .5 - assert IterationLoop._incumbent_mean_case_speedup(state) == .5 result = dict(best_commit=initial['commit'], improved=False, iteration_count=0, llm_usage={'calls': 1, 'input_tokens': 7, 'output_tokens': 2, 'cost_available': True, 'cost_source': 'provider', 'total_cost_usd': 0}) @@ -289,7 +255,7 @@ def test_installed_upstream_initialization(tmp_path, language, mode): if not python: pytest.skip("Set AKA_FORGE_PROBE_PYTHON to the pinned Hyperloom[forge] interpreter") context, plan, path = fixture_task(tmp_path, language=language, initial_state="unimplemented") - config = adapter._config({"agent": {"agent_backend": "codex", "model": "scripted-model", + config = adapter._config({"agent": {"agent_backend": "arena-scripted", "model": "scripted-model", "initialization_max_attempts": 2, "session_timeout_seconds": 30}}) if mode == "timeout": config["session_timeout_seconds"] = 1 diff --git a/tests/test_forge_search_settings.py b/tests/test_forge_search_settings.py new file mode 100644 index 000000000..22d003ca1 --- /dev/null +++ b/tests/test_forge_search_settings.py @@ -0,0 +1,56 @@ +"""What the Forge adapter tells the engine about the search beyond the task itself.""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from test_forge_v2 import fixture_task +from agents.forge import adapter + + +def _values(command: list[str], option: str) -> list[str]: + """Every value ``option`` carries on the command line, in order.""" + return [command[index + 1] for index, word in enumerate(command) if word == option] + + +def _loop_command(tmp_path, overrides=None, *, workflow="optimize", capabilities=None): + context, plan, _ = fixture_task(tmp_path, language="triton") + (Path(plan["engine_root"]) / "solution/nested").mkdir() + plan.update(workflow=workflow, **(capabilities or {})) + config = adapter._config({"agent": overrides or {}}) + return adapter.build_command(plan, context, config, gpu_arch="gfx942", gpu_type="mi300x") + + +@pytest.mark.parametrize("workflow", ["optimize", "initialize"]) +def test_the_loop_may_commit_a_new_file_wherever_the_task_lets_a_candidate_add_one(tmp_path, workflow): + """A session that splits the kernel into a new module would otherwise have its whole change rolled back.""" + command = _loop_command(tmp_path, workflow=workflow) + + assert _values(command, "--commit-new-path") == ["solution/*", "solution/nested/*"] + + +def test_the_lane_count_is_the_engines_unless_the_run_names_one(tmp_path): + assert "--lanes" not in _loop_command(tmp_path) + + +def test_a_run_may_ask_for_a_lane_count(tmp_path): + assert _values(_loop_command(tmp_path, {"lanes": 1}), "--lanes") == ["1"] + + +@pytest.mark.parametrize("lanes", [0, -1, "3", 1.0, True]) +def test_a_lane_count_that_is_not_a_positive_integer_is_refused(lanes): + with pytest.raises(ValueError, match="Forge lanes must be a positive integer"): + adapter._config({"agent": {"lanes": lanes}}) + + +def test_an_engine_that_accepts_it_is_told_arena_scores_by_the_geometric_mean(tmp_path): + """An engine searching by another mean keeps candidates Arena scores lower.""" + command = _loop_command(tmp_path, capabilities={"case_aggregate": True}) + + assert _values(command, "--case-aggregate") == ["geometric"] + + +@pytest.mark.parametrize("capabilities", [None, {"case_aggregate": False}], ids=["unreported", "declined"]) +def test_an_engine_that_cannot_be_told_the_aggregate_still_runs(tmp_path, capabilities): + assert "--case-aggregate" not in _loop_command(tmp_path, capabilities=capabilities) diff --git a/tests/test_forge_v2.py b/tests/test_forge_v2.py index b4a472522..b0af81f8d 100644 --- a/tests/test_forge_v2.py +++ b/tests/test_forge_v2.py @@ -275,20 +275,12 @@ def test_real_upstream_rejects_failure_diagnostics_as_benchmark_or_correctness(t script = r''' import asyncio, json, sys from agents.forge.engine import probe -try: - from kernelforge.evaluation.correctness.driver import test_correctness - from kernelforge.evaluation.benchmark.runner import bench_wallclock as measure, BenchRun - async def bench_wallclock(driver): - return await measure(BenchRun(driver)) -except ModuleNotFoundError as error: - if not error.name.startswith('kernelforge.evaluation'): - raise - from kernelforge.mcp_server.tools.test import test_correctness - from kernelforge.mcp_server.tools.bench import bench_wallclock +from kernelforge.evaluation.correctness.driver import test_correctness +from kernelforge.evaluation.benchmark.runner import BenchRun, bench_wallclock probe() async def main(): return {'correctness': await test_correctness(sys.argv[1]), - 'benchmark': await bench_wallclock(sys.argv[1])} + 'benchmark': await bench_wallclock(BenchRun(sys.argv[1]))} print(json.dumps(asyncio.run(main()))) ''' result = subprocess.run([python, "-c", script, str(driver)], cwd=engine, @@ -934,10 +926,8 @@ def test_resume_recovery_does_not_hide_environment_or_evidence_errors(tmp_path, @pytest.mark.parametrize("default_branch", ["main", "master"]) -def test_scratch_branch_passes_real_upstream_campaign_preflight(tmp_path, monkeypatch, default_branch): - python = os.environ.get("AKA_FORGE_PROBE_PYTHON") - if not python: - pytest.skip("Set AKA_FORGE_PROBE_PYTHON to the pinned Hyperloom[forge] interpreter") +def test_scratch_repository_leaves_the_git_default_branch(tmp_path, monkeypatch, default_branch): + """The engine refuses to optimize on main or master, whichever the runtime's Git defaults to.""" # Model the actual Docker runtime without modifying any user's Git config. git_config = tmp_path / "global.gitconfig" git_config.write_text(f"[init]\n\tdefaultBranch = {default_branch}\n") @@ -949,25 +939,10 @@ def test_scratch_branch_passes_real_upstream_campaign_preflight(tmp_path, monkey adapter._initialize_git(root) actual = subprocess.check_output(["git", "branch", "--show-current"], cwd=root, text=True).strip() assert actual == "codex/arena-forge" - script = r''' -import sys -from agents.forge.engine import probe -from kernelforge.loop import campaign_config -import inspect -probe() -options = dict(kernel='kernel.py', driver='driver.py', program_md_file=None, - gpu_target='gfx950', gpu_type='mi355x', kernel_backend='triton', task_type='repository') -if 'inputs' in inspect.signature(campaign_config.create_campaign_config).parameters: - inputs = campaign_config.CampaignInputs(**options, source_files='kernel.py', target_functions='add') - campaign_config.create_campaign_config(workspace_dir=sys.argv[1], inputs=inputs) -else: - campaign_config.create_campaign_config(workspace_dir=sys.argv[1], **options, - source_files=['kernel.py'], target_functions=['add']) -''' - env = dict(os.environ, PYTHONPATH=str(ROOT)) - run = subprocess.run([python, "-c", script, str(root)], cwd=root, env=env, - capture_output=True, text=True, timeout=30) - assert run.returncode == 0, run.stdout + run.stderr + # A campaign starts from a clean tree with the kernel and the driver tracked. + assert subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True) == "" + tracked = subprocess.check_output(["git", "ls-files"], cwd=root, text=True).split() + assert {"kernel.py", "driver.py"} <= set(tracked) def test_internal_absolute_symlinks_rebind_to_snapshot(tmp_path):