From 61043d4ebf5b4ba2fc315a5b3fd1fecf67c119fa Mon Sep 17 00:00:00 2001 From: AltmanD Date: Tue, 24 Nov 2026 15:45:44 +0800 Subject: [PATCH 1/3] feat: complete Hub training, rollout recovery and math validation Integrate validated Hub and math work on current upstream main without importing private development history. Support shared IR publication, generation recovery, checkpoint retention and resume; document explicit worker storage and retain CPU publication checks. --- .github/workflows/ci.yml | 36 + .gitignore | 1 + docs/deployment.md | 31 + docs/sandbox-rollout.md | 153 +- harborrl/backends/slime_v032/config.py | 5 + .../backends/slime_v032/hub_rollout_client.py | 224 +++ harborrl/backends/slime_v032/rollout.py | 247 ++- .../slime_v032/rollout_service_client.py | 451 ++--- harborrl/config/native.py | 21 +- harborrl/deployment/controller.py | 101 +- harborrl/deployment/hub_rollout_executor.py | 159 +- harborrl/deployment/hub_server.py | 51 +- harborrl/deployment/schema.py | 101 +- harborrl/deployment/training_target.py | 2 +- harborrl/gateway/server.py | 23 +- harborrl/gateway/sglang_backend.py | 24 +- harborrl/gateway/shard_service.py | 2 +- harborrl/gateway/trace.py | 28 +- harborrl/math/config.py | 6 +- harborrl/math/data.py | 43 +- harborrl/options/catalog.py | 5 +- harborrl/options/presets.py | 3 +- harborrl/platform/checkpoint_guard.py | 162 ++ harborrl/platform/hub_train.py | 26 + harborrl/platform/preflight.py | 3 +- harborrl/platform/slime_train.sh | 22 +- harborrl/rollout/generations.py | 161 ++ harborrl/rollout/harbor_job/coordinator.py | 100 +- .../harbor_job/environments/opensandbox.py | 5 +- harborrl/rollout/harbor_job/reconcile.py | 371 ++++ harborrl/rollout/harbor_job/reliability.py | 370 ++++ harborrl/rollout/harbor_job/runner.py | 6 + harborrl/rollout/harbor_job/sandbox_config.py | 54 +- harborrl/rollout/runtime.py | 180 +- harborrl/rollout/service.py | 1563 +++++++++-------- practices/h_cluster/HISTORICAL_VALIDATION.md | 32 - practices/h_cluster/VALIDATION.md | 76 - .../src/harborrl_h_cluster/environment.py | 5 +- scripts/audit_public_tree.sh | 10 + tests/harborrl/test_checkpoint_guard.py | 93 + tests/harborrl/test_deployment_config.py | 16 + tests/harborrl/test_gateway_auto_shards.py | 4 +- tests/harborrl/test_gateway_recovery.py | 218 +++ tests/harborrl/test_hub_rollout_client.py | 274 +++ tests/harborrl/test_math.py | 37 + tests/harborrl/test_native_training.py | 36 + tests/harborrl/test_rejected_generations.py | 123 ++ tests/harborrl/test_rollout_generations.py | 133 ++ tests/harborrl/test_rollout_runtime.py | 710 ++++---- .../test_rollout_runtime_lifecycle.py | 52 + tests/harborrl/test_sandbox_reconciliation.py | 392 +++++ tests/harborrl/test_sandbox_reliability.py | 261 +++ 52 files changed, 5565 insertions(+), 1647 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 harborrl/backends/slime_v032/hub_rollout_client.py create mode 100644 harborrl/platform/checkpoint_guard.py create mode 100644 harborrl/platform/hub_train.py create mode 100644 harborrl/rollout/generations.py create mode 100644 harborrl/rollout/harbor_job/reconcile.py create mode 100644 harborrl/rollout/harbor_job/reliability.py delete mode 100644 practices/h_cluster/HISTORICAL_VALIDATION.md delete mode 100644 practices/h_cluster/VALIDATION.md create mode 100644 tests/harborrl/test_checkpoint_guard.py create mode 100644 tests/harborrl/test_gateway_recovery.py create mode 100644 tests/harborrl/test_hub_rollout_client.py create mode 100644 tests/harborrl/test_rejected_generations.py create mode 100644 tests/harborrl/test_rollout_generations.py create mode 100644 tests/harborrl/test_sandbox_reconciliation.py create mode 100644 tests/harborrl/test_sandbox_reliability.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..8b28edd53 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CPU checks +on: + push: + pull_request: +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -e '.[dev]' + - run: ruff check . + - run: pytest -q + - run: bash scripts/audit_public_tree.sh + - name: Audit pull request document history + if: github.event_name == 'pull_request' + env: + BASE_REF: ${{ github.base_ref }} + run: bash scripts/audit_public_tree.sh --history-base "origin/$BASE_REF" + sandbox-practice: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -e '.[dev,sandbox]' -e practices/h_cluster + - run: pytest practices/h_cluster/tests -q diff --git a/.gitignore b/.gitignore index 6e33a94ee..1852fc826 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,7 @@ docs/agents/* !docs/deployment.md !docs/math-distill.md !docs/sandbox-rollout.md +!docs/rollout-runtime-lifecycle.md !docs/train-inference-consistency.md !docs/web-console.md practices/**/VALIDATION.md diff --git a/docs/deployment.md b/docs/deployment.md index bab285b00..5ff455a20 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -131,6 +131,37 @@ even when service shutdown fails. Both Docker and Sandbox runtimes reject new attempts while observed cleanup-required markers remain. Inspect the resources before removing resolved markers. +## Hub training with remote workers + +Use `manager.mode: hub` with an explicit `hub_port`, reachable `hub_url` +and GPU pool, and select `rollout.provider: hub_pull`. The trainer submits +groups to the Hub; workers execute attempts and publish trajectory IRs. +The trainer validates their digests, batch identities, readiness and policy +versions before consuming them. Workers use Docker by default; a sandbox +configuration selects OpenSandbox with the same trajectory contract. See +[sandbox rollout](sandbox-rollout.md) for environment and cleanup settings. + +Set `HARBORRL_HUB_URL` and `HARBORRL_HUB_TOKEN_FILE` for the training process. +For Ray deployments, `HARBORRL_HUB_ENV_FILE` can name a shared JSON object +mapping these variable names and `RUN_ID` to values; explicit environment +variables take precedence. Protect the token file and keep credentials out +of checked-in configuration. + +Every worker must export `HARBORRL_HUB_ATTEMPT_MIRROR` as an absolute shared +directory, for example `/shared/harborrl/attempts`. The trainer must see the +same directory at the same path. Missing or relative paths fail before an +attempt starts. Attempts execute on worker-local storage and publish their +IR and evaluation records into this shared directory. If task roots differ +between trainer and worker, configure `HARBORRL_HUB_TASK_PATH_MAP` as +`shared_path=worker_path` pairs separated by commas. The worker gateway +address must be reachable from inside its Docker or OpenSandbox environment. + +Validate consecutive training steps, checkpoint publication and a separate +restore followed by another training step. Successful transport, zero-reward +steps and checkpoint restoration establish execution correctness; they do +not establish learning improvement. Checkpoint space guards and retention +settings help bound storage use but do not replace capacity planning. + ## Operational limits Service mode requires shared storage visible at the configured paths on the diff --git a/docs/sandbox-rollout.md b/docs/sandbox-rollout.md index d31b65cae..c37d26bd3 100644 --- a/docs/sandbox-rollout.md +++ b/docs/sandbox-rollout.md @@ -142,6 +142,27 @@ Set `training.export_hf: true` to export HF weights under independent model serving and evaluation. Optimizer checkpoints remain under `checkpoints/`. The export option defaults to `false`. +Use `training.resume` to load a Slime checkpoint root, including optimizer and +scheduler state. Relative paths resolve beside the YAML file. The default is +`null`, which starts from the model checkpoint. `training.num_rollout` remains +the total target rollout count. A checkpoint at index `k` resumes at `k + 1`; +set the target to at least `k + 2` to perform another update. A target of +`k + 1` restores state without taking a new training step. Set +`training.max_tokens_per_gpu` (default `16384`) +for the training batch token budget and `training.max_ckpt_keep` (default `2`) +for checkpoint retention; both require positive integers. These options must +be declared in configuration: ambient `RESUME_LOAD`, `MAX_TOKENS_PER_GPU`, and +`MAX_CKPT_KEEP` variables are filtered by the local training target. + +The launcher supervises Slime with `harborrl.platform.checkpoint_guard`; the +pinned backend silently ignores unknown retention flags. The supervisor checks +available space before launch (at least 128 GiB, or 1.15 times the resumed +checkpoint size), and removes older generations only after a tracker-published +successor has readable tensor archives and complete requested HF exports. It +records deletion manifests in `checkpoints//retention.jsonl`. These are +structural checks, not a full tensor restore, and the preflight is not a space +reservation: budget for a complete extra generation while the old one remains. + ## Concurrency and evidence `max_live_instances` bounds all active instances; each image binding has its @@ -151,12 +172,132 @@ using process-shared locks. Shared-filesystem flock support is required when runners use the same lock directory across hosts. Groups use the same identity, policy barrier, verifier and consumption audit -as Docker. Failed slots cancel their group siblings. Direct Slime rollout -batches cancel and await all remaining groups and their slot cleanup before -closing the runtime and propagating a failure or cancellation. RolloutService -requests wait for submitted independent groups before rejecting a partial -batch. Unconfirmed cleanup blocks new admission. Production export never -accepts synthetic evidence. +as Docker. Failed slots cancel and await their group siblings. Direct Slime +rollout batches also settle every remaining group before deciding whether +recovery is permitted. RolloutService requests wait for submitted independent +groups before rejecting a partial batch. Unconfirmed cleanup blocks new +admission. Production export never accepts synthetic evidence. + +### Independent cleanup and admission debt + +Each Sandbox runner registers a dedicated Linux session, inherited attempt +tag, PID start time, host and boot identity in `runner-process.json`. After the +runner exits, a separate process on the same host observes and terminates any +surviving owned processes. PID reuse, a different host or boot, and unreadable +possible descendants leave ownership unresolved. Protected processes older +than the runner are excluded. The observer also verifies its parent chain and +excludes those exact ancestor PIDs and start times, so a protected SSH service +that launched the observer cannot block cleanup just because it started after +the runner. A changed parent chain, the runner's session, or its inherited +attempt tag rejects the observer as nonindependent. Transient process read +errors retry a complete scan within the cleanup deadline; persistent errors +retain debt and their observations. Process sessions, `/proc` and POSIX signals +are required; this is a Linux runner contract. + +The observer reads the attempt's locked runtime and lifecycle, then polls the +platform independently of the SDK. A known allocation is absent only after +GET returns 404, a complete and consistent paginated project inventory excludes +that ID, and the process proof succeeds. DELETE acknowledgement or a lifecycle +string alone cannot close cleanup. The observer can delete only the allocation +ID recorded for that attempt; an unknown POST outcome remains blocked for +ownership reconciliation. Unknown inventory entries are preserved. + +Every observation is retained under `cleanup-reconciliations/`. A successful +observation publishes immutable `cleanup-reconciliation.json`, bound to the +runtime, lifecycle and process-owner digests. The original +`cleanup-required.json` markers and lifecycle history remain available; a +validated receipt explains their closure. Repeating a completed reconciliation +returns that receipt. + +Image and global live capacity remain reserved while cleanup is unresolved. +Queued requests wake and fail when debt appears, including when all capacity +is retained. After a new independent reconciliation succeeds, the owning +runtime can call `sandbox_admission.reconcile(attempt_root)` to release the +retained capacity. Restarting into an old attempt is forbidden: inspect its +evidence, finish cleanup on the original runner host, then use a fresh protocol. +To invoke the observer manually on that host, supply the nonsecret resolved +configuration on stdin, for example from a private deployment script: + +```python +import json +import subprocess +import sys +from harborrl.rollout.harbor_job.sandbox_config import load_sandbox + +cfg = load_sandbox('sandbox.yaml') +subprocess.run([sys.executable, '-m', 'harborrl.rollout.harbor_job.reconcile', + 'ATTEMPT_ROOT'], input=json.dumps(cfg) + '\n', text=True, check=True) +``` + +Credentials remain in the configured permission-restricted file. Cleanup stderr +and receipts belong in the private run evidence directory. + +### Whole rollout generation recovery + +Sandbox Slime batches freeze task order, group and slot membership, sampling +parameters and the serving policy version before the first generation. A +retryable infrastructure failure invalidates the entire generation, discards +all partial sample IR/reward/response fields, and uses new batch, group, attempt +and trajectory identities for recovery. The task list and policy stay fixed. +Low rewards, protocol or audit errors, cancellation, seed budget exhaustion +and unresolved cleanup never trigger this recovery. A sibling terminal error +discovered during cleanup takes precedence over a retryable failure. + +`HARBORRL_NATIVE_GENERATION_POLICY` accepts the positive integer limits +`max_attempts_per_rollout` (default 32) and `max_failed_groups_per_rollout` +(default 8), plus the nonnegative `max_reruns_per_seed` (default 2). The +failed-group limit blocks new attempts after it is exceeded; exhaustion of any +group's slot attempts also invalidates the generation immediately. Seed reruns +are shared across all batches, not reset for each batch. + +`rollout-generations/` contains a frozen policy, each batch's input manifest, +generation reservation, failure and superseded records, and a single selected +generation. Only complete results from the expected tasks, slots, policy and +generation can be selected, after the normal training-export audit passes. +An attempt retry within a generation preserves its input-derived sampling seed. +A whole generation rerun changes the batch and group identity, so the existing +SGLang seed derivation produces a new sampling seed. The base training seed, +sampling parameters, tasks and policy stay frozen; recovery is independent of +reward and does not promise bit-for-bit replay across generations. +`generation-budgets/` persists attempt reservations and failed groups under a +shared-filesystem flock. Embedded and service workers use the same bound; +restarting a worker cannot reset it or increase the limits. Reopening an +existing rollout directory is rejected and requires a fresh run protocol. + +### Reliability control plane + +Sandbox rollouts also maintain an append-only `sandbox-reliability/events.jsonl` +journal under the run root. Every event has a monotonic sequence, UTC and +monotonic timestamps, attempt id, state, failure kind, node, allocation id, +budget snapshot, decision and sanitized detail. Consecutive events are linked +by SHA-256 digests, so rewriting or removing history is detectable. URLs, +credential-looking fields and long diagnostic strings are redacted before the +journal is written. The journal is independent from rewards: an invalid attempt +can be retried as a new attempt id, but its partial trajectory never enters a +training export. + +Configure retry spacing and node cooling with +`HARBORRL_NATIVE_RELIABILITY_POLICY` as a JSON object. Supported keys are +`backoff_seconds`, `max_backoff_seconds`, `node_consecutive_failures` and +`node_cooldown_seconds`; `max_attempts_per_slot` remains governed by the +existing native attempt limit. A node reaching the consecutive platform-failure +threshold is unavailable until its cooldown expires. Configure the frozen seed +infrastructure budget with `HARBORRL_NATIVE_INFRA_BUDGET` using positive JSON +integers for `attempts`, `create_retries`, `cleanup_reconciliations` and +`storage_faults`, plus a positive finite `wall_clock_seconds`. Once any budget +is exhausted, the runtime records a fail-seed event and does not reserve another +attempt. These limits must be chosen before a run and cannot be increased after +observing rewards or held-out results. +The seed budget lock persists its original limits and absolute wall-clock +expiry, and journal replay restores the remaining counters. Removing the +budget when reopening a locked seed is rejected, even before its first attempt. +An infrastructure failure remains counted after cleanup succeeds; cleanup +receipts are additional events and do not replace failed outcomes. + +The node-cooling ledger can exclude known nodes when candidates are available. +Server-controlled scheduling is still authoritative; this does not force the +platform to choose a different node. Unknown allocation ownership, cleanup +debt and exhausted budgets require reconciliation or a fresh protocol. ## Checks diff --git a/harborrl/backends/slime_v032/config.py b/harborrl/backends/slime_v032/config.py index 3bba35617..39024803e 100644 --- a/harborrl/backends/slime_v032/config.py +++ b/harborrl/backends/slime_v032/config.py @@ -10,6 +10,8 @@ "MODEL_TAG": ("model", "args_file"), "NUM_ROLLOUT": ("training", "num_rollout"), "SAVE_INTERVAL": ("training", "save_interval"), + "MAX_TOKENS_PER_GPU": ("training", "max_tokens_per_gpu"), + "MAX_CKPT_KEEP": ("training", "max_ckpt_keep"), "LR": ("training", "learning_rate"), "ROLLOUT_BATCH_SIZE": ("sampling", "groups_per_batch"), "N_SAMPLES": ("sampling", "group_size"), @@ -93,6 +95,8 @@ def launch_plan(config): environment['HARBORRL_NATIVE_RUNNER_TRANSPORT'] = c['harbor'].get('runner_transport', 'ssh') if c['training'].get('seed') is not None: environment['HARBORRL_TRAINING_SEED'] = c['training']['seed'] + if c['training'].get('resume') is not None: + environment['RESUME_LOAD'] = c['training']['resume'] if sandbox is not None: environment['HARBORRL_NATIVE_SANDBOX'] = json.dumps(sandbox, sort_keys=True) return {'config': config, 'math': selection.asdict(), @@ -121,6 +125,7 @@ def field_usage(): "training.backend_contract": ["environment:HARBORRL_NATIVE_SLIME_CONTRACT", "preflight:backend hooks"], "training.seed": ["environment:HARBORRL_TRAINING_SEED"], "training.export_hf": ["run_environment:SAVE_HF"], + "training.resume": ["environment:RESUME_LOAD"], "harbor.workers": ["environment:HARBORRL_NATIVE_RUNNER_WORKERS", "preflight:worker probe"], "harbor.runner_transport": ["environment:HARBORRL_NATIVE_RUNNER_TRANSPORT"], "harbor.environment": ["environment:HARBORRL_NATIVE_SANDBOX", "runner:environment"], diff --git a/harborrl/backends/slime_v032/hub_rollout_client.py b/harborrl/backends/slime_v032/hub_rollout_client.py new file mode 100644 index 000000000..00d75156d --- /dev/null +++ b/harborrl/backends/slime_v032/hub_rollout_client.py @@ -0,0 +1,224 @@ +"""Training-side client for hub-mode rollout dispatch (hub_pull provider). + +The GPU job sends one attempt request per (group, slot) to the hub server; +Registered workers pull them, execute the full trial (worker-hosted gateway + +sandbox container + verifier) and report {success, ir_path, ir_sha256, +reward}. Trajectory IRs live on shared storage, so this client only needs +paths and digests over HTTP — mirroring the rollout-service contract where +heavy payloads never cross the wire. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +from urllib import request, error + + +class HubRolloutError(RuntimeError): + def __init__(self, message, *, status=None, code=None): + super().__init__(message) + self.status, self.code = status, code + + +class HubRolloutClient: + """Synchronous urllib client; safe to call from asyncio.to_thread.""" + + def __init__(self, hub_url, run_id, token, *, timeout=120, + poll_interval=2.0, opener=None): + self.base_url = hub_url.rstrip("/") + self.run_id = run_id + self.token = token + self.timeout = timeout + self.poll_interval = poll_interval + self.opener = opener or request.build_opener(request.ProxyHandler({})) + + def _request(self, method, path, body=None): + url = f"{self.base_url}{path}" + data = json.dumps(body).encode() if body is not None else None + headers = {"Content-Type": "application/json"} + if self.token: + headers["X-Api-Key"] = self.token + req = request.Request(url, data=data, headers=headers, method=method) + try: + with self.opener.open(req, timeout=self.timeout) as response: + return json.load(response) + except error.HTTPError as exc: + try: + payload = json.load(exc) + except (ValueError, OSError): + payload = {"error": {"type": "transport", "message": str(exc)}} + error_payload = payload.get("error", payload) + raise HubRolloutError( + f"{method} {path}: {error_payload.get('type')}: " + f"{error_payload.get('message')}", + status=exc.code, code=error_payload.get("type")) from exc + except (error.URLError, OSError, ValueError) as exc: + raise HubRolloutError(f"{method} {path}: {exc}", code="transport") from exc + + def submit_attempt(self, attempt_request): + """Idempotent per (run, rollout, group, slot); returns task_id.""" + payload = self._request("POST", "/hub/rollout_tasks", + {"run_id": self.run_id, "request": attempt_request}) + task_id = payload.get("task_id") + if not task_id: + raise HubRolloutError(f"hub submit returned no task_id: {payload}") + return task_id + + def task_status(self, task_ids): + return self._request("POST", "/hub/rollout_tasks/status", + {"task_ids": list(task_ids)}) + + +def load_attempt_ir(task_id, result, *, expected_policy_version=None, + expected_task_digest=None): + """Read the trajectory IR from shared storage and verify its seal.""" + if not isinstance(result, dict): + raise HubRolloutError(f"task {task_id} reported no result body") + # RolloutPuller reports an outcome envelope; the hub preserves it verbatim. + if "result" in result: + if result.get("success") is not True or not isinstance(result["result"], dict): + raise HubRolloutError(f"task {task_id} reported an unsuccessful result envelope") + result = result["result"] + if result.get("success") is False: + raise HubRolloutError(f"task {task_id} reported a failed attempt") + ir_path = result.get("ir_path") + ir_sha = result.get("ir_sha256") + if not ir_path or not ir_sha: + raise HubRolloutError( + f"task {task_id} completed without ir_path/ir_sha256") + path = Path(ir_path) + if not path.is_file(): + raise HubRolloutError(f"task {task_id} ir_path missing on shared storage: {ir_path}") + from harborrl.trajectories.native import digest, read_json + + try: + ir = read_json(path) + actual_digest = digest(ir) + except (OSError, ValueError, TypeError) as exc: + raise HubRolloutError(f"task {task_id} invalid IR at {ir_path}: {exc}") from exc + if actual_digest != ir_sha: + raise HubRolloutError(f"task {task_id} IR digest mismatch at {ir_path}") + identity = ir.get("identity", {}) + if expected_policy_version is not None and \ + str(identity.get("policy_version")) != str(expected_policy_version): + raise HubRolloutError( + f"task {task_id} policy version {identity.get('policy_version')!r} " + f"!= locked {expected_policy_version!r}") + if expected_task_digest and identity.get("task_digest") != expected_task_digest: + raise HubRolloutError(f"task {task_id} task digest mismatch") + if ir.get("readiness") != "RL_READY": + raise HubRolloutError( + f"task {task_id} IR readiness {ir.get('readiness')!r} is not RL_READY") + if ir.get("integrity_errors"): + raise HubRolloutError(f"task {task_id} IR integrity errors: {ir['integrity_errors']}") + return ir + + +def _rewrite_task_path(path): + """Map a trainer-visible task path onto the worker's local filesystem. + + Task trees live twice: the shared-storage copy the GPU job inspects for + digest preflight, and the worker-local copy the sandbox actually mounts + (sshfs paths are invisible to the worker's docker daemon). The mapping + comes from HARBORRL_HUB_TASK_PATH_MAP="shared=local[,shared2=local2]". + """ + mapping = os.environ.get("HARBORRL_HUB_TASK_PATH_MAP", "") + if not mapping: + import json as _json + try: + env_file = os.environ.get( + "HARBORRL_HUB_ENV_FILE", + "") + mapping = _json.loads(Path(env_file).read_text(encoding="utf-8")).get( + "HARBORRL_HUB_TASK_PATH_MAP", "") + except (OSError, ValueError): + mapping = "" + for pair in filter(None, mapping.split(",")): + if "=" not in pair: + continue + shared, local = pair.split("=", 1) + if path.startswith(shared): + return path.replace(shared, local, 1) + return path + + +def hub_attempt_request(group_request, slot, *, serving_endpoint, hf_ckpt, + tokenizer_digest, template_digest, model_tag, + max_output_tokens, max_context, task_path, + reward_profile=None, batch_id=None, audited_raw_logprobs=False): + """Expand one service-style GroupRequest into a per-slot attempt request. + + Field superset consumed by deployment.hub_rollout_executor.execute(). + """ + task = group_request["task"] + sampling = group_request.get("sampling", {}) + if type(audited_raw_logprobs) is not bool: + raise ValueError("audited_raw_logprobs must be boolean") + if 'rollout_generation' in group_request: + from harborrl.rollout.generations import generation_batch_id + locked_batch = generation_batch_id( + group_request['rollout_id'], group_request['rollout_generation']) + if batch_id is not None and batch_id != locked_batch: + raise ValueError('hub batch_id conflicts with rollout generation') + batch_id = locked_batch + elif batch_id is None: + batch_id = 'batch' + return { + # slot identity — also the hub's idempotency key part + "rollout_id": group_request["rollout_id"], + "group_id": group_request["group_id"], + "group_index": group_request.get("group_index"), + "slot_id": str(slot["slot_id"]), + "batch_id": batch_id, + "trajectory_id": f"{group_request['group_id']}-s{slot['slot_id']}", + "policy_version": group_request["policy_version"], + # task lock (worker executes from its local mirror of the tree) + "task_path": _rewrite_task_path(task["path"]), + "task_digest": task.get("task_digest", ""), + "reward_profile": reward_profile or {"key": "reward", "scale": 1.0, + "offset": 0.0, "raw_range": [0.0, 1.0]}, + # generation + "model_tag": model_tag, + "serving_endpoint": serving_endpoint, + "hf_ckpt": hf_ckpt, + "audited_raw_logprobs": audited_raw_logprobs, + "tokenizer_digest": tokenizer_digest, + "template_digest": template_digest, + "max_output_tokens": max_output_tokens, + "max_context": max_context, + "stop": list(sampling.get("stop") or []), + "sampling": sampling, + } + + +def client_from_environment(): + """Build a HubRolloutClient from HARBORRL_HUB_* variables or a JSON file. + + Ray workers inherit the raylet's startup environment, which predates the + trainer shell's exports on platform-bootstrapped clusters; a shared JSON + file (HARBORRL_HUB_ENV_FILE) reaches both the trainer and the workers. + The file maps variable names to values and overrides nothing already set. + """ + env_file = os.environ.get( + "HARBORRL_HUB_ENV_FILE", + "") + extra = {} + if env_file: + path = Path(env_file) + if path.is_file(): + extra = json.loads(path.read_text(encoding="utf-8")) + + def setting(name, default=None): + return os.environ.get(name) or extra.get(name) or default + + hub_url = setting("HARBORRL_HUB_URL") + if not hub_url: + raise HubRolloutError( + "HARBORRL_HUB_URL is not set (env or HARBORRL_HUB_ENV_FILE); hub rollout requires it") + token_file = setting("HARBORRL_HUB_TOKEN_FILE") + token = "" + if token_file: + token = Path(token_file).read_text().strip() + run_id = os.environ.get("RUN_ID") or extra.get("RUN_ID") or "adhoc" + return HubRolloutClient(hub_url, run_id, token) diff --git a/harborrl/backends/slime_v032/rollout.py b/harborrl/backends/slime_v032/rollout.py index 822e360a1..e4d0fda04 100644 --- a/harborrl/backends/slime_v032/rollout.py +++ b/harborrl/backends/slime_v032/rollout.py @@ -10,6 +10,7 @@ import asyncio import math import os +import time from pathlib import Path from harborrl.backends.slime_v032.versions import lock_policy_version @@ -20,6 +21,7 @@ close_runtime, current_policy_version, digest, + run_embedded, run_group, runtime, task_entry, @@ -102,7 +104,15 @@ async def generate_group(args, group, sampling_params_, rollout_id, evaluation=F })) config = runtime_config_from_args(args) runtime_ = await runtime(config, tokenizer_loader=slime_tokenizer_loader(args)) - policy_version = current_policy_version(runtime_) + from harborrl.rollout.generations import ACTIVE_GENERATION + context = ACTIVE_GENERATION.get() + if context is None: + policy_version = current_policy_version(runtime_) + else: + from harborrl.platform.policy_pool import validate_pool + policy_version = validate_pool(runtime_.backend.pool_states()) + if policy_version != context['policy_version']: + raise ValueError('serving pool changed during rollout generation recovery') trajectories = await run_group( config, runtime_, entry=entry, group_index=group_index_of(group), rollout_id=rollout_id, sampling_digest=sampling_digest, @@ -127,13 +137,11 @@ def bind_group_samples(group, trajectories): return output -async def run_service_groups(args, groups, rollout_id): - """Request complete groups from the manager-side RolloutService (P3).""" +async def prepare_service_policy(args): + """Activate and lock the pool before reserving a rollout generation.""" from harborrl.backends.slime_v032.rollout_service_client import ( RolloutServiceClient, fetch_pool_states, - load_group_result, - service_group_request, ) token_file = os.environ.get('HARBORRL_ROLLOUT_SERVICE_TOKEN_FILE') @@ -155,6 +163,22 @@ async def run_service_groups(args, groups, rollout_id): # The manager's activation publishes the locked policy-pool record into # the shared run directory; lock the same version before requesting. policy_version = lock_policy_version(args) + return client, policy_version + + +async def run_service_groups(args, groups, rollout_id): + """Request complete groups from the manager-side RolloutService (P3).""" + from harborrl.backends.slime_v032.rollout_service_client import ( + load_group_result, + service_group_request, + ) + from harborrl.rollout.generations import ACTIVE_GENERATION + from harborrl.rollout.harbor_job.reliability import RetryableRolloutFailure + + client, policy_version = await prepare_service_policy(args) + context = ACTIVE_GENERATION.get() + if context is not None and context['policy_version'] != policy_version: + raise ValueError('serving pool changed during rollout generation recovery') params = sampling_params(args) async def request_group(group): request = service_group_request(group, params, rollout_id, policy_version) @@ -163,6 +187,9 @@ async def request_group(group): # GroupResult itself. result = payload.get("result") if isinstance(payload, dict) else None if not isinstance(result, dict): + if (isinstance(payload, dict) and payload.get('status') == 'failed' + and payload.get('failure_code') == 'retryable_infrastructure'): + raise RetryableRolloutFailure('service group exhausted infrastructure attempts') from harborrl.backends.slime_v032.rollout_service_client import ( ServiceRolloutError, ) @@ -177,10 +204,13 @@ async def request_group(group): try: results = await asyncio.gather(*pending, return_exceptions=True) # Retain independent groups' evidence, but never export a partial batch. - for result in results: - if isinstance(result, BaseException): - raise result + errors = [result for result in results if isinstance(result, BaseException)] + if errors: + raise next((exc for exc in errors if not isinstance(exc, RetryableRolloutFailure)), errors[0]) return results + except RetryableRolloutFailure: + # Every group settled before retry; new generations use fresh keys. + raise except BaseException: # HTTP workers keep running until the manager acknowledges cancellation. try: @@ -190,6 +220,132 @@ async def request_group(group): raise + + +def hub_rollout_enabled(): + """True when hub dispatch is configured via env or the shared JSON file. + + Ray workers inherit the raylet's startup environment on platform-boot + strapped clusters, so the shared file is the reliable carrier.""" + import json as _json + if os.environ.get("HARBORRL_HUB_URL"): + return True + env_file = os.environ.get( + "HARBORRL_HUB_ENV_FILE", + "") + if env_file: + try: + return bool(_json.loads(Path(env_file).read_text(encoding="utf-8")).get("HARBORRL_HUB_URL")) + except (OSError, ValueError): + return False + return False + +async def run_hub_groups(args, groups, rollout_id): + """Dispatch every (group, slot) to the hub; workers execute full trials.""" + from harborrl.backends.slime_v032.hub_rollout_client import ( + HubRolloutError, client_from_environment, hub_attempt_request, + load_attempt_ir, + ) + from harborrl.backends.slime_v032.rollout_service_client import ( + fetch_pool_states, service_group_request, + ) + + client = client_from_environment() + import json as _json + _extra = {} + _env_file = os.environ.get( + "HARBORRL_HUB_ENV_FILE", + "") + try: + _extra = _json.loads(Path(_env_file).read_text(encoding="utf-8")) + except (OSError, ValueError): + _extra = {} + + def _hub_setting(name, default=None): + return os.environ.get(name) or _extra.get(name) or default + + serving_endpoint = _hub_setting("HARBORRL_HUB_SERVING_ENDPOINT") + hf_ckpt = _hub_setting("HARBORRL_HUB_HF_CKPT") + if not serving_endpoint or not hf_ckpt: + raise HubRolloutError( + "hub rollout requires HARBORRL_HUB_SERVING_ENDPOINT and HARBORRL_HUB_HF_CKPT") + tokenizer_digest = _hub_setting("HARBORRL_HUB_TOKENIZER_DIGEST", "") + template_digest = _hub_setting("HARBORRL_HUB_TEMPLATE_DIGEST", "") + model_tag = _hub_setting("HARBORRL_HUB_MODEL_TAG", "qwen3-8B") + max_output_tokens = int(_hub_setting("HARBORRL_HUB_MAX_OUTPUT_TOKENS", "8192")) + max_context = int(_hub_setting("HARBORRL_HUB_MAX_CONTEXT", "32768")) + sandbox = _json.loads(_hub_setting("HARBORRL_NATIVE_SANDBOX", "null")) + if sandbox is not None and not isinstance(sandbox, dict): + raise HubRolloutError("HARBORRL_NATIVE_SANDBOX must be an object or null") + audited_raw_logprobs = _hub_setting("HARBORRL_NATIVE_AUDITED_LOGPROBS", "0") == "1" + deadline = time.monotonic() + float( + _hub_setting("HARBORRL_HUB_ROLLOUT_TIMEOUT_S", "3600")) + # Service mode has the manager announce/activate the serving pool and + # publish the locked record; hub mode inlines it: read what the local + # rollout engine actually serves and lock that version into the run dir. + run_dir = os.environ.get("RUN_DIR") + if not run_dir: + raise HubRolloutError("hub rollout requires RUN_DIR") + # The trainer updates serving weights between rollouts. Re-admit the pool + # each time; reusing the first file would dispatch every later batch stale. + from harborrl.platform.policy_pool import publish_pool + router = f"http://{args.sglang_router_ip}:{args.sglang_router_port}" + states = await asyncio.to_thread(fetch_pool_states, router) + await asyncio.to_thread(publish_pool, states) + policy_version = lock_policy_version(args) + + params = sampling_params(args) + submitted = [] # (group, slot_id, task_id, request) + for group in groups: + base = service_group_request(group, params, rollout_id, policy_version) + for slot in base["slots"]: + request_ = hub_attempt_request( + base, slot, serving_endpoint=serving_endpoint, hf_ckpt=hf_ckpt, + tokenizer_digest=tokenizer_digest, template_digest=template_digest, + model_tag=model_tag, max_output_tokens=max_output_tokens, + max_context=max_context, task_path=base["task"]["path"], + audited_raw_logprobs=audited_raw_logprobs) + if sandbox is not None: + request_["sandbox"] = sandbox + task_id = await asyncio.to_thread(client.submit_attempt, request_) + submitted.append((group, slot["slot_id"], task_id, request_)) + + pending_ids = {task_id for _, _, task_id, _ in submitted} + completed = {} + while pending_ids: + if time.monotonic() > deadline: + raise HubRolloutError( + f"hub rollout deadline reached with {len(pending_ids)} tasks pending") + response = await asyncio.to_thread(client.task_status, list(pending_ids)) + statuses = response.get("tasks", {}) + for task_id, state in statuses.items(): + status = state.get("status") + if status == "completed": + completed[task_id] = state.get("result") + pending_ids.discard(task_id) + elif status in ("failed", "unknown"): + raise HubRolloutError( + f"hub task {task_id} {status}: {state.get('error', '')}") + if pending_ids: + await asyncio.sleep(client.poll_interval) + + ir_groups = [] + for group in groups: + group_tasks = [(slot_id, task_id, request_) + for g, slot_id, task_id, request_ in submitted if g is group] + group_tasks.sort(key=lambda item: int(item[0])) + trajectories = [] + for slot_id, task_id, request_ in group_tasks: + ir = load_attempt_ir( + task_id, completed[task_id], + expected_policy_version=policy_version, + expected_task_digest=request_.get("task_digest") or None) + trajectories.append(ir) + bind_group_samples(group, trajectories) + ir_groups.append(trajectories) + return ir_groups + + async def run_native_groups(args, groups, policy_version, rollout_id): """Run every group concurrently and return only complete IR evidence.""" params = sampling_params(args) @@ -197,21 +353,40 @@ async def run_native_groups(args, groups, policy_version, rollout_id): ir_groups = await run_service_groups(args, groups, rollout_id) assert_locked_policy_versions(ir_groups, policy_version) return ir_groups + if hub_rollout_enabled(): + ir_groups = await run_hub_groups(args, groups, rollout_id) + assert_locked_policy_versions(ir_groups, policy_version) + return ir_groups pending = [asyncio.create_task( generate_group(args, group, params, rollout_id=rollout_id)) for group in groups] batch = asyncio.gather(*pending) try: # Keep parent cancellation from being forwarded twice during cleanup. results = await asyncio.shield(batch) - except BaseException: + except BaseException as exc: # Groups own their slot cleanup; finish it before shutting down the gateway. await cancel_and_wait(pending, batch) - # Close the cached runtime here unless an embedded run owns the loop: - # run_embedded's failure handler closes it after the loop unwinds, so - # the original error is what propagates. - from harborrl.rollout import runtime as _runtime - loop = getattr(_runtime, "_EMBEDDED_LOOP", None) - if not (loop is not None and loop.is_running()): + from harborrl.rollout import runtime as runtime_module + from harborrl.rollout.generations import ACTIVE_GENERATION + from harborrl.rollout.harbor_job.reliability import ( + CleanupUnresolved, + RetryableRolloutFailure, + ) + current = runtime_module._RUNTIME + if (isinstance(exc, RetryableRolloutFailure) and current is not None + and getattr(getattr(current, 'sandbox_admission', None), 'blocked', False)): + close_runtime() + raise CleanupUnresolved('sibling cleanup unresolved; rollout rerun forbidden') from exc + if isinstance(exc, RetryableRolloutFailure): + for task in pending: + if not task.cancelled() and task.done() and task.exception() is not None: + other = task.exception() + if not isinstance(other, RetryableRolloutFailure): + close_runtime() + raise other + loop = getattr(runtime_module, "_EMBEDDED_LOOP", None) + if (not (loop is not None and loop.is_running()) + and (not isinstance(exc, RetryableRolloutFailure) or ACTIVE_GENERATION.get() is None)): close_runtime() raise ir_groups = [] @@ -321,7 +496,47 @@ def generate_rollout( if runner is None: async def runner(args_, groups_, policy_version): return await run_native_groups(args_, groups_, policy_version, rollout_id) - ir_groups = asyncio.run(runner(args, groups, None)) + if os.environ.get('HARBORRL_NATIVE_SANDBOX', 'null') != 'null': + native_runner = runner + + async def runner(args_, groups_, policy_version): + import json + + from harborrl.rollout.generations import ( + GenerationJournal, + GenerationPolicy, + ) + + if os.environ.get('HARBORRL_ROLLOUT_SERVICE_URL'): + _, version = await prepare_service_policy(args_) + else: + config = runtime_config_from_args(args_) + runtime_ = await runtime(config, tokenizer_loader=slime_tokenizer_loader(args_)) + version = current_policy_version(runtime_) + policy = GenerationPolicy(**json.loads( + os.environ.get('HARBORRL_NATIVE_GENERATION_POLICY', '{}'))) + journal = GenerationJournal(os.environ['RUN_DIR'], policy) + inputs = {'sampling': sampling_params(args_), 'groups': [ + {'group_index': group_index_of(group), 'tasks': [task_entry(sample) for sample in group], + 'slots': [str(index) for index in range(len(group))]} for group in groups_]} + + def discard(): + for group in groups_: + for sample in group: + sample.metadata.pop('native_ir', None) + sample.reward = None + sample.response = None + + async def run(generation): + return await native_runner(args_, groups_, version) + + def validate(irs): + export_training_batch(irs, group_size=expected_size, + rollout_id_base=rollout_id * batch_size) + + return await journal.execute(rollout_id, inputs, version, run, + discard=discard, validate=validate) + ir_groups = run_embedded(runner(args, groups, None)) policy_version = lock_policy_version(args) assert_locked_policy_versions(ir_groups, policy_version) batch = export_training_batch( diff --git a/harborrl/backends/slime_v032/rollout_service_client.py b/harborrl/backends/slime_v032/rollout_service_client.py index 161fb24f2..25f5ebf07 100644 --- a/harborrl/backends/slime_v032/rollout_service_client.py +++ b/harborrl/backends/slime_v032/rollout_service_client.py @@ -1,220 +1,231 @@ -"""SlimeAdapter HTTP client (P3): complete groups from the RolloutService. - -The GPU job never trusts a GroupResult: every manifest digest is recomputed, -identities are checked against the request, the group must be complete with -at least two RL_READY slots, and the policy version must be the locked one. -After a transport timeout the client queries status; it never resubmits. -""" -from __future__ import annotations - -import json -import time -from pathlib import Path -from urllib import error, parse, request - -from harborrl.rollout.runtime import task_entry -from harborrl.trajectories.native import ( - canonical_sampling, - digest, - read_json, - require_ready, -) - -SERVICE_SCHEMA = "harborrl-rollout-service-v1" - - -def fetch_pool_states(endpoint, *, timeout=120, opener=None): - """Read the serving pool states directly from the SGLang router. - - Mirrors SGLangBackend.pool_states without a tokenizer: the GPU job calls - this before asking the manager to admit the version it currently serves. - """ - import json as json_module - from urllib import request as url_request - - opener = opener or url_request.build_opener(url_request.ProxyHandler({})) - endpoint = endpoint.rstrip("/") - - def get(url): - with opener.open(url_request.Request(url), timeout=timeout) as response: - return json_module.load(response) - - workers = get(endpoint + "/workers").get("workers") - if not isinstance(workers, list) or not workers: - raise ServiceRolloutError("serving router returned no workers") - states = [] - for worker in workers: - engine = worker.get("url") if isinstance(worker, dict) else None - if not isinstance(engine, str) or not engine.strip(): - raise ServiceRolloutError("serving router returned an invalid worker URL") - engine = engine.rstrip("/") - version = get(engine + "/get_weight_version").get("weight_version") - if not isinstance(version, str) or not version.strip(): - raise ServiceRolloutError("missing serving weight version") - states.append({"endpoint": engine, "healthy": True, - "weight_version": version}) - versions = {state["weight_version"] for state in states} - if len(versions) != 1: - raise ServiceRolloutError( - f"serving pool is mid-update; retry after all engines agree: {sorted(versions)}") - return states - - -class ServiceRolloutError(RuntimeError): - def __init__(self, message, *, status=None, code=None): - super().__init__(message) - self.status, self.code = status, code - - -def service_group_request(group, sampling_params, rollout_id, policy_version): - """Build one GroupRequest from a Slime sample group.""" - entries = [task_entry(sample) for sample in group] - if any(entry != entries[0] for entry in entries[1:]): - raise ValueError("native rollout group mixes task locks") - indexes = {getattr(sample, "group_index", None) for sample in group} - if len(indexes) != 1 or type(next(iter(indexes), None)) is not int: - raise ValueError("Slime must provide one group identity before native generation") - index = indexes.pop() - return { - "group_id": f"group-{index}", - "rollout_id": int(rollout_id), - "group_index": index, - "policy_version": str(policy_version), - "task": entries[0], - "sampling": {key: sampling_params.get(key) for key in - ("temperature", "top_p", "top_k", "max_new_tokens", "stop")}, - "slots": [{"slot_id": str(slot)} for slot in range(len(group))], - } - - -class RolloutServiceClient: - """Synchronous urllib client; safe to call from asyncio.to_thread.""" - - def __init__(self, base_url, run_id, token, *, timeout=120, poll_interval=1.0, - opener=None): - self.base_url = base_url.rstrip("/") - self.run_id = run_id - self.token = token - self.timeout = timeout - self.poll_interval = poll_interval - self.opener = opener or request.build_opener(request.ProxyHandler({})) - - def _request(self, method, path, body=None): - url = f"{self.base_url}{path}" - data = json.dumps(body).encode() if body is not None else None - headers = {"Content-Type": "application/json"} - if self.token: - headers["Authorization"] = f"Bearer {self.token}" - req = request.Request(url, data=data, headers=headers, method=method) - try: - with self.opener.open(req, timeout=self.timeout) as response: - return json.load(response) - except error.HTTPError as exc: - try: - payload = json.load(exc) - except (ValueError, OSError): - payload = {"error": {"type": "transport", "message": str(exc)}} - error_payload = payload.get("error", payload) - raise ServiceRolloutError( - f"{method} {path}: {error_payload.get('type')}: " - f"{error_payload.get('message')}", - status=exc.code, code=error_payload.get("type")) from exc - except (error.URLError, OSError, ValueError) as exc: - raise ServiceRolloutError(f"{method} {path}: {exc}", - code="transport") from exc - - def health(self): - return self._request("GET", "/healthz") - - def register(self, manifest): - return self._request("POST", f"/runs/{parse.quote(self.run_id)}/register", - {"manifest": manifest}) - - def submit_group(self, group_request, *, max_attempts=None): - """Submit idempotently; on timeout poll status, never regenerate.""" - path = f"/runs/{parse.quote(self.run_id)}/groups" - try: - status = self._request('POST', path, group_request) - except ServiceRolloutError as exc: - if exc.code != 'transport': - raise - status = self.group_status(group_request['group_id']) - polls = 0 - while status['status'] in ('queued', 'running'): - if max_attempts is not None and polls >= max_attempts: - raise ServiceRolloutError('group polling deadline reached', code='transport') - polls += 1 - time.sleep(self.poll_interval) - status = self.group_status(group_request["group_id"]) - return status - - def group_status(self, group_id): - return self._request( - "GET", f"/runs/{parse.quote(self.run_id)}/groups/{parse.quote(group_id)}") - - def cancel_group(self, group_id): - return self._request( - "POST", - f"/runs/{parse.quote(self.run_id)}/groups/{parse.quote(group_id)}/cancel") - - def activate_policy(self, states, expected): - return self._request( - "POST", f"/runs/{parse.quote(self.run_id)}/policy/activate", - {"states": states, "expected": str(expected)}) - - def announce_serving(self, router_url): - return self._request( - "POST", f"/runs/{parse.quote(self.run_id)}/serving/announce", - {"router_url": router_url}) - - def drain(self): - return self._request("POST", f"/runs/{parse.quote(self.run_id)}/drain") - - def cancel_run(self): - return self._request("POST", f"/runs/{parse.quote(self.run_id)}/cancel") - - -def load_group_result(run_id, group_request, result, *, allow_synthetic=False): - """Validate a GroupResult and load its trajectory manifests in slot order.""" - if not isinstance(result, dict): - raise ServiceRolloutError("group result must be a mapping") - if result.get("status") != "complete": - raise ServiceRolloutError( - f"group is {result.get('status')!r}, not complete: {result.get('error', '')}") - if result.get("run_id") != run_id or result.get("group_id") != group_request["group_id"]: - raise ServiceRolloutError("group result identity does not match the request") - if result.get("request_digest") != digest(group_request): - raise ServiceRolloutError("group result digest does not match the request") - slots = result.get("slots") - expected = [slot["slot_id"] for slot in group_request["slots"]] - if (not isinstance(slots, list) or len(slots) != len(expected) or len(slots) < 2 - or [slot.get("slot_id") for slot in slots] != expected): - raise ServiceRolloutError("group result is incomplete or reordered") - sampling_sha = digest(canonical_sampling(group_request["sampling"])) - trajectories = [] - for descriptor, slot in zip(group_request["slots"], slots): - if slot.get("sampling_digest") != sampling_sha: - raise ServiceRolloutError(f"slot {descriptor['slot_id']} sampling digest differs from the request") - path = Path(slot["manifest_path"]) - try: - payload = read_json(path) - except (OSError, ValueError) as exc: - raise ServiceRolloutError(f"cannot read slot manifest: {exc}") from exc - if digest(payload) != slot.get("manifest_sha256"): - raise ServiceRolloutError(f"slot {descriptor['slot_id']} manifest digest mismatch") - identity = payload.get("identity", {}) - if identity.get("sampling_digest") != sampling_sha: - raise ServiceRolloutError(f"slot {descriptor['slot_id']} manifest sampling differs from the request") - if (identity.get("policy_version") != group_request["policy_version"] - or identity.get("task_digest") != group_request["task"]["task_digest"] - or identity.get("run_id") != run_id - or identity.get("group_id") != group_request["group_id"] - or identity.get("slot_id") != descriptor["slot_id"]): - raise ServiceRolloutError( - f"slot {descriptor['slot_id']} identity differs from the request") - try: - require_ready(payload, allow_synthetic=allow_synthetic) - except ValueError as exc: - raise ServiceRolloutError(f"slot {descriptor['slot_id']}: {exc}") from exc - trajectories.append(payload) - return trajectories +"""SlimeAdapter HTTP client (P3): complete groups from the RolloutService. + +The GPU job never trusts a GroupResult: every manifest digest is recomputed, +identities are checked against the request, the group must be complete with +at least two RL_READY slots, and the policy version must be the locked one. +After a transport timeout the client queries status; it never resubmits. +""" +from __future__ import annotations + +import json +import time +from pathlib import Path +from urllib import error, parse, request + +from harborrl.rollout.runtime import task_entry +from harborrl.trajectories.native import ( + canonical_sampling, + digest, + read_json, + require_ready, +) + +SERVICE_SCHEMA = "harborrl-rollout-service-v1" + + +def fetch_pool_states(endpoint, *, timeout=120, opener=None): + """Read the serving pool states directly from the SGLang router. + + Mirrors SGLangBackend.pool_states without a tokenizer: the GPU job calls + this before asking the manager to admit the version it currently serves. + """ + import json as json_module + from urllib import request as url_request + + opener = opener or url_request.build_opener(url_request.ProxyHandler({})) + endpoint = endpoint.rstrip("/") + + def get(url): + with opener.open(url_request.Request(url), timeout=timeout) as response: + return json_module.load(response) + + workers = get(endpoint + "/workers").get("workers") + if not isinstance(workers, list) or not workers: + raise ServiceRolloutError("serving router returned no workers") + states = [] + for worker in workers: + engine = worker.get("url") if isinstance(worker, dict) else None + if not isinstance(engine, str) or not engine.strip(): + raise ServiceRolloutError("serving router returned an invalid worker URL") + engine = engine.rstrip("/") + version = get(engine + "/get_weight_version").get("weight_version") + if not isinstance(version, str) or not version.strip(): + raise ServiceRolloutError("missing serving weight version") + states.append({"endpoint": engine, "healthy": True, + "weight_version": version}) + versions = {state["weight_version"] for state in states} + if len(versions) != 1: + raise ServiceRolloutError( + f"serving pool is mid-update; retry after all engines agree: {sorted(versions)}") + return states + + +class ServiceRolloutError(RuntimeError): + def __init__(self, message, *, status=None, code=None): + super().__init__(message) + self.status, self.code = status, code + + +def service_group_request(group, sampling_params, rollout_id, policy_version): + """Build one GroupRequest from a Slime sample group.""" + entries = [task_entry(sample) for sample in group] + if any(entry != entries[0] for entry in entries[1:]): + raise ValueError("native rollout group mixes task locks") + indexes = {getattr(sample, "group_index", None) for sample in group} + if len(indexes) != 1 or type(next(iter(indexes), None)) is not int: + raise ValueError("Slime must provide one group identity before native generation") + index = indexes.pop() + from harborrl.rollout.generations import ACTIVE_GENERATION, generation_group_id + context = ACTIVE_GENERATION.get() + payload = { + "group_id": f"group-{index}", + "rollout_id": int(rollout_id), + "group_index": index, + "policy_version": str(policy_version), + "task": entries[0], + "sampling": {key: sampling_params.get(key) for key in + ("temperature", "top_p", "top_k", "max_new_tokens", "stop")}, + "slots": [{"slot_id": str(slot)} for slot in range(len(group))], + } + if context is not None: + payload['rollout_generation'] = context['generation'] + payload['group_id'] = generation_group_id(rollout_id, context['generation'], index) + return payload + + +class RolloutServiceClient: + """Synchronous urllib client; safe to call from asyncio.to_thread.""" + + def __init__(self, base_url, run_id, token, *, timeout=120, poll_interval=1.0, + opener=None): + self.base_url = base_url.rstrip("/") + self.run_id = run_id + self.token = token + self.timeout = timeout + self.poll_interval = poll_interval + self.opener = opener or request.build_opener(request.ProxyHandler({})) + + def _request(self, method, path, body=None): + url = f"{self.base_url}{path}" + data = json.dumps(body).encode() if body is not None else None + headers = {"Content-Type": "application/json"} + if self.token: + headers["Authorization"] = f"Bearer {self.token}" + req = request.Request(url, data=data, headers=headers, method=method) + try: + with self.opener.open(req, timeout=self.timeout) as response: + return json.load(response) + except error.HTTPError as exc: + try: + payload = json.load(exc) + except (ValueError, OSError): + payload = {"error": {"type": "transport", "message": str(exc)}} + error_payload = payload.get("error", payload) + raise ServiceRolloutError( + f"{method} {path}: {error_payload.get('type')}: " + f"{error_payload.get('message')}", + status=exc.code, code=error_payload.get("type")) from exc + except (error.URLError, OSError, ValueError) as exc: + raise ServiceRolloutError(f"{method} {path}: {exc}", + code="transport") from exc + + def health(self): + return self._request("GET", "/healthz") + + def register(self, manifest): + return self._request("POST", f"/runs/{parse.quote(self.run_id)}/register", + {"manifest": manifest}) + + def submit_group(self, group_request, *, max_attempts=None): + """Submit idempotently; on timeout poll status, never regenerate.""" + path = f"/runs/{parse.quote(self.run_id)}/groups" + try: + status = self._request('POST', path, group_request) + except ServiceRolloutError as exc: + if exc.code != 'transport': + raise + status = self.group_status(group_request['group_id']) + polls = 0 + while status['status'] in ('queued', 'running'): + if max_attempts is not None and polls >= max_attempts: + raise ServiceRolloutError('group polling deadline reached', code='transport') + polls += 1 + time.sleep(self.poll_interval) + status = self.group_status(group_request["group_id"]) + return status + + def group_status(self, group_id): + return self._request( + "GET", f"/runs/{parse.quote(self.run_id)}/groups/{parse.quote(group_id)}") + + def cancel_group(self, group_id): + return self._request( + "POST", + f"/runs/{parse.quote(self.run_id)}/groups/{parse.quote(group_id)}/cancel") + + def activate_policy(self, states, expected): + return self._request( + "POST", f"/runs/{parse.quote(self.run_id)}/policy/activate", + {"states": states, "expected": str(expected)}) + + def announce_serving(self, router_url): + return self._request( + "POST", f"/runs/{parse.quote(self.run_id)}/serving/announce", + {"router_url": router_url}) + + def drain(self): + return self._request("POST", f"/runs/{parse.quote(self.run_id)}/drain") + + def cancel_run(self): + return self._request("POST", f"/runs/{parse.quote(self.run_id)}/cancel") + + +def load_group_result(run_id, group_request, result, *, allow_synthetic=False): + """Validate a GroupResult and load its trajectory manifests in slot order.""" + if not isinstance(result, dict): + raise ServiceRolloutError("group result must be a mapping") + if result.get("status") != "complete": + raise ServiceRolloutError( + f"group is {result.get('status')!r}, not complete: {result.get('error', '')}") + if result.get("run_id") != run_id or result.get("group_id") != group_request["group_id"]: + raise ServiceRolloutError("group result identity does not match the request") + if result.get("request_digest") != digest(group_request): + raise ServiceRolloutError("group result digest does not match the request") + slots = result.get("slots") + expected = [slot["slot_id"] for slot in group_request["slots"]] + if (not isinstance(slots, list) or len(slots) != len(expected) or len(slots) < 2 + or [slot.get("slot_id") for slot in slots] != expected): + raise ServiceRolloutError("group result is incomplete or reordered") + sampling_sha = digest(canonical_sampling(group_request["sampling"])) + trajectories = [] + for descriptor, slot in zip(group_request["slots"], slots): + if slot.get("sampling_digest") != sampling_sha: + raise ServiceRolloutError(f"slot {descriptor['slot_id']} sampling digest differs from the request") + path = Path(slot["manifest_path"]) + try: + payload = read_json(path) + except (OSError, ValueError) as exc: + raise ServiceRolloutError(f"cannot read slot manifest: {exc}") from exc + if digest(payload) != slot.get("manifest_sha256"): + raise ServiceRolloutError(f"slot {descriptor['slot_id']} manifest digest mismatch") + identity = payload.get("identity", {}) + if identity.get("sampling_digest") != sampling_sha: + raise ServiceRolloutError(f"slot {descriptor['slot_id']} manifest sampling differs from the request") + if (identity.get("policy_version") != group_request["policy_version"] + or identity.get("task_digest") != group_request["task"]["task_digest"] + or identity.get("run_id") != run_id + or identity.get("group_id") != group_request["group_id"] + or identity.get("slot_id") != descriptor["slot_id"]): + raise ServiceRolloutError( + f"slot {descriptor['slot_id']} identity differs from the request") + try: + require_ready(payload, allow_synthetic=allow_synthetic) + if 'rollout_generation' in group_request: + from harborrl.rollout.generations import generation_batch_id + if identity.get('batch_id') != generation_batch_id( + group_request['rollout_id'], group_request['rollout_generation']): + raise ValueError('slot belongs to a different rollout generation') + except ValueError as exc: + raise ServiceRolloutError(f"slot {descriptor['slot_id']}: {exc}") from exc + trajectories.append(payload) + return trajectories diff --git a/harborrl/config/native.py b/harborrl/config/native.py index 43a3a2808..00625847c 100644 --- a/harborrl/config/native.py +++ b/harborrl/config/native.py @@ -15,12 +15,14 @@ 'harbor': {'python', 'version', 'workers', 'runner_transport', 'environment'}, 'gateway': {'host', 'port', 'advertised_url', 'tokenizer_digest', 'template_digest', 'audited_raw_logprobs'}, 'model': {'checkpoint', 'reference', 'args_file'}, - 'training': {'num_rollout', 'learning_rate', 'save_interval', 'backend_contract', 'seed', 'export_hf'}, + 'training': {'num_rollout', 'learning_rate', 'save_interval', 'backend_contract', 'seed', 'export_hf', + 'resume', 'max_tokens_per_gpu', 'max_ckpt_keep'}, 'sampling': {'group_size', 'groups_per_batch', 'max_attempts', 'max_tokens', 'max_context'}, 'deployment': {'layout', 'num_gpus', 'actor_gpus', 'rollout_gpus', 'actor_tensor_parallel_size', 'rollout_gpus_per_engine'}, 'output': {'root'}, } -OPTIONAL = {'harbor': {'runner_transport', 'environment'}, 'training': {'seed', 'export_hf'}} +OPTIONAL = {'harbor': {'runner_transport', 'environment'}, + 'training': {'seed', 'export_hf', 'resume', 'max_tokens_per_gpu', 'max_ckpt_keep'}} class SelectedConfig(dict): @@ -77,20 +79,27 @@ def validate(config, path): config['training'].setdefault( 'backend_contract', 'slime-v0.3.2-native-v1') config['training'].setdefault('export_hf', False) + config['training'].setdefault('resume', None) + config['training'].setdefault('max_tokens_per_gpu', 16384) + config['training'].setdefault('max_ckpt_keep', 2) for section, fields in FIELDS.items(): actual = set(config[section]) if isinstance(config[section], dict) else set() if not isinstance(config[section], dict) or not fields - OPTIONAL.get(section, set()) <= actual <= fields: raise ValueError(f'{section} requires exactly {sorted(fields)}') for section, key in [('tasks','catalog'), ('harness','profile'), ('harbor','python'), - ('model','checkpoint'), ('model','reference'), ('output','root')]: + ('model','checkpoint'), ('model','reference'), ('output','root'), + ('training','resume')]: value = config[section][key] - if not isinstance(value, str) or not value: + if (section, key) == ('training', 'resume') and value is None: + continue + if not isinstance(value, str) or not value.strip(): raise ValueError(f'{section}.{key} must be a path') expanded = Path(value).expanduser() absolute = expanded if expanded.is_absolute() else Path(path).parent / expanded config[section][key] = str(Path(os.path.abspath(absolute))) for section, keys in [('sampling', FIELDS['sampling']), ('deployment', FIELDS['deployment'] - {'layout'}), - ('training', {'num_rollout','save_interval'}), ('gateway', {'port'})]: + ('training', {'num_rollout','save_interval','max_tokens_per_gpu','max_ckpt_keep'}), + ('gateway', {'port'})]: for key in keys: if type(config[section][key]) is not int or config[section][key] <= 0: raise ValueError(f'{section}.{key} must be a positive integer') @@ -132,7 +141,7 @@ def validate(config, path): if d['actor_gpus'] % d['actor_tensor_parallel_size'] or d['rollout_gpus'] % d['rollout_gpus_per_engine']: raise ValueError('deployment GPU counts must be divisible by their tensor parallel sizes') preset = config['model']['args_file'] - if not isinstance(preset,str) or not re.fullmatch(r'[A-Za-z0-9_-]+',preset): + if not isinstance(preset,str) or not re.fullmatch(r'[A-Za-z0-9._-]+',preset): raise ValueError('model.args_file must name a Slime model preset; SLIME_DIR is checked by doctor') for key in ('tokenizer_digest', 'template_digest'): if not re.fullmatch(r'[0-9a-f]{64}', g[key]): diff --git a/harborrl/deployment/controller.py b/harborrl/deployment/controller.py index 4cb937a64..a85bcc13c 100644 --- a/harborrl/deployment/controller.py +++ b/harborrl/deployment/controller.py @@ -22,7 +22,8 @@ from urllib.parse import urlsplit from harborrl.config import ROOT -from harborrl.deployment import remote +from harborrl.deployment import provision, remote +from harborrl.deployment.preflight import gpu_checks from harborrl.deployment.schema import destination from harborrl.deployment.training_target import SshTrainingTarget from harborrl.platform.evidence import ( @@ -362,42 +363,58 @@ def dispatch_hub(plan, deployment, *, checks): def dispatch_service(plan, deployment, *, checks): manager, gpu, storage = deployment["manager"], deployment["gpu_target"], deployment["storage"] - - # Hub mode: submit to long-running manager instead of direct execution - mode = manager.get("mode") - if mode == "hub": + if manager.get("mode") == "hub": return dispatch_hub(plan, deployment, checks=checks) - - # Standard service mode execution config = plan["config"] root = new_run_root(storage["run_root"]) root.mkdir(parents=True, mode=0o700) run_id = root.name - # Concurrent dispatches on one manager must not collide on the declared - # ports; patch every consumer's view before the environment is rendered. - deployment = _with_allocated_ports(deployment, run_id) - manager = deployment["manager"] - - catalog_path, prompt_path = _materialize(plan, root) - source = _source_audit(root) - environment = run_environment(plan, root, catalog_path, prompt_path) - token = _ensure_token(manager["run_token_file"]) - environment = _rollout_environment(plan, deployment, environment) - - sampling = config["sampling"] - concurrency = sampling["group_size"] * sampling["groups_per_batch"] - service = RolloutService( - run_root=root, - runtime_factory=_runtime_factory( - deployment, environment, - concurrency_limit=concurrency, group_size=sampling["group_size"]), - token_file=manager["run_token_file"]) - control = make_control_server(service, host=manager["bind"], - port=manager["control_port"]) - control_thread = None - target = None + provision_spec = gpu.get("provision") + provision_record = None + service = control = control_thread = target = None exit_code = 1 try: + # Concurrent dispatches on one manager must not collide on the declared + # ports; patch every consumer's view before the environment is rendered. + # Allocation is per-run state, so it runs inside the guarded region: a + # partial allocation would otherwise strand slots for the life of the + # manager process, and repeated failures would exhaust the range. + deployment = _with_allocated_ports(deployment, run_id) + manager, gpu = deployment["manager"], deployment["gpu_target"] + if provision_spec is not None: + # The machine does not exist until up returns, so nothing may dial + # it before this point; the record is evidence the moment it is + # obtained, and down runs however this dispatch ends. + provision_record = provision.up( + provision_spec, evidence_path=root / "gpu-provision.json") + gpu = {**gpu, "ssh": provision.ssh_spec(provision_record)} + deployment = {**deployment, "gpu_target": gpu} + # The checks deferred at plan time are exactly the ones that need a + # live machine; rerun them now and fail before any launch. + checks = list(checks) + gpu_checks(plan, deployment) + failed = [check for check in checks if not check["ok"]] + if failed: + raise RuntimeError( + "provisioned GPU target failed preflight: " + + "; ".join(f"{check['check']}: {check['detail']}" + for check in failed)) + + catalog_path, prompt_path = _materialize(plan, root) + source = _source_audit(root) + environment = run_environment(plan, root, catalog_path, prompt_path) + token = _ensure_token(manager["run_token_file"]) + environment = _rollout_environment(plan, deployment, environment) + + sampling = config["sampling"] + concurrency = sampling["group_size"] * sampling["groups_per_batch"] + service = RolloutService( + run_root=root, + runtime_factory=_runtime_factory( + deployment, environment, + concurrency_limit=concurrency, group_size=sampling["group_size"]), + token_file=manager["run_token_file"]) + control = make_control_server(service, host=manager["bind"], + port=manager["control_port"]) service.register_run(run_id, { "run_id": run_id, "deployment_source": plan["deployment"]["source"], "source_commit": source["commit"], @@ -455,11 +472,25 @@ def forward_signal(signum, frame): finally: with contextlib.suppress(Exception): service.drain_run(run_id) - service.close() + cleanup_error = None + actions = [] + if service is not None: + actions.append(service.close) if control_thread is not None: - control.shutdown() - control_thread.join(5) - control.server_close() - _release_run_ports(run_id) + actions.extend([control.shutdown, lambda: control_thread.join(5)]) + if control is not None: + actions.append(control.server_close) + if provision_record is not None: + actions.append(lambda: provision.down( + provision_spec, provision_record, + evidence_path=root / "gpu-provision-release.json")) + actions.append(lambda: _release_run_ports(run_id)) + for action in actions: + try: + action() + except Exception as exc: + cleanup_error = cleanup_error or exc print(json.dumps({"run_dir": str(root), "exit_code": exit_code}), file=sys.stderr) + if cleanup_error is not None and sys.exc_info()[0] is None: + raise cleanup_error return exit_code diff --git a/harborrl/deployment/hub_rollout_executor.py b/harborrl/deployment/hub_rollout_executor.py index abde1855d..641afeb9b 100644 --- a/harborrl/deployment/hub_rollout_executor.py +++ b/harborrl/deployment/hub_rollout_executor.py @@ -3,10 +3,12 @@ The hub server deliberately holds no Gateway and no RolloutRuntime, so a pulled rollout task is executed here on the worker: - 1. start a local Gateway + TraceRegistry for this task, - 2. register the attempt to obtain its credential, - 3. hand the runner a request whose gateway_url points at that gateway, - 4. speak the runner's stdin/stdout protocol (prepared -> run -> terminal). + 1. start a local Gateway + TraceRegistry for this attempt, + 2. delegate the full trial to harbor_job.coordinator.run_attempt (which + registers the attempt credential, drives the runner protocol, audits + the session and assembles the trajectory IR), + 3. publish the IR under the attempt root (shared storage) and report + {success, ir_path, ir_sha256, reward} back to the hub. The gateway must be reachable from inside the sandbox, so the advertised origin is composed from --gateway-host (defaults to the local IP) and the @@ -14,16 +16,15 @@ """ from __future__ import annotations -import asyncio import json -import secrets +import os +import shutil import socket import threading from pathlib import Path from harborrl.gateway.server import Gateway, make_server from harborrl.gateway.trace import TraceRegistry -from harborrl.trajectories.native import Identity, RewardProfile, digest, publish def local_ip(): @@ -45,6 +46,7 @@ def sampling_digest_for(max_output_tokens, stop=None): is the profile output budget, and stop is the caller's sequence list (empty when unspecified). """ + from harborrl.trajectories.native import digest return digest({ # floats on purpose: messages.convert() defaults temperature/top_p to # 1.0, and digest() hashes JSON text, so 1 and 1.0 hash differently. @@ -57,7 +59,7 @@ def sampling_digest_for(max_output_tokens, stop=None): class RolloutExecutor: - """Run one rollout group request against a locally hosted gateway.""" + """Run one rollout attempt request against a locally hosted gateway.""" def __init__(self, *, run_root, task_path, profile, runner_python, source_dir, gateway_host=None, tracing=True, log=print): @@ -71,15 +73,25 @@ def __init__(self, *, run_root, task_path, profile, runner_python, source_dir, self.log = log def execute(self, group_request): - """Execute one group request; returns a result dict for the hub.""" - task_id = group_request.get('task_id') or 'rollout_' + secrets.token_hex(8) + """Execute one attempt request; returns a result dict for the hub.""" + import asyncio + + shared_root = os.environ.get('HARBORRL_HUB_ATTEMPT_MIRROR', '').strip() + if not shared_root or not Path(shared_root).is_absolute(): + raise ValueError( + 'HARBORRL_HUB_ATTEMPT_MIRROR must be an absolute shared directory ' + 'visible at the same path to workers and trainer') + + task_id = group_request.get('task_id') or 'rollout_' + __import__('secrets').token_hex(8) run_id = group_request.get('run_id', 'adhoc') group_id = group_request.get('group_id', task_id) slot_id = str(group_request.get('slot_id', '0')) attempt_id = f'{task_id}-{slot_id}' + # run_attempt creates the attempt root itself (exist_ok=False) and + # must stay its only owner; pre-creating it here made every retry + # fail with FileExistsError. attempt_root = self.run_root / attempt_id - attempt_root.mkdir(parents=True, exist_ok=True) trace_root = attempt_root / 'traces' registry = TraceRegistry(trace_root) @@ -104,7 +116,7 @@ def execute(self, group_request): # The tokenizer cannot cross JSON, so load it locally from the # checkpoint and verify it still matches the run's lock digests. from transformers import AutoTokenizer - ckpt = group_request.get('hf_ckpt') or self.hf_ckpt + ckpt = group_request.get('hf_ckpt') if not ckpt: raise ValueError('live rollout requires hf_ckpt to load the tokenizer') tokenizer = AutoTokenizer.from_pretrained(ckpt, trust_remote_code=True) @@ -117,13 +129,18 @@ def execute(self, group_request): if expect_tpl and tpl_digest != expect_tpl: raise ValueError(f'template digest mismatch: {tpl_digest} != {expect_tpl}') from harborrl.gateway.sglang_backend import SGLangBackend + audited = group_request.get('audited_raw_logprobs', False) + if type(audited) is not bool: + raise ValueError('audited_raw_logprobs must be boolean') backend = SGLangBackend( endpoint, tokenizer, model.adapter, tokenizer_digest=tok_digest, template_digest=tpl_digest, - max_context=group_request.get('max_context', 32768)) + max_context=group_request.get('max_context', 32768), + audited_raw_logprobs=audited) + max_output_tokens = group_request.get('max_output_tokens', 8192) gateway = Gateway(registry, backend, model=self.profile.get('model', 'policy'), - max_output_tokens=group_request.get('max_output_tokens', 8192)) + max_output_tokens=max_output_tokens) server = make_server(gateway, host='0.0.0.0', port=0) port = server.server_address[1] thread = threading.Thread(target=server.serve_forever, daemon=True, @@ -134,6 +151,9 @@ def execute(self, group_request): self.log(f'[ROLLOUT] gateway up at {advertised} (attempt {attempt_id})') try: + from harborrl.rollout.harbor_job.coordinator import run_attempt + from harborrl.trajectories.native import Identity, RewardProfile, digest + identity = Identity( run_id=run_id, batch_id=group_request.get('batch_id', 'batch'), @@ -146,77 +166,50 @@ def execute(self, group_request): harness_digest=digest(self.profile), reward_digest=RewardProfile().digest, sampling_digest=group_request.get('sampling_digest') - or sampling_digest_for(group_request.get('max_output_tokens', 8192), - group_request.get('stop')), + or sampling_digest_for(max_output_tokens, group_request.get('stop')), ) - # register() mints the attempt credential; the runner must hand - # exactly this token to the sandbox or the gateway rejects it. - attempt_credential = registry.register(identity, task_id) - - request = { - 'identity': identity.to_dict(), - 'task_path': str(self.task_path), - 'profile': self.profile, - 'gateway_url': advertised, - 'credential': attempt_credential, - 'output': str(attempt_root / 'runner'), - 'max_output_tokens': group_request.get('max_output_tokens', 8192), - } - - terminal = asyncio.run( - self._drive_runner(request, attempt_root)) - publish(attempt_root / 'terminal.json', terminal) - return {'success': terminal.get('type') == 'terminal', 'terminal': terminal, + + sandbox = group_request.get('sandbox') or None + reward_profile = RewardProfile( + **group_request['reward_profile']) if group_request.get('reward_profile') else RewardProfile() + + ir = asyncio.run(run_attempt( + identity, + task_path=str(self.task_path), + profile=self.profile, + gateway_url=advertised, + runner_python=self.runner_python, + root=attempt_root, + registry=registry, + reward_profile=reward_profile, + max_output_tokens=max_output_tokens, + sandbox=sandbox, + )) + ir_path = attempt_root / 'trajectory.v2.json' + ir_sha = digest(ir) + reward = ir.get('evaluation', {}).get('training_reward') + # The attempt runs on the worker's local disk (docker cannot bind + # mount through the sshfs share); mirror the IR to shared storage + # so the trainer can load and verify it, and report that path. + mirrored = Path(shared_root) / attempt_id + try: + mirrored.mkdir(parents=True, exist_ok=True) + for name in ('trajectory.v2.json', 'evaluation.json', 'terminal.json'): + src = attempt_root / name + if src.is_file(): + shutil.copy2(src, mirrored / name) + shared_ir = mirrored / 'trajectory.v2.json' + if digest(json.loads(shared_ir.read_text(encoding='utf-8'))) != ir_sha: + raise ValueError('mirrored IR digest mismatch') + ir_path = shared_ir + except OSError as exc: + raise RuntimeError(f'failed to mirror IR to shared storage: {exc}') + return {'success': True, + 'ir_path': str(ir_path), 'ir_sha256': ir_sha, + 'reward': reward, 'readiness': ir.get('readiness'), + 'integrity_errors': ir.get('integrity_errors'), 'attempt_root': str(attempt_root)} finally: server.shutdown() - server.server_close() + server.close() if hasattr(server, 'close') else server.server_close() thread.join(5) - - async def _drive_runner(self, request, attempt_root): - """Speak the runner stdin/stdout protocol to completion.""" - env = {**__import__('os').environ} - env['PYTHONPATH'] = self.source_dir - process = await asyncio.create_subprocess_exec( - self.runner_python, '-m', 'harborrl.rollout.harbor_job.runner', - cwd=self.source_dir, env=env, - stdin=asyncio.subprocess.PIPE, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE) - - process.stdin.write(json.dumps(request).encode() + b'\n') - await process.stdin.drain() - - terminal = None - try: - while True: - line = await process.stdout.readline() - if not line: - break - try: - event = json.loads(line) - except ValueError: - self.log(f'[ROLLOUT] non-JSON line: {line[:200]!r}') - continue - kind = event.get('type') - self.log(f'[ROLLOUT] runner event: {kind}') - if kind == 'prepared': - process.stdin.write(b'{"command":"run"}\n') - await process.stdin.drain() - elif kind in ('terminal', 'cancelled'): - terminal = event - break - finally: - with __import__('contextlib').suppress(Exception): - await asyncio.wait_for(process.wait(), timeout=60) - stderr = b'' - if process.stderr is not None: - with __import__('contextlib').suppress(Exception): - stderr = await process.stderr.read() - if stderr: - publish(attempt_root / 'runner.stderr.txt', - stderr.decode('utf-8', 'replace')[-8000:]) - - if terminal is None: - raise RuntimeError('runner exited before emitting a terminal record') - return terminal diff --git a/harborrl/deployment/hub_server.py b/harborrl/deployment/hub_server.py index 4efd41ee1..38040abc7 100644 --- a/harborrl/deployment/hub_server.py +++ b/harborrl/deployment/hub_server.py @@ -119,6 +119,11 @@ def __init__(self, *, hub_config: dict, run_root: str, max_concurrent_runs: int self.gpu_pool: Dict[str, GpuResource] = {} self.gpu_tasks: Dict[str, GpuTask] = {} self.rollout_tasks: Dict[str, RolloutTask] = {} + # Idempotency index for rollout submissions: (run_id, rollout_id, + # group_id, slot_id) -> task_id. Retried submits of the same logical + # slot must not enqueue a second worker execution. + self.rollout_index: Dict[str, str] = {} + self.reports_path = self.run_root / "hub-rollout-reports.jsonl" self.lock = threading.RLock() # Initialize GPU pool from config @@ -389,8 +394,16 @@ def report_gpu_status(self, gpu_id: str, task_id: str, status: dict) -> dict: return {"task_id": task_id, "acknowledged": True} def submit_rollout_task(self, run_id: str, group_request: dict) -> dict: - """Submit a rollout group task for worker processing.""" + """Submit a rollout attempt task for worker processing (idempotent per slot).""" with self.lock: + idem = "%s:%s:%s:%s" % (run_id, + group_request.get("rollout_id", ""), + group_request.get("group_id", ""), + group_request.get("slot_id", "")) + existing = self.rollout_index.get(idem) + if existing is not None and existing in self.rollout_tasks: + task = self.rollout_tasks[existing] + return {"task_id": existing, "status": task.status, "deduplicated": True} task_id = f"rollout_{secrets.token_hex(8)}" task = RolloutTask( task_id=task_id, @@ -399,6 +412,7 @@ def submit_rollout_task(self, run_id: str, group_request: dict) -> dict: request=group_request ) self.rollout_tasks[task_id] = task + self.rollout_index[idem] = task_id # Link to run run_info = self.runs.get(run_id) @@ -436,7 +450,7 @@ def pull_rollout_task(self, worker_id: str) -> Optional[dict]: } def report_rollout_result(self, worker_id: str, task_id: str, result: dict) -> dict: - """Rollout worker reports task completion.""" + """Rollout worker reports task completion; results are journaled.""" with self.lock: task = self.rollout_tasks.get(task_id) if task is None or task.worker_id != worker_id: @@ -451,8 +465,36 @@ def report_rollout_result(self, worker_id: str, task_id: str, result: dict) -> d task.error = result.get("error", "unknown error") task.completed_at = time.time() + # Journal the terminal state so a hub restart cannot erase which + # attempts already ran; the trainer treats the JSONL as evidence. + record = {"task_id": task_id, "run_id": task.run_id, + "group_id": task.group_id, "worker_id": worker_id, + "status": task.status, "error": task.error, + "result": result, "reported_at": task.completed_at} + self.run_root.mkdir(parents=True, exist_ok=True) + with self.reports_path.open("a", encoding="utf-8") as journal: + journal.write(json.dumps(record, ensure_ascii=False) + "\n") + return {"task_id": task_id, "acknowledged": True} + def rollout_task_status(self, task_ids: list) -> dict: + """Batch status query used by the training side to collect results.""" + with self.lock: + statuses = {} + for task_id in task_ids: + task = self.rollout_tasks.get(task_id) + if task is None: + statuses[task_id] = {"status": "unknown"} + continue + statuses[task_id] = { + "status": task.status, + "run_id": task.run_id, + "group_id": task.group_id, + "result": task.result, + "error": task.error, + } + return {"tasks": statuses} + def make_hub_server(hub_manager: HubManager, host: str = "0.0.0.0", port: int = 0, *, max_body_bytes: int = 16 * 1024 * 1024): @@ -573,6 +615,11 @@ def do_POST(self): ) return self.reply(200, result) + elif path == "/hub/rollout_tasks/status": + body = self._read_json_body() + result = hub_manager.rollout_task_status(body.get("task_ids", [])) + return self.reply(200, result) + elif path == "/hub/rollout_tasks": body = self._read_json_body() result = hub_manager.submit_rollout_task( diff --git a/harborrl/deployment/schema.py b/harborrl/deployment/schema.py index ec179be1e..db30ac9e5 100644 --- a/harborrl/deployment/schema.py +++ b/harborrl/deployment/schema.py @@ -27,7 +27,9 @@ MANAGER_REQUIRED = {"id", "mode", "bind", "control_port", "control_url", "gateway_port", "gateway_url", "run_token_file", "source_dir", "controller_python"} MANAGER_OPTIONAL = {"gateway_shards", "gateway_routing", "sandboxes_per_shard", - "worker_shards", "gateway_hosts", "shard_python"} + "worker_shards", "gateway_hosts", "shard_python", + "hub_port", "hub_url", "hub_pull_interval", + "gpu_pool", "max_concurrent_runs", "run_queue_size"} MANAGER_FIELDS = MANAGER_REQUIRED | MANAGER_OPTIONAL SHARD_FIELDS = {"name", "port", "mode", "url", "admin_url"} SHARD_MODES = ("local", "remote") @@ -46,8 +48,8 @@ ROLLOUT_FIELDS = {"provider", "workers"} CONNECTIVITY_FIELDS = {"command_timeout_s", "ssh_timeout_s", "http_timeout_s", "gpu_to_controller", "worker_to_gateway", "manager_to_gpu_inference"} -TRANSPORTS = ("local", "ssh") -ROLLOUT_PROVIDERS = ("ssh_docker", "embedded", "sandbox") +TRANSPORTS = ("local", "ssh", "http_pull") +ROLLOUT_PROVIDERS = ("ssh_docker", "embedded", "sandbox", "hub_pull") STORAGE_MODES = ("shared_fs",) @@ -220,8 +222,8 @@ def _manager(config): if missing: raise DeploymentError(f"manager requires {sorted(missing)}") mode = config["mode"] - if mode not in ("embedded", "service"): - raise DeploymentError("manager.mode must be embedded or service") + if mode not in ("embedded", "service", "hub"): + raise DeploymentError("manager.mode must be embedded, service, or hub") service = mode == "service" control_port = _positive_int(config["control_port"], "manager.control_port") gateway_port = _positive_int(config["gateway_port"], "manager.gateway_port") @@ -291,6 +293,89 @@ def _manager(config): "manager.shard_python interprets gateway_hosts growth; " "declare the pool first") shard_python = _absolute_path(shard_python, "manager.shard_python") + # Hub mode specific validation and fields + if mode == "hub": + hub_port = config.get("hub_port") + if hub_port is None: + raise DeploymentError("manager.hub_port is required in hub mode") + hub_port = _positive_int(hub_port, "manager.hub_port") + if hub_port == control_port or hub_port == gateway_port: + raise DeploymentError("manager.hub_port must differ from control_port and gateway_port") + if not 0 < hub_port < 65536: + raise DeploymentError("manager.hub_port must be in 1..65535") + + hub_url = config.get("hub_url") + if hub_url is None: + raise DeploymentError("manager.hub_url is required in hub mode") + hub_url = _plain_origin(hub_url, "manager.hub_url", port=hub_port, allow_loopback=False) + + gpu_pool = config.get("gpu_pool") + if gpu_pool is None or not isinstance(gpu_pool, list) or not gpu_pool: + raise DeploymentError("manager.gpu_pool must be a nonempty list in hub mode") + + # Validate each GPU in the pool + validated_pool = [] + pool_ids = set() + for gpu in gpu_pool: + if not isinstance(gpu, dict): + raise DeploymentError("manager.gpu_pool entries must be mappings") + gpu_id = _slug(gpu.get("id", ""), "gpu_pool entry id") + if gpu_id in pool_ids: + raise DeploymentError(f"duplicate gpu_pool id: {gpu_id}") + pool_ids.add(gpu_id) + + transport = gpu.get("transport", "ssh") + if transport not in ("ssh", "http_pull"): + raise DeploymentError("gpu_pool transport must be ssh or http_pull") + + validated_gpu = { + "id": gpu_id, + "transport": transport, + "source_dir": _absolute_path(gpu["source_dir"], f"gpu_pool {gpu_id} source_dir"), + "train_python": _absolute_path(gpu["train_python"], f"gpu_pool {gpu_id} train_python"), + "expected_gpus": _positive_int(gpu["expected_gpus"], f"gpu_pool {gpu_id} expected_gpus"), + } + + if transport == "ssh": + validated_gpu["ssh"] = _ssh_spec(gpu.get("ssh"), f"gpu_pool {gpu_id} ssh") + elif transport == "http_pull": + validated_gpu["ssh"] = None + if "pull_url" not in gpu: + raise DeploymentError(f"gpu_pool {gpu_id} with http_pull transport requires pull_url") + validated_gpu["pull_url"] = _plain_origin(gpu["pull_url"], + f"gpu_pool {gpu_id} pull_url", + allow_loopback=False) + + if "environment_file" in gpu and gpu["environment_file"] is not None: + validated_gpu["environment_file"] = _absolute_path(gpu["environment_file"], + f"gpu_pool {gpu_id} environment_file") + else: + validated_gpu["environment_file"] = None + + validated_pool.append(validated_gpu) + + max_concurrent_runs = config.get("max_concurrent_runs", 4) + if type(max_concurrent_runs) is not int or max_concurrent_runs < 1: + raise DeploymentError("manager.max_concurrent_runs must be a positive integer") + + run_queue_size = config.get("run_queue_size", 100) + if type(run_queue_size) is not int or run_queue_size < 1: + raise DeploymentError("manager.run_queue_size must be a positive integer") + + hub_pull_interval = config.get("hub_pull_interval", 5) + if type(hub_pull_interval) not in (int, float) or hub_pull_interval <= 0: + raise DeploymentError("manager.hub_pull_interval must be a positive number") + + # Store hub fields to add to manager dict later + hub_fields = { + "hub_port": hub_port, + "hub_url": hub_url, + "gpu_pool": validated_pool, + "max_concurrent_runs": max_concurrent_runs, + "run_queue_size": run_queue_size, + "hub_pull_interval": hub_pull_interval, + } + manager = { "id": _slug(config["id"], "manager.id"), "mode": mode, "bind": _nonempty_str(config["bind"], "manager.bind"), @@ -327,6 +412,8 @@ def _manager(config): manager["gateway_hosts"] = list(gateway_hosts) if shard_python is not None: manager["shard_python"] = shard_python + if mode == "hub": + manager.update(hub_fields) return manager @@ -391,7 +478,7 @@ def _gpu_target(config): if ssh is not None: ssh = _ssh_spec(ssh, "gpu_target.ssh") elif ssh is not None: - raise DeploymentError("gpu_target.ssh must be null for local transport") + raise DeploymentError("gpu_target.ssh must be null for local or http_pull transport") target = { "id": _slug(config["id"], "gpu_target.id"), "transport": transport, "ssh": ssh, "source_dir": _absolute_path(config["source_dir"], "gpu_target.source_dir"), @@ -429,7 +516,7 @@ def _rollout(config): # ssh_docker needs explicit machines; the embedded provider falls back to # the training config's worker list, so it may start empty. if (not isinstance(workers, list) - or (not workers and config["provider"] not in ("embedded", "sandbox"))): + or (not workers and config["provider"] not in ("embedded", "sandbox", "hub_pull"))): raise DeploymentError("rollout.workers must be a nonempty list") normalized, seen = [], set() for worker in workers: diff --git a/harborrl/deployment/training_target.py b/harborrl/deployment/training_target.py index 8df8168cb..dc857378f 100644 --- a/harborrl/deployment/training_target.py +++ b/harborrl/deployment/training_target.py @@ -204,7 +204,7 @@ def local_target(plan, *, environment): "LD_PRELOAD", "CUDA_HOME", "NVTE_CUDA_INCLUDE_DIR", "CUDA_VISIBLE_DEVICES", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "PYTHONPATH", - "SLIME_DIR", "MEGATRON_DIR", "SGLANG_IMAGE"} + "SLIME_DIR", "MEGATRON_DIR", "SGLANG_IMAGE", "HARBORRL_HUB_ENV_FILE"} child_env = {key: value for key, value in os.environ.items() if key in allowed} child_env["PATH"] = os.pathsep.join( [str(Path(sys.executable).parent), child_env.get("PATH", os.defpath)]) diff --git a/harborrl/gateway/server.py b/harborrl/gateway/server.py index db07a3ed2..cb4f61b93 100644 --- a/harborrl/gateway/server.py +++ b/harborrl/gateway/server.py @@ -1,8 +1,10 @@ """Bounded stdlib HTTP transport. All policy requests require attempt credentials.""" +import errno import json import secrets import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.error import HTTPError, URLError from urllib.parse import urlsplit from harborrl.trajectories.native import digest, encode @@ -10,6 +12,17 @@ from .messages import ProtocolError, convert, sse_events +def _transport_failure(error): + if isinstance(error, HTTPError): + return error.code in {408, 429, 500, 502, 503, 504} + if isinstance(error, URLError): + return isinstance(error.reason, OSError) and _transport_failure(error.reason) + # Restrict this classification to the backend call, never trace persistence. + return isinstance(error, (ConnectionError, TimeoutError)) or (type(error) is OSError + and error.errno in {None, errno.ECONNRESET, errno.ECONNREFUSED, errno.ETIMEDOUT, + errno.EHOSTUNREACH, errno.ENETUNREACH, errno.EPIPE}) + + class Gateway: def __init__(self, registry, backend, *, model, max_output_tokens=8192): self.registry, self.backend = registry, backend @@ -17,12 +30,18 @@ def __init__(self, registry, backend, *, model, max_output_tokens=8192): def generate(self, token, payload): aid, rid, identity, trial = self.registry.begin(token) + failure_kind = None try: converted = convert(payload, model=self.model, max_output_tokens=self.max_output_tokens) if digest(converted["sampling"]) != identity.sampling_digest: raise ProtocolError("sampling parameters differ from attempt manifest") response_id = "msg_" + secrets.token_hex(16) - generated = self.backend.generate(converted, identity, response_id) + try: + generated = self.backend.generate(converted, identity, response_id) + except Exception as exc: + if _transport_failure(exc): + failure_kind = 'upstream-transport' + raise if generated.get("policy_version") != identity.policy_version: raise ValueError("generation policy version mismatch") message = {"id": response_id, "type": "message", "role": "assistant", "model": self.model, @@ -38,7 +57,7 @@ def generate(self, token, payload): return aid, message except BaseException as exc: # Deliberately retain failed generation in the seal, even if CLI retries. - self.registry.finish(aid, rid, error=type(exc).__name__) + self.registry.finish(aid, rid, error=type(exc).__name__, failure_kind=failure_kind) raise def count_tokens(self, token, payload): diff --git a/harborrl/gateway/sglang_backend.py b/harborrl/gateway/sglang_backend.py index 0471ef8f2..287a0834d 100644 --- a/harborrl/gateway/sglang_backend.py +++ b/harborrl/gateway/sglang_backend.py @@ -5,9 +5,10 @@ are deliberately insufficient. This adapter does not load models on import. """ import json +from pathlib import Path from urllib import request -from harborrl.trajectories.native import digest, finite +from harborrl.trajectories.native import digest, finite, publish from .messages import ProtocolError @@ -15,7 +16,7 @@ class SGLangBackend: def __init__(self, endpoint, tokenizer, model_adapter, *, tokenizer_digest, template_digest, timeout=120, max_context=32768, - audited_raw_logprobs=False, sampling_seed=None): + audited_raw_logprobs=False, sampling_seed=None, rejected_root=None): if sampling_seed is not None and (type(sampling_seed) is not int or not 0 <= sampling_seed < 2**31): raise ValueError('sampling_seed must be null or an integer in 0..2147483647') self.endpoint = endpoint.rstrip("/") @@ -25,6 +26,7 @@ def __init__(self, endpoint, tokenizer, model_adapter, *, tokenizer_digest, self.timeout, self.max_context = timeout, max_context self.audited_raw_logprobs = audited_raw_logprobs self.sampling_seed = sampling_seed + self.rejected_root = Path(rejected_root) if rejected_root is not None else None self.opener = request.build_opener(request.ProxyHandler({})) def prepare(self, converted): @@ -81,7 +83,23 @@ def generate(self, converted, identity, response_id): headers={"Content-Type": "application/json"}) with self.opener.open(req, timeout=self.timeout) as response: output = json.load(response) - return self.decode(output, payload, converted, identity, response_id) + try: + return self.decode(output, payload, converted, identity, response_id) + except (ValueError, TypeError, KeyError) as exc: + if self.rejected_root is not None: + # Keep rejected generations outside the trainable trace. Never + # replay them automatically or include HTTP credentials here. + evidence = {"identity": identity.to_dict(), "response_id": response_id, + "error_type": type(exc).__name__, "training_use": False, + "serving_input": payload, "converted_request": converted, + "serving_output": output, "serving_output_digest": digest(output)} + path = self.rejected_root / digest(identity.to_dict()) / (digest(response_id) + '.json') + try: + publish(path, evidence) + except (OSError, ValueError, TypeError) as storage_error: + # A failed diagnostic write is not a backend transport fault. + raise ValueError('rejected generation evidence could not be persisted') from storage_error + raise def decode(self, output, payload, converted, identity, response_id): meta = output.get("meta_info", {}) diff --git a/harborrl/gateway/shard_service.py b/harborrl/gateway/shard_service.py index 34308162a..fb6c79975 100644 --- a/harborrl/gateway/shard_service.py +++ b/harborrl/gateway/shard_service.py @@ -2,7 +2,7 @@ Usually launched on another machine that shares the run directory: - RUN_ID=... RUN_DIR=/mnt/shared-storage-user/.../runs/Run-... \\ + RUN_ID=... RUN_DIR=/shared/harborrl/runs/Run-... \\ HARBORRL_SHARD_NAME=gw1 \\ HARBORRL_SHARD_GATEWAY_HOST=0.0.0.0 HARBORRL_SHARD_GATEWAY_PORT=49300 \\ HARBORRL_SHARD_GATEWAY_URL=http://10.98.250.180:49300 \\ diff --git a/harborrl/gateway/trace.py b/harborrl/gateway/trace.py index cd06ce9f5..2ef759d94 100644 --- a/harborrl/gateway/trace.py +++ b/harborrl/gateway/trace.py @@ -118,7 +118,8 @@ def register(self, identity, trial_id, *, credential=None): f.write("single writer\n") self.version = identity.policy_version self.attempts[identity.attempt_id] = {"identity": identity, "trial_id": trial_id, "root": root, - "pending": set(), "turns": [], "errors": [], "closed": False, "sealed": False, "credential": key} + "pending": set(), "turns": [], "errors": [], "failures": [], + "closed": False, "sealed": False, "credential": key} self.credentials[key] = identity.attempt_id return token @@ -144,20 +145,41 @@ def begin(self, token): state["pending"].add(request_id) return aid, request_id, state["identity"], state["trial_id"] - def finish(self, aid, request_id, turn=None, error=None): + def finish(self, aid, request_id, turn=None, error=None, *, failure_kind=None): with self.changed: state = self.attempts[aid] if request_id not in state["pending"]: raise ValueError("request not pending") if error: state["errors"].append(error) + state['failures'].append({'request_id': request_id, 'error': error, + 'kind': failure_kind}) if turn is not None: state["turns"].append(deepcopy(turn)) - publish(state["root"] / "generated" / f"{request_id}.json", {"turn": turn, "error": error}) + publish(state["root"] / "generated" / f"{request_id}.json", {"turn": turn, "error": error, + **({'failure_kind': failure_kind} if failure_kind else {})}) if error: state["pending"].remove(request_id) self.changed.notify_all() + def has_nontransport_failure(self, aid): + """A known contract failure vetoes retries even when the CLI exits first.""" + with self.lock: + state = self.attempts[aid] + return (state['errors'] != [failure['error'] for failure in state['failures']] + or any(failure['kind'] != 'upstream-transport' for failure in state['failures'])) + + def transport_failure_only(self, aid): + """Use trusted backend observations, not exception names from an IR.""" + with self.lock: + state = self.attempts[aid] + failures = state['failures'] + return (state['closed'] and state['sealed'] and not state['pending'] + and bool(failures) + and state['errors'] == [failure['error'] for failure in failures] + and all(failure['kind'] == 'upstream-transport' for failure in failures) + and all(turn.get('delivery') == 'consumed_confirmed' for turn in state['turns'])) + def delivery(self, aid, response_id, status): with self.changed: state = self.attempts[aid] diff --git a/harborrl/math/config.py b/harborrl/math/config.py index 766eb2a7f..304ec0b31 100644 --- a/harborrl/math/config.py +++ b/harborrl/math/config.py @@ -29,6 +29,8 @@ def load_config(config, path, overrides=None, task_ids=None): config['training'].setdefault('resume', None) config['training'].setdefault('export_hf', False) config['training'].setdefault('seed', None) + config['training'].setdefault('max_tokens_per_gpu', 16384) + config['training'].setdefault('max_ckpt_keep', 2) config.setdefault('algorithm', {'name': 'grpo'}) fields = {**MATH_FIELDS, 'training': MATH_FIELDS['training'] | {'resume', 'export_hf', 'seed'}, 'algorithm': {'name'}} @@ -90,7 +92,7 @@ def load_config(config, path, overrides=None, task_ids=None): config[section][field] = str((Path(path).parent / Path(value).expanduser()).resolve()) for section, keys in [('sampling', FIELDS['sampling']), ('deployment', FIELDS['deployment'] - {'layout'}), - ('training', {'num_rollout', 'save_interval'})]: + ('training', {'num_rollout', 'save_interval', 'max_tokens_per_gpu', 'max_ckpt_keep'})]: for key in keys: if type(config[section][key]) is not int or config[section][key] <= 0: raise ValueError(f'{section}.{key} must be a positive integer') @@ -114,7 +116,7 @@ def load_config(config, path, overrides=None, task_ids=None): if (deployment['actor_gpus'] % deployment['actor_tensor_parallel_size'] or deployment['rollout_gpus'] % deployment['rollout_gpus_per_engine']): raise ValueError('GPU counts must be divisible by tensor parallel sizes') - if not isinstance(config['model']['args_file'], str) or not re.fullmatch(r'[A-Za-z0-9_-]+', config['model']['args_file']): + if not isinstance(config['model']['args_file'], str) or not re.fullmatch(r'[A-Za-z0-9._-]+', config['model']['args_file']): raise ValueError('model.args_file must name a Slime model preset') if config['consistency']['mode'] != 'off': raise ValueError('text_math currently requires consistency.mode: off; Harbor sidecars are not math evidence') diff --git a/harborrl/math/data.py b/harborrl/math/data.py index 044a29258..0e3beff3b 100644 --- a/harborrl/math/data.py +++ b/harborrl/math/data.py @@ -8,7 +8,8 @@ NUMBER = r"[+-]?(?:\d{1,32}(?:\.\d{1,16})?|\d{1,32}/[1-9]\d{0,31})" GSM_NUMBER = r"[+-]?(?:\d{1,3}(?:,\d{3}){1,10}(?:\.\d{1,16})?|\d{1,32}(?:\.\d{1,16})?|\d{1,32}/[1-9]\d{0,31})" -VERIFIERS = {"exact_rational_v1", "gsm8k_numeric_v1"} +VERIFIERS = {"exact_rational_v1", "gsm8k_numeric_v1", "math_latex_v1"} +LATEX_REFERENCE = re.compile(r"\S.{0,199}") # 单行、非空、≤200 字符;结构合法性由 math_verify 解析兜底 TASK_FIELDS = {"task_id", "problem_id", "prompt", "reference", "verifier", "split", "source", "license"} @@ -25,8 +26,13 @@ def load_tasks(path): raise ValueError("Task fields must be nonempty strings") if row["split"] not in {"train", "validation", "test"} or row["verifier"] not in VERIFIERS: raise ValueError("Only split-locked tasks with a supported numeric verifier are supported") - if len(row["prompt"]) > 8192 or not re.fullmatch(NUMBER, row["reference"]): - raise ValueError("Unsupported prompt length or rational reference") + if len(row["prompt"]) > 8192: + raise ValueError("Unsupported prompt length") + if row["verifier"] == "math_latex_v1": + if not LATEX_REFERENCE.fullmatch(row["reference"]): + raise ValueError("math_latex_v1 reference must be a bounded single-line LaTeX answer") + elif not re.fullmatch(NUMBER, row["reference"]): + raise ValueError("Unsupported rational reference") if row["task_id"] in identities: raise ValueError("Duplicate task_id") identities.add(row["task_id"]) @@ -42,7 +48,7 @@ def load_tasks(path): def _gsm_answer(response): candidates = [] - for pattern in (r"(?m)^[ \t]*####[ \t]+([^\n]{1,100})$", r"\\boxed\{([^{}]{1,100})\}"): + for pattern in (r"(?m)^[ \t]*####[ \t]*([^\n]{1,100})$", r"\\boxed\{([^{}]{1,100})\}"): for match in re.finditer(pattern, response): text = match[1].strip() for wrapper in ("**", "$"): @@ -56,9 +62,38 @@ def _gsm_answer(response): return text if re.fullmatch(NUMBER, text) else "" +def _latex_verify(response, reference): + try: + from math_verify import parse as mv_parse, verify as mv_verify + except ImportError as exc: + raise ValueError("math_latex_v1 requires the math_verify package") from exc + record = {"verifier": "math_latex_v1", "input_digest": digest({"response": response, "reference": reference}), + "status": "unparseable", "reward": 0.0, "parsed": None} + if not isinstance(response, str) or len(response) > 16384: + record["status"] = "unsupported" + return record + try: + gold = mv_parse("$" + reference.strip() + "$") + answer = mv_parse(response) + except Exception: + return record + if not gold or not answer: + return record + try: + correct = bool(mv_verify(gold, answer)) + except Exception: + return record + extracted = answer[0] if isinstance(answer, list) and answer else str(answer) + record.update(status="correct" if correct else "incorrect", reward=1.0 if correct else 0.0, + parsed=str(extracted)[:100]) + return record + + def verify(response, reference, verifier="exact_rational_v1"): if verifier not in VERIFIERS: raise ValueError(f"Unsupported numeric verifier: {verifier}") + if verifier == "math_latex_v1": + return _latex_verify(response, reference) record = {"verifier": verifier, "input_digest": digest({"response": response, "reference": reference}), "status": "unparseable", "reward": 0.0, "parsed": None} if not isinstance(response, str) or len(response) > 16384: diff --git a/harborrl/options/catalog.py b/harborrl/options/catalog.py index cebe93cae..9edb3fb6f 100644 --- a/harborrl/options/catalog.py +++ b/harborrl/options/catalog.py @@ -40,6 +40,9 @@ "training.learning_rate": ("number", "Positive finite learning rate"), "training.seed": ("number_or_null", "Sampling seed shared by every group; null keeps sampling nondeterministic"), "training.export_hf": ("boolean", "Also export an HF checkpoint next to the training checkpoints"), + "training.resume": ("path_or_null", "Checkpoint directory to resume; rollout count remains the total target"), + "training.max_tokens_per_gpu": ("integer", "Maximum actor token budget per GPU"), + "training.max_ckpt_keep": ("integer", "Complete checkpoints retained after a new checkpoint is saved"), "training.save_interval": ("integer", "Positive checkpoint interval in rollout batches"), "training.backend_contract": ("string", "Pinned backend/algorithm contract"), "sampling.group_size": ("integer", "Samples per prompt, at least two for GRPO"), @@ -138,7 +141,7 @@ def build_catalog(): for name in sorted(fields): kind, description = DEPLOYMENT_FIELDS[name] deployment[f"{section}.{name}"] = {"type": kind, "description": description} - for key, values in {"manager.mode": ("embedded", "service"), "storage.mode": schema.STORAGE_MODES, + for key, values in {"manager.mode": ("embedded", "service", "hub"), "storage.mode": schema.STORAGE_MODES, "rollout.provider": schema.ROLLOUT_PROVIDERS, "gpu_target.transport": schema.TRANSPORTS}.items(): deployment[key]["values"] = list(values) datasets = deepcopy(dataset_metadata()["datasets"]) diff --git a/harborrl/options/presets.py b/harborrl/options/presets.py index f52fdc365..b3685000d 100644 --- a/harborrl/options/presets.py +++ b/harborrl/options/presets.py @@ -54,7 +54,8 @@ def defaults(preset, output_directory): "model": {"checkpoint": None, "reference": None, "args_file": "qwen3-8B"}, "training": {"num_rollout": 2, "learning_rate": 1e-6, "save_interval": 1, "backend_contract": "slime-v0.3.2-native-v1", - "seed": None, "export_hf": False}, + "seed": None, "export_hf": False, "resume": None, + "max_tokens_per_gpu": 16384, "max_ckpt_keep": 2}, "sampling": {"group_size": 2, "groups_per_batch": 1, "max_attempts": 1, "max_tokens": 2048, "max_context": 32768}, "deployment": {"layout": "colocate", "num_gpus": 1, "actor_gpus": 1, diff --git a/harborrl/platform/checkpoint_guard.py b/harborrl/platform/checkpoint_guard.py new file mode 100644 index 000000000..4905b7cc7 --- /dev/null +++ b/harborrl/platform/checkpoint_guard.py @@ -0,0 +1,162 @@ +"""Supervise retention because pinned Slime silently ignores unknown CLI flags.""" +import argparse +import json +import math +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import time +import zipfile + + +def complete_checkpoints(root, hf_template=None): + """Inspect tracker-published generations; never consume or prune partial saves.""" + root = Path(root).resolve() + try: + latest = int((root / 'latest_checkpointed_iteration.txt').read_text().strip()) + except (OSError, ValueError): + return [] + complete = [] + for path in root.glob('iter_*'): + if not re.fullmatch(r'iter_[0-9]+', path.name) or path.is_symlink(): + continue + step = int(path.name[5:]) + if step > latest: + continue + try: + files = list(path.rglob('*')) + if any(f.is_symlink() for f in files): + continue + if not (path / '.metadata').is_file() or not (path / 'common.pt').is_file(): + continue + metadata = json.loads((path / 'metadata.json').read_text()) + if metadata.get('sharded_backend') != 'torch_dist': + continue + shards = list(path.glob('*.distcp')) + if not shards: + continue + for shard in shards: + with zipfile.ZipFile(shard) as archive: + if not archive.infolist(): + raise ValueError('empty checkpoint archive') + hf = None + if hf_template: + hf = Path(hf_template.format(rollout_id=step)) + if hf.is_symlink(): + continue + index = json.loads((hf / 'model.safetensors.index.json').read_text()) + for name in set(index['weight_map'].values()): + shard = hf / name + if shard.is_symlink() or not shard.resolve().is_relative_to(hf.resolve()): + raise ValueError('unsafe HF shard path') + with shard.open('rb') as stream: + size = int.from_bytes(stream.read(8), 'little') + if not 0 < size < 100_000_000: + raise ValueError('invalid safetensors header') + header = json.loads(stream.read(size)) + end = max(v['data_offsets'][1] for k, v in header.items() if k != '__metadata__') + if shard.stat().st_size != 8 + size + end: + raise ValueError('incomplete HF shard') + complete.append({'step': step, 'path': path, 'hf': hf, + 'bytes': sum(f.stat().st_size for f in files if f.is_file())}) + except (OSError, ValueError, KeyError, zipfile.BadZipFile): + continue + return sorted(complete, key=lambda record: record['step']) + + +def prune(root, keep, *, hf_template=None, journal=None): + if type(keep) is not int or keep < 1: + raise ValueError('keep must be a positive integer') + root = Path(root).resolve() + complete = complete_checkpoints(root, hf_template) + removed = [] + for checkpoint in complete[:-keep]: + for path in (checkpoint['path'], checkpoint['hf']): + if path is None: + continue + parent = root if path == checkpoint['path'] else Path(hf_template).parent.resolve() + resolved = path.resolve() + if path.is_symlink() or resolved == parent or not resolved.is_relative_to(parent): + raise ValueError('unsafe checkpoint retention target') + record = {'path': str(resolved), 'successor': complete[-1]['step'], + 'files': [{'path': str(f.relative_to(resolved)), 'bytes': f.stat().st_size} + for f in resolved.rglob('*') if f.is_file()], 'time': time.time()} + if journal: + with Path(journal).open('a') as stream: + stream.write(json.dumps({**record, 'event': 'prune_planned'}) + chr(10)) + shutil.rmtree(resolved) + removed.append(str(resolved)) + if journal: + with Path(journal).open('a') as stream: + stream.write(json.dumps({'event': 'pruned', 'path': str(resolved)}) + chr(10)) + return removed + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--checkpoint-root', required=True, type=Path) + parser.add_argument('--keep', type=int, default=2) + parser.add_argument('--min-free-gb', type=float, default=128) + parser.add_argument('--expected-gb', type=float, default=0) + parser.add_argument('--margin', type=float, default=1.15) + parser.add_argument('--hf-template') + parser.add_argument('--resume-root', type=Path) + parser.add_argument('command', nargs=argparse.REMAINDER) + args = parser.parse_args() + command = args.command[1:] if args.command[:1] == ['--'] else args.command + if (not command or args.keep < 1 or args.min_free_gb < 0 or args.expected_gb < 0 or args.margin < 1 + or not all(math.isfinite(x) for x in (args.min_free_gb, args.expected_gb, args.margin))): + parser.error('valid command, retention count and space limits required') + args.checkpoint_root.mkdir(parents=True, exist_ok=True) + expected = args.expected_gb * 1024**3 + if args.resume_root: + source = complete_checkpoints(args.resume_root) + if (not source or source[-1]['step'] != int( + (args.resume_root / 'latest_checkpointed_iteration.txt').read_text().strip())): + raise RuntimeError('resume root contains no complete published checkpoint') + expected = max(expected, source[-1]['bytes']) + free = shutil.disk_usage(args.checkpoint_root).free + required = max(args.min_free_gb * 1024**3, expected * args.margin) + if free < required: + raise RuntimeError(f'checkpoint preflight requires {required / 1024**3:.1f} GiB; free={free / 1024**3:.1f}') + journal = args.checkpoint_root / 'retention.jsonl' + journal.write_text(json.dumps({'event': 'start', 'keep': args.keep, 'free_bytes': free, + 'required_bytes': required, 'command': command}) + chr(10)) + child = subprocess.Popen(command, start_new_session=True) + stopping = None + + def stop(signum, _frame): + nonlocal stopping + if child.poll() is None: + stopping = stopping or time.monotonic() + try: + os.killpg(child.pid, signum) + except ProcessLookupError: + pass + + previous = {sig: signal.signal(sig, stop) for sig in (signal.SIGINT, signal.SIGTERM)} + try: + while child.poll() is None: + prune(args.checkpoint_root, args.keep, hf_template=args.hf_template, journal=journal) + if stopping and time.monotonic() - stopping > 30: + stop(signal.SIGKILL, None) + time.sleep(2) + prune(args.checkpoint_root, args.keep, hf_template=args.hf_template, journal=journal) + return child.returncode + finally: + if child.poll() is None: + stop(signal.SIGTERM, None) + try: + child.wait(30) + except subprocess.TimeoutExpired: + stop(signal.SIGKILL, None) + child.wait() + for sig, handler in previous.items(): + signal.signal(sig, handler) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/harborrl/platform/hub_train.py b/harborrl/platform/hub_train.py new file mode 100644 index 000000000..0def14b00 --- /dev/null +++ b/harborrl/platform/hub_train.py @@ -0,0 +1,26 @@ +"""Run upstream Slime with explicitly configured Hub environment on Ray workers.""" +import os +import runpy +import sys +from pathlib import Path + + +def rollout_environment(environ): + return {key: value for key, value in environ.items() + if key.startswith('HARBORRL_') or key in { + 'RUN_DIR', 'RUN_ID', 'MODEL_TAG', 'MODEL_ARGS_FILE', + 'ROLLOUT_MAX_RESPONSE_LEN', 'ROLLOUT_MAX_CONTEXT_LEN', 'PYTHONPATH'}} + + +def main(): + import ray + + if not ray.is_initialized(): + ray.init(runtime_env={'env_vars': rollout_environment(os.environ)}) + entry = Path(os.environ['SLIME_DIR']) / 'train.py' + sys.argv[0] = str(entry) + runpy.run_path(str(entry), run_name='__main__') + + +if __name__ == '__main__': + main() diff --git a/harborrl/platform/preflight.py b/harborrl/platform/preflight.py index a0be564ff..8ce22ea88 100644 --- a/harborrl/platform/preflight.py +++ b/harborrl/platform/preflight.py @@ -66,7 +66,8 @@ def _doctor(plan, *, math_only=False): explicit = deployment is not None and plan.get("deployment", {}).get( "source", "embedded-local") != "embedded-local" local_gpu = deployment is None or deployment["gpu_target"]["transport"] == "local" - legacy_workers = (not explicit) or deployment["rollout"]["provider"] in ("embedded", "sandbox") + legacy_workers = (not explicit) or deployment["rollout"]["provider"] in ( + "embedded", "sandbox", "hub_pull") if explicit: from harborrl.deployment.preflight import preflight as deployment_preflight diff --git a/harborrl/platform/slime_train.sh b/harborrl/platform/slime_train.sh index 2ea9ed238..951fc0be8 100644 --- a/harborrl/platform/slime_train.sh +++ b/harborrl/platform/slime_train.sh @@ -65,10 +65,6 @@ CKPT_ARGS=( --megatron-to-hf-mode bridge --save "${CKPT_ROOT}/${RUN_ID:-run}" --save-interval "${SAVE_INTERVAL}" - --max-ckpt-keep "${MAX_CKPT_KEEP:-2}" - --checkpoint-min-free-gb "${CHECKPOINT_MIN_FREE_GB:-128}" - --checkpoint-expected-gb "${CHECKPOINT_EXPECTED_GB:-0}" - --checkpoint-space-margin-ratio "${CHECKPOINT_SPACE_MARGIN_RATIO:-1.15}" ) if [[ -n "${RESUME_LOAD:-}" ]]; then CKPT_ARGS+=(--load "${RESUME_LOAD}" --use-checkpoint-opt-param-scheduler) @@ -215,16 +211,28 @@ export PYTHONPATH="${REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" ENTRY=("${SLIME_DIR}/train.py") if [[ "${HARBORRL_CONSISTENCY_MODE:-off}" != "off" ]]; then ENTRY=(-m harborrl.consistency.train) +elif [[ -n "${HARBORRL_HUB_ENV_FILE:-}" || -n "${HARBORRL_HUB_URL:-}" ]]; then + ENTRY=(-m harborrl.platform.hub_train) fi +GUARD_ARGS=( + --checkpoint-root "${CKPT_ROOT}/${RUN_ID:-run}" --keep "${MAX_CKPT_KEEP:-2}" + --min-free-gb "${CHECKPOINT_MIN_FREE_GB:-128}" + --expected-gb "${CHECKPOINT_EXPECTED_GB:-0}" + --margin "${CHECKPOINT_SPACE_MARGIN_RATIO:-1.15}" +) +[[ -z "${RESUME_LOAD:-}" ]] || GUARD_ARGS+=(--resume-root "${RESUME_LOAD}") +[[ -z "${SAVE_HF:-}" ]] || GUARD_ARGS+=(--hf-template "${SAVE_HF}") +COMMAND=("${TRAIN_PYTHON}" -u -m harborrl.platform.checkpoint_guard "${GUARD_ARGS[@]}" + -- "${TRAIN_PYTHON}" -u "${ENTRY[@]}" "${TRAIN_ARGS[@]}") "${TRAIN_PYTHON}" -m harborrl.platform.evidence "${RUN_DIR}" "${DRY_RUN:-0}" \ - "${TRAIN_PYTHON}" -u "${ENTRY[@]}" "${TRAIN_ARGS[@]}" + "${COMMAND[@]}" if [[ "${DRY_RUN:-0}" == "1" ]]; then printf '[dry-run] ' - printf '%q ' "${TRAIN_PYTHON}" -u "${ENTRY[@]}" "${TRAIN_ARGS[@]}" + printf '%q ' "${COMMAND[@]}" printf '\n' exit 0 fi -exec "${TRAIN_PYTHON}" -u "${ENTRY[@]}" "${TRAIN_ARGS[@]}" +exec "${COMMAND[@]}" diff --git a/harborrl/rollout/generations.py b/harborrl/rollout/generations.py new file mode 100644 index 000000000..da6b17d12 --- /dev/null +++ b/harborrl/rollout/generations.py @@ -0,0 +1,161 @@ +"""Bounded whole-batch recovery with immutable, reward-independent inputs.""" +from __future__ import annotations + +import contextvars +from dataclasses import dataclass +from pathlib import Path + +from harborrl.rollout.harbor_job.reliability import ( + InfraBudgetExhausted, + RetryableRolloutFailure, +) +from harborrl.trajectories.native import digest, publish, read_json + +ACTIVE_GENERATION = contextvars.ContextVar('harborrl_rollout_generation', default=None) + + +@dataclass(frozen=True) +class GenerationPolicy: + max_reruns_per_seed: int = 2 + max_attempts_per_rollout: int = 32 + max_failed_groups_per_rollout: int = 8 + + def __post_init__(self): + for key, minimum in (('max_reruns_per_seed', 0), ('max_attempts_per_rollout', 1), + ('max_failed_groups_per_rollout', 1)): + value = getattr(self, key) + if type(value) is not int or value < minimum: + raise ValueError(f'{key} must be an integer >= {minimum}') + + +def generation_batch_id(rollout_id, generation): + return f'rollout-{rollout_id}-generation-{generation}' + + +def generation_group_id(rollout_id, generation, group_index): + return f'{generation_batch_id(rollout_id, generation)}-group-{group_index}' + + +def reserve_generation_attempt(run_root, identity, context): + """A shared, restart-stable bound for embedded and service group workers.""" + import fcntl + + root = Path(run_root) / 'generation-budgets' / identity.batch_id + root.mkdir(parents=True, exist_ok=True) + with (root / 'budget.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + publish(root / 'limits.json', {'max_attempts': context['max_attempts'], + 'max_failed_groups': context['max_failed_groups']}) + if (len(list((root / 'attempts').glob('*.json'))) >= context['max_attempts'] + or len(list((root / 'failed-groups').glob('*.json'))) > context['max_failed_groups']): + raise RetryableRolloutFailure('rollout infrastructure budget exhausted') + publish(root / 'attempts' / f'{identity.attempt_id}.json', identity.to_dict()) + + +def record_failed_group(run_root, identity): + root = Path(run_root) / 'generation-budgets' / identity.batch_id / 'failed-groups' + publish(root / f'{identity.group_id}.json', {'group_id': identity.group_id}) + + +class GenerationJournal: + def __init__(self, run_root, policy=None): + self.root = Path(run_root) / 'rollout-generations' + self.policy = policy or GenerationPolicy() + self.root.mkdir(parents=True, exist_ok=True) + publish(self.root / 'policy.json', self.policy.__dict__) + + def reserve_rerun(self, rollout_id, generation): + # Persist at seed scope across batches and process restarts. A conflict + # never silently buys another retry or resumes a superseded protocol. + import fcntl + + with (self.root / 'budget.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + used = len(list((self.root / 'rerun-budget').glob('*.json'))) + if used >= self.policy.max_reruns_per_seed: + raise InfraBudgetExhausted('rollout generation rerun budget exhausted') + publish(self.root / 'rerun-budget' / f'{used:04d}.json', + {'rollout_id': rollout_id, 'generation': generation}) + + async def execute(self, rollout_id, inputs, policy_version, run, *, discard=None, validate=None): + fixed = {'rollout_id': rollout_id, 'inputs': inputs, 'policy_version': policy_version, + 'policy': self.policy.__dict__} + fingerprint = digest(fixed) + batch_root = self.root / f'rollout-{rollout_id}' + # Existing attempts must be inspected under a fresh run; never replay a + # frozen generation implicitly after a process restart. + try: + batch_root.mkdir() + except FileExistsError as exc: + raise ValueError('rollout generation already exists; use a fresh run protocol') from exc + publish(batch_root / 'inputs.json', fixed) + generation = 0 + while True: + directory = batch_root / f'generation-{generation}' + context = {'rollout_id': rollout_id, 'generation': generation, + 'policy_version': policy_version, 'input_sha256': fingerprint, + 'max_attempts': self.policy.max_attempts_per_rollout, + 'max_failed_groups': self.policy.max_failed_groups_per_rollout} + publish(directory / 'reserved.json', context) + token = ACTIVE_GENERATION.set(context) + try: + result = await run(generation) + if digest(fixed) != fingerprint or digest(read_json(batch_root / 'inputs.json')) != fingerprint: + raise ValueError('frozen rollout inputs changed during recovery') + ids = self.validate_result(result, inputs, rollout_id, generation, policy_version) + if validate is not None: + validate(result) + except RetryableRolloutFailure as exc: + publish(directory / 'failed.json', {'error_type': type(exc).__name__, + 'input_sha256': fingerprint}) + if discard is not None: + discard() + try: + self.reserve_rerun(rollout_id, generation + 1) + except InfraBudgetExhausted: + publish(batch_root / 'failed-seed.json', {'generation': generation, + 'reason': 'rerun budget exhausted'}) + raise + publish(directory / 'superseded.json', {'next_generation': generation + 1, + 'export_allowed': False}) + generation += 1 + except BaseException as exc: + if discard is not None: + discard() + publish(directory / 'failed.json', {'error_type': type(exc).__name__, + 'input_sha256': fingerprint}) + raise + else: + publish(batch_root / 'selected.json', {'generation': generation, + 'input_sha256': fingerprint, 'identities': ids, 'result_sha256': digest(result)}) + return result + finally: + ACTIVE_GENERATION.reset(token) + + @staticmethod + def validate_result(result, inputs, rollout_id, generation, policy_version): + if not isinstance(result, list) or not result or any( + not isinstance(group, list) or not group for group in result): + raise ValueError('rollout result is empty or incomplete') + ids = [[ir['identity'] for ir in group] for group in result] + if any(identity['policy_version'] != policy_version or + identity['batch_id'] != generation_batch_id(rollout_id, generation) + for group in ids for identity in group): + raise ValueError('rollout result escaped its generation or policy lock') + trajectory_ids = [identity['trajectory_id'] for group in ids for identity in group] + if len(set(trajectory_ids)) != len(trajectory_ids): + raise ValueError('duplicate trajectory in rollout generation') + groups = inputs.get('groups') + if groups is not None: + if len(groups) != len(ids) or len({g['group_index'] for g in groups}) != len(groups): + raise ValueError('rollout group membership changed') + for expected, actual in zip(groups, ids, strict=True): + if len(expected['slots']) != len(actual) or len(expected['tasks']) != len(actual): + raise ValueError('rollout slot membership changed') + for index, identity in enumerate(actual): + if (identity['group_id'] != generation_group_id( + rollout_id, generation, expected['group_index']) + or identity['slot_id'] != expected['slots'][index] + or identity['task_digest'] != expected['tasks'][index]['task_digest']): + raise ValueError('rollout task or slot order changed') + return ids diff --git a/harborrl/rollout/harbor_job/coordinator.py b/harborrl/rollout/harbor_job/coordinator.py index ad6131087..46dad4557 100644 --- a/harborrl/rollout/harbor_job/coordinator.py +++ b/harborrl/rollout/harbor_job/coordinator.py @@ -13,9 +13,10 @@ from pathlib import Path from harborrl.math_registry import CLAUDE_CODE_HARNESS -from harborrl.trajectories.native import assemble, publish +from harborrl.trajectories.native import assemble, publish, validate_v2 from .collector import collect +from .reliability import GatewayTransportFailure class GroupSlots: @@ -65,14 +66,51 @@ def export(self): return export_group([self.completed[slot] for slot in self.identities], len(self.identities)) -def runner_command(runner_python, project, runner_host=None, *, module="harborrl.rollout.harbor_job.runner"): +def runner_command(runner_python, project, runner_host=None, *, + module="harborrl.rollout.harbor_job.runner", extra_args=()): if runner_host is None: - return [runner_python, "-m", module] - remote = f"cd {shlex.quote(str(project))} && exec {shlex.quote(runner_python)} -m {module}" + return [runner_python, "-m", module, *extra_args] + remote = (f"cd {shlex.quote(str(project))} && exec " + + shlex.join([runner_python, '-m', module, *extra_args])) return ["ssh", "-o", "BatchMode=yes", "-o", "ClearAllForwardings=yes", "-o", "StrictHostKeyChecking=accept-new", runner_host, remote] +async def reconcile_runner(sandbox, root, runner_python, project, runner_host, env): + """A fresh host-side observer, outside the terminated runner and its SDK.""" + from .reconcile import cleanup_resolved + command = runner_command(runner_python, project, runner_host, + module='harborrl.rollout.harbor_job.reconcile', extra_args=(str(root),)) + with (root / 'reconciliation.stderr').open('wb') as stderr: + process = await asyncio.create_subprocess_exec( + *command, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.DEVNULL, + stderr=stderr, env=env) + try: + await asyncio.wait_for(process.communicate(json.dumps(sandbox).encode() + b'\n'), + sandbox['cleanup_timeout_s'] * 2 + 30) + finally: + if process.returncode is None: + process.kill() + await process.wait() + return process.returncode == 0 and cleanup_resolved(root) + + +async def settle_reconciliation(*args, propagate_cancel=True): + task = asyncio.create_task(reconcile_runner(*args)) + cancelled = False + while True: + try: + result = await asyncio.shield(task) + break + except asyncio.CancelledError: + cancelled = True + if task.cancelled(): + raise + if cancelled and propagate_cancel: + raise asyncio.CancelledError + return result + + async def run_attempt(identity, *, task_path, profile, gateway_url, runner_python, root, registry, reward_profile, timeout=1800, cleanup_timeout=120, max_output_tokens=8192, runner_host=None, sandbox=None): @@ -98,6 +136,7 @@ async def run_attempt(identity, *, task_path, profile, gateway_url, runner_pytho publish(root / "launch-failed.json", {"identity": identity.to_dict(), "reason": reason}) raise registered, trial_id, lifecycle_timeout = False, None, False + reconciliation_started = False messages = [] try: req = {"identity": identity.to_dict(), "task_path": str(Path(task_path).resolve()), "profile": profile, @@ -144,15 +183,15 @@ async def lifecycle(): registry.close(identity.attempt_id) # Do not kill a serving thread: drain safely or leave a blocking cleanup record. await asyncio.wait_for(process.wait(), cleanup_timeout) - if process.returncode != 0 or terminal["type"] != "terminal": - raise RuntimeError("native trial did not finish normally") if sandbox is not None: - from harborrl.trajectories.native import read_json - lifecycle_path = root / 'runner' / 'sandbox-lifecycle.json' - lifecycle = read_json(lifecycle_path) if lifecycle_path.is_file() else {} - if lifecycle.get('state') != 'deleted' or lifecycle.get('runtime_digest') != req['runtime_digest']: + reconciliation_started = True + if not await settle_reconciliation(sandbox, root, runner_python, project, runner_host, env): publish(root / 'cleanup-required.json', {'identity': identity.to_dict(), 'reason': 'Sandbox deletion unconfirmed'}) - raise RuntimeError('sandbox deletion unconfirmed') + raise RuntimeError('independent sandbox deletion unconfirmed') + if registry.has_nontransport_failure(identity.attempt_id): + raise ValueError('Gateway recorded a non-transport generation failure; retry forbidden') + if process.returncode != 0 or terminal["type"] != "terminal": + raise RuntimeError("native trial did not finish normally") trial_dir = Path(terminal["trial_dir"]).resolve() result_path = Path(terminal["result_path"]).resolve() if not trial_dir.is_relative_to(root / "runner" / "harbor") or result_path != trial_dir / "result.json": @@ -180,17 +219,27 @@ async def lifecycle(): termination='budget_truncated' if termination_evidence else 'completed', termination_evidence=termination_evidence) publish(root / "trajectory.v2.json", ir) + if (registry.transport_failure_only(identity.attempt_id) + and validate_v2(ir) == ['trace_not_sealed']): + # Keep the rejected trace immutable. Only a fresh attempt can recover. + raise GatewayTransportFailure('upstream transport failed; retained trace is ineligible') return ir except BaseException as exc: lifecycle_timeout = isinstance(exc, (asyncio.TimeoutError, asyncio.CancelledError)) + if (registered and not isinstance(exc, (ValueError, asyncio.CancelledError)) + and registry.has_nontransport_failure(identity.attempt_id)): + publish(root / "failure.json", {"identity": identity.to_dict(), + "error_type": "ValueError", "cause_type": type(exc).__name__}) + raise ValueError('Gateway recorded a non-transport generation failure; retry forbidden') from exc publish(root / "failure.json", {"identity": identity.to_dict(), "error_type": type(exc).__name__}) raise finally: - if (sandbox is not None and (root / 'runner' / 'cleanup-required.json').exists() - and not (root / 'cleanup-required.json').exists()): - publish(root / 'cleanup-required.json', {'identity': identity.to_dict(), 'reason': 'Inspect runner/cleanup-required.json'}) if registered: registry.close(identity.attempt_id) + if ((root / 'runner/cleanup-required.json').exists() + and not (root / 'cleanup-required.json').exists()): + publish(root / 'cleanup-required.json', { + 'identity': identity.to_dict(), 'reason': 'Inspect runner/cleanup-required.json'}) if process.returncode is None: try: process.stdin.write(b'{"command":"cancel"}\n') @@ -208,6 +257,29 @@ async def lifecycle(): if (process.returncode != 0 or lifecycle_timeout) and not (root / "cleanup-required.json").exists(): publish(root / "cleanup-required.json", {"identity": identity.to_dict(), "trial_id": trial_id, "reason": "Runner exited abnormally; inspect Harbor resources before retry"}) + if sandbox is not None and not reconciliation_started: + async def finish_cleanup(): + try: + return await reconcile_runner(sandbox, root, runner_python, project, runner_host, env) + except Exception: # noqa: BLE001 - cleanup failure must retain admission debt + return False + cleanup = asyncio.create_task(finish_cleanup()) + while True: + try: + resolved = await asyncio.shield(cleanup) + break + except asyncio.CancelledError: + if cleanup.cancelled(): + raise + continue + if not resolved and not (root / 'cleanup-required.json').exists(): + publish(root / 'cleanup-required.json', { + 'identity': identity.to_dict(), 'reason': 'Independent reconciliation unresolved'}) + if sandbox is not None: + from .reconcile import cleanup_resolved + if not cleanup_resolved(root) and not (root / 'cleanup-required.json').exists(): + publish(root / 'cleanup-required.json', { + 'identity': identity.to_dict(), 'reason': 'Independent reconciliation unresolved'}) if registered: try: registry.seal(identity.attempt_id) diff --git a/harborrl/rollout/harbor_job/environments/opensandbox.py b/harborrl/rollout/harbor_job/environments/opensandbox.py index 436b913a5..75448d748 100644 --- a/harborrl/rollout/harbor_job/environments/opensandbox.py +++ b/harborrl/rollout/harbor_job/environments/opensandbox.py @@ -66,6 +66,10 @@ def extensions(self): return {} def api_params(self): + return self.cleanup_api_params(self.cfg) + + @classmethod + def cleanup_api_params(cls, cfg): return {} def startup_transport(self, allocated): @@ -230,7 +234,6 @@ async def stop(self, delete=True): try: await asyncio.wait_for(sandbox.kill(), self.cfg['cleanup_timeout_s']) self.record_state('deleted') - (self.evidence / 'cleanup-required.json').unlink(missing_ok=True) self._sandbox = None except BaseException: # noqa: BLE001 - preserve cleanup debt on cancellation self.record_state('delete_failed') diff --git a/harborrl/rollout/harbor_job/reconcile.py b/harborrl/rollout/harbor_job/reconcile.py new file mode 100644 index 000000000..de45916c5 --- /dev/null +++ b/harborrl/rollout/harbor_job/reconcile.py @@ -0,0 +1,371 @@ +"""Independent, bounded Sandbox cleanup; never trust an SDK delete receipt. + +The CLI runs on the runner host after the trial process exits. Only the ID +in this attempt's locked lifecycle can be deleted. History is retained and +closed by a separate immutable receipt. +""" +from __future__ import annotations + +import argparse +import asyncio +import math +import os +import re +import secrets +import signal +import socket +import sys +import time +from pathlib import Path + +import httpx + +from harborrl.trajectories.native import digest, publish, read_json + + +def process_info(pid): + text = (Path('/proc') / str(pid) / 'stat').read_text() + fields = text[text.rindex(')') + 2:].split() + return {'pid': int(pid), 'state': fields[0], 'ppid': int(fields[1]), 'pgrp': int(fields[2]), + 'session': int(fields[3]), 'start_ticks': int(fields[19])} + + +def register_runner(root, identity): + """Give the independent observer a session and inherited ownership tag.""" + if os.getsid(0) != os.getpid(): + os.setsid() + os.environ['HARBORRL_ATTEMPT_ID'] = identity['attempt_id'] + publish(Path(root) / 'runner-process.json', { + **process_info(os.getpid()), 'host': socket.gethostname(), + 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), + 'attempt_id': identity['attempt_id']}) + + +def observer_ancestors(owner): + """Prove observer ancestry rather than ignoring protected process names.""" + ancestors, child = {}, process_info(os.getpid()) + if (child['session'] == owner['session'] or child['pid'] == owner['pid'] + or os.environ.get('HARBORRL_ATTEMPT_ID') == owner['attempt_id']): + raise RuntimeError('process observer belongs to the runner; independent observer required') + while child['ppid']: + parent = process_info(child['ppid']) + current = process_info(child['pid']) + if (current['ppid'] != child['ppid'] or current['start_ticks'] != child['start_ticks'] + or parent['start_ticks'] > child['start_ticks'] or parent['pid'] in ancestors): + raise RuntimeError('observer ancestry changed; process ownership uncertain') + if parent['session'] == owner['session'] or parent['pid'] == owner['pid']: + raise RuntimeError('process observer is a runner descendant; independent observer required') + ancestors[parent['pid']] = parent['start_ticks'] + child = parent + return ancestors + + +def owned_processes(owner): + if owner['host'] != socket.gethostname(): + raise RuntimeError('process observer is on a different runner host') + if owner.get('boot_id') and owner['boot_id'] != Path( + '/proc/sys/kernel/random/boot_id').read_text().strip(): + raise RuntimeError('runner host restarted; process ownership uncertain') + try: + leader = process_info(owner['pid']) + except FileNotFoundError: + leader = None + if leader is not None and leader['start_ticks'] != owner['start_ticks']: + raise RuntimeError('runner PID was reused; process ownership uncertain') + ancestors = observer_ancestors(owner) + tag = ('HARBORRL_ATTEMPT_ID=' + owner['attempt_id']).encode() + found = [] + for path in Path('/proc').iterdir(): + if not path.name.isdecimal() or int(path.name) == os.getpid(): + continue + try: + info = process_info(int(path.name)) + # Zombies cannot execute or hold a live agent connection. + if info['state'] == 'Z': + continue + if ancestors.get(info['pid']) == info['start_ticks']: + continue + member = info['session'] == owner['session'] + # A process older than the runner cannot be its descendant. Do not + # require access to protected platform services that predate it. + # Equal ticks remain in scope: children can fork within one tick. + if not member and info['start_ticks'] < owner['start_ticks']: + continue + tagged = not member and tag in (path / 'environ').read_bytes().split(b'\0') + if member or tagged: + found.append(info) + except (FileNotFoundError, ProcessLookupError): + continue + # Unreadable processes within the possible descendant lifetime fail + # closed, including those that escaped the original session. + return found + + +async def close_owned_processes(owner, *, deadline): + observations = [] + + async def scan(sig): + while True: + try: + processes = owned_processes(owner) + except (OSError, RuntimeError) as exc: + observations.append({'signal': int(sig) if sig else None, 'processes': None, + 'error_type': type(exc).__name__, + 'errno': getattr(exc, 'errno', None)}) + # /proc can become unreadable during exec/exit. Retry a full + # scan, never interpret an unreadable process as absent. PID + # reuse, host changes and persistent read errors retain debt. + remaining = deadline - time.monotonic() + if isinstance(exc, RuntimeError) or remaining <= 0: + return None + await asyncio.sleep(min(.1, remaining)) + else: + observations.append({'signal': int(sig) if sig else None, 'processes': processes}) + return processes + + for sig in (None, signal.SIGTERM, signal.SIGKILL): + processes = await scan(sig) + if processes is None: + return {'verified_absent': False, 'observations': observations} + if not processes: + return {'verified_absent': True, 'observations': observations} + if time.monotonic() >= deadline: + return {'verified_absent': False, 'observations': observations} + if sig is not None: + for process in processes: + try: + current = process_info(process['pid']) + if current['start_ticks'] != process['start_ticks']: + raise RuntimeError('owned process PID changed during cleanup') + os.kill(process['pid'], sig) + except (FileNotFoundError, ProcessLookupError): + pass + except (OSError, RuntimeError) as exc: + observations.append({'signal': int(sig), 'processes': None, + 'error_type': type(exc).__name__, + 'errno': getattr(exc, 'errno', None)}) + return {'verified_absent': False, 'observations': observations} + await asyncio.sleep(min(1.0, max(0, deadline - time.monotonic()))) + survivors = await scan(None) + return {'verified_absent': survivors == [], 'observations': observations} + + +def processes_verified_absent(proof): + if not isinstance(proof, dict) or proof.get('verified_absent') is not True: + return False + rows = proof.get('observations') + if not isinstance(rows, list) or not rows: + return False + for row in rows: + if (not isinstance(row, dict) or 'signal' not in row + or row['signal'] not in (None, int(signal.SIGTERM), int(signal.SIGKILL))): + return False + if (row.get('processes', 'missing') is None + and isinstance(row.get('error_type'), str) and row['error_type']): + continue + if not isinstance(row.get('processes'), list) or 'error_type' in row: + return False + for process in row['processes']: + if not isinstance(process, dict) or any( + type(process.get(key)) is not int or process[key] < minimum + for key, minimum in (('pid', 1), ('session', 1), ('start_ticks', 0))): + return False + return rows[-1]['processes'] == [] + + +def inventory_verified_absent(receipt): + sid, ids, rows = receipt.get('sandbox_id'), receipt.get('inventory_ids'), receipt['observations'] + if (not isinstance(ids, list) or any(not isinstance(value, str) or not value for value in ids) + or len(set(ids)) != len(ids) or sid in ids): + return False + get_index = next((index for index in reversed(range(len(rows))) + if rows[index].get('operation') == 'get' + and rows[index].get('http_status') == 404), None) + if get_index is None: + return False + pages = rows[get_index + 1:] + observed, total = set(), None + if not pages: + return False + for index, row in enumerate(pages, 1): + page_ids, count = row.get('ids'), row.get('total_items') + if (row.get('operation') != 'inventory' or row.get('http_status') != 200 + or type(row.get('page')) is not int or row['page'] != index + or type(count) is not int or count < 0 + or type(row.get('has_next_page')) is not bool + or row['has_next_page'] != (index < len(pages)) + or not isinstance(page_ids, list) + or any(not isinstance(value, str) or not value for value in page_ids) + or len(set(page_ids)) != len(page_ids) or observed.intersection(page_ids) + or (index < len(pages) and not page_ids) + or (total is not None and total != count)): + return False + total = count + observed.update(page_ids) + return len(observed) == total and observed == set(ids) + + +async def inventory(client, base, params, observations, *, max_pages=100): + """Require complete, consistent pagination, never an empty first page alone.""" + ids, total = set(), None + for page in range(1, max_pages + 1): + response = await client.get(base + '/sandboxes', + params={**params, 'page': page, 'pageSize': 100}) + row = {'operation': 'inventory', 'page': page, 'http_status': response.status_code} + observations.append(row) + if response.status_code != 200: + return None + body = response.json() + items, pagination = body.get('items'), body.get('pagination') + if not isinstance(items, list) or not isinstance(pagination, dict): + raise TypeError('incomplete inventory schema') + more, count = pagination.get('hasNextPage'), pagination.get('totalItems') + if type(more) is not bool or type(count) is not int or count < 0: + raise ValueError('invalid inventory pagination') + if total is not None and count != total: + return None # Inventory changed while paging; restart a full observation. + total = count + page_ids = [item.get('id') for item in items if isinstance(item, dict)] + if (len(page_ids) != len(items) or any(not isinstance(sid, str) or not sid for sid in page_ids) + or len(set(page_ids)) != len(page_ids) or ids.intersection(page_ids)): + raise ValueError('invalid or repeated inventory entries') + ids.update(page_ids) + row.update(ids=sorted(page_ids), has_next_page=more, total_items=total) + if not more: + if len(ids) != total: + raise ValueError('inventory total does not match complete pages') + return sorted(ids) + if not items: + raise ValueError('empty intermediate inventory page') + raise ValueError('inventory page budget exhausted') + + +async def reconcile_instance(cfg, lifecycle, *, params, credential, process_proof, + transport=None, retry_interval=2.0): + started = time.monotonic() + deadline = started + cfg['cleanup_timeout_s'] + sid = lifecycle.get('sandbox_id') + receipt = {'schema': 'harborrl-cleanup-v1', 'runtime_digest': digest(cfg), + 'sandbox_id': sid, 'status': 'unresolved', 'observations': [], + 'process_proof': process_proof, 'lifecycle_sha256': digest(lifecycle)} + observations = receipt['observations'] + if lifecycle.get('runtime_digest') != digest(cfg): + receipt['reason'] = 'runtime lock mismatch' + elif not processes_verified_absent(process_proof): + receipt['reason'] = 'owned processes remain or ownership unverified' + elif not sid and lifecycle.get('state') in {'pending', 'waiting', 'reserved'}: + receipt.update(status='not_allocated', reason='creation never started') + elif not isinstance(sid, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', sid): + receipt['reason'] = 'unknown allocation; automatic deletion forbidden' + else: + base = cfg['domain'].rstrip('/') + '/v1' + try: + async with asyncio.timeout(cfg['cleanup_timeout_s']): + async with httpx.AsyncClient( + timeout=min(cfg['request_timeout_s'], cfg['cleanup_timeout_s']), + headers={'OPEN-SANDBOX-API-KEY': credential}, transport=transport) as client: + while True: + try: + response = await client.get(base + '/sandboxes/' + sid, params=params) + observations.append({'operation': 'get', 'http_status': response.status_code}) + if response.status_code == 404: + ids = await inventory(client, base, params, observations) + if ids is not None and sid not in ids: + receipt.update(status='verified_absent', inventory_ids=ids, + inventory_complete=True, get404=True, + reconciled_lifecycle='deleted') + break + elif response.status_code == 200: + deleted = await client.delete(base + '/sandboxes/' + sid, params=params) + observations.append({'operation': 'delete', 'http_status': deleted.status_code}) + elif response.status_code in {401, 403}: + receipt['reason'] = 'cleanup authorization rejected' + break + except (httpx.HTTPError, ValueError, TypeError) as exc: + observations.append({'operation': 'observe', 'error_type': type(exc).__name__}) + await asyncio.sleep(min(retry_interval, max(0, deadline - time.monotonic()))) + except TimeoutError: + receipt['reason'] = 'independent cleanup deadline exceeded' + receipt['elapsed_sec'] = time.monotonic() - started + return receipt + + +def cleanup_resolved(root): + root = Path(root) + receipt_path = root / 'cleanup-reconciliation.json' + if not receipt_path.is_file(): + return False + try: + receipt = read_json(receipt_path) + lifecycle = read_json(root / 'runner/sandbox-lifecycle.json') + owner = read_json(root / 'runner-process.json') + if not all(isinstance(item, dict) for item in (receipt, lifecycle, owner)): + return False + proof, observations = receipt.get('process_proof'), receipt.get('observations') + if (not isinstance(proof, dict) or not isinstance(observations, list) + or not all(isinstance(item, dict) for item in observations)): + return False + common = (receipt.get('schema') == 'harborrl-cleanup-v1' + and receipt.get('runtime_digest') == lifecycle.get('runtime_digest') + and receipt.get('lifecycle_sha256') == digest(lifecycle) + and receipt.get('owner_sha256') == digest(owner) + and processes_verified_absent(proof) + and type(receipt.get('elapsed_sec')) in {float, int} + and math.isfinite(receipt['elapsed_sec']) + and receipt['elapsed_sec'] >= 0) + if not common: + return False + if receipt.get('status') == 'not_allocated': + return (not lifecycle.get('sandbox_id') + and lifecycle.get('state') in {'pending', 'waiting', 'reserved'}) + return (receipt.get('status') == 'verified_absent' + and isinstance(lifecycle.get('sandbox_id'), str) + and receipt.get('sandbox_id') == lifecycle['sandbox_id'] + and receipt.get('get404') is True + and receipt.get('inventory_complete') is True + and receipt.get('reconciled_lifecycle') == 'deleted' + and inventory_verified_absent(receipt)) + except (OSError, ValueError, TypeError): + return False + + +def cleanup_debt(root): + root = Path(root) + return (any((root / path).exists() for path in + ('cleanup-required.json', 'runner/cleanup-required.json', + 'runner/sandbox-lifecycle.json', 'runner-process.json')) + and not cleanup_resolved(root)) + +async def reconcile_attempt(cfg, root): + from harborrl.rollout.harbor_job.sandbox_config import ( + environment_class, + read_credential, + ) + + root = Path(root) + if cleanup_resolved(root): + return read_json(root / 'cleanup-reconciliation.json') + lifecycle = read_json(root / 'runner/sandbox-lifecycle.json') + owner = read_json(root / 'runner-process.json') + proof = await close_owned_processes(owner, deadline=time.monotonic() + cfg['cleanup_timeout_s']) + cls = environment_class(cfg) + receipt = await reconcile_instance(cfg, lifecycle, params=cls.cleanup_api_params(cfg), + credential=read_credential(cfg), process_proof=proof) + receipt['owner_sha256'] = digest(owner) + publish(root / 'cleanup-reconciliations' / f'{secrets.token_hex(16)}.json', receipt) + if receipt['status'] in {'verified_absent', 'not_allocated'}: + publish(root / 'cleanup-reconciliation.json', receipt) + return receipt + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('root') + args = parser.parse_args() + cfg = __import__('json').loads(sys.stdin.readline()) + receipt = asyncio.run(reconcile_attempt(cfg, args.root)) + if receipt['status'] not in {'verified_absent', 'not_allocated'}: + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/harborrl/rollout/harbor_job/reliability.py b/harborrl/rollout/harbor_job/reliability.py new file mode 100644 index 000000000..e0bdfb551 --- /dev/null +++ b/harborrl/rollout/harbor_job/reliability.py @@ -0,0 +1,370 @@ +"""Reliability control plane for Sandbox rollout failures. + +The ledger is independent from rewards and trajectory exports. It records +infrastructure decisions so platform recovery can be audited without turning +partial attempts into training data. +""" +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import time +from collections import Counter, defaultdict +from dataclasses import dataclass +from pathlib import Path + +ATTEMPT_STATES = frozenset({ + "reserved", "creating", "allocated", "starting", "ready", "executing", + "completed", "failed", "cleaning", "verified_absent", +}) +FAILURE_KINDS = frozenset({ + "create-deadline", "node-unhealthy", "schedule-pressure", "startup-timeout", + "runtime-fault", "transient-io", "storage-fault", "cleanup-fault", + "cancel-fault", "task-invalid", "unknown", +}) +_CREATE_DEADLINE = re.compile( + r"FailedCreatePodSandBox|DeadlineExceeded|pod name reserved|CRI-O timeout", re.IGNORECASE) +_NODE = re.compile(r"\b(?:node|sbx)-[a-z0-9-]+\b", re.IGNORECASE) +_NO_SPACES = re.compile(r"\s+") + + +def _utc_now(): + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def _event_digest(event): + """Hash all semantic fields, excluding the digest itself.""" + encoded = json.dumps({key: value for key, value in event.items() + if key != "event_sha256"}, + sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +def sanitize_evidence(value): + if isinstance(value, dict): + return {str(key): ('' if re.search( + r'(?:token|credential|password|secret|authorization|api[_-]?key)', str(key), re.IGNORECASE) + else sanitize_evidence(item)) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [sanitize_evidence(item) for item in value] + if isinstance(value, str): + text = re.sub(r"https?://\S+", "", value) + text = re.sub(r"\b(?:token|credential|authorization|api[_-]?key)\s*[:=]\s*\S+", "", text, flags=re.IGNORECASE) + return _NO_SPACES.sub(" ", text).strip()[:2048] + if value is None or isinstance(value, (bool, int, float)): + return value + return str(value) + + +def classify_failure(stage, error, *, evidence=None): + stage = str(stage or "unknown").lower() + if stage == 'protocol': + return 'task-invalid' + text = error if isinstance(error, str) else f"{type(error).__name__}: {error}" + if isinstance(evidence, dict): + text += " " + json.dumps(evidence, sort_keys=True, default=str) + elif evidence: + text += " " + str(evidence) + text = sanitize_evidence(text) + lowered = text.lower() + if any(word in lowered for word in ("enospc", "no space left", "read-back mismatch")): + return "storage-fault" + if _CREATE_DEADLINE.search(lowered): + return "create-deadline" + insufficient = "failedscheduling" in lowered or ( + "insufficient" in lowered and any(word in lowered for word in ("cpu", "memory", "device"))) + if insufficient: + return "schedule-pressure" + if any(word in lowered for word in ("incomplete read", "connection reset", "download 500", "transient io")): + return "transient-io" + if stage in {"create", "allocation"} and any(word in lowered for word in ("503", "504", "deadline", "timeout")): + return "create-deadline" + if stage in {"startup", "readiness", "install"}: + return "startup-timeout" + if stage in {"cleanup", "delete", "reconcile"}: + return "cleanup-fault" + if stage == "cancel": + return "cancel-fault" + if stage == "storage": + return "storage-fault" + if "task lock" in lowered or "verifier lock" in lowered: + return "task-invalid" + if stage in {"execute", "runtime", "command"} or isinstance(error, RuntimeError): + return "runtime-fault" + return "unknown" + + +def extract_node(error, evidence=None): + text = error if isinstance(error, str) else f"{type(error).__name__}: {error}" + if isinstance(evidence, dict): + text += " " + json.dumps(evidence, sort_keys=True, default=str) + match = _NODE.search(text) + return match.group(0).lower() if match else None + + +@dataclass(frozen=True) +class RetryPolicy: + max_attempts_per_slot: int = 3 + backoff_seconds: tuple = (5.0, 15.0, 45.0) + max_backoff_seconds: float = 120.0 + node_consecutive_failures: int = 2 + node_cooldown_seconds: float = 900.0 + + def __post_init__(self): + if type(self.max_attempts_per_slot) is not int or self.max_attempts_per_slot < 1: + raise ValueError("max_attempts_per_slot must be a positive integer") + if not self.backoff_seconds or any(not math.isfinite(x) or x < 0 for x in self.backoff_seconds): + raise ValueError("backoff_seconds must contain finite non-negative values") + if not math.isfinite(self.max_backoff_seconds) or self.max_backoff_seconds < 0: + raise ValueError("invalid max_backoff_seconds") + if type(self.node_consecutive_failures) is not int or self.node_consecutive_failures < 1: + raise ValueError("node_consecutive_failures must be positive") + if not math.isfinite(self.node_cooldown_seconds) or self.node_cooldown_seconds < 0: + raise ValueError("invalid node_cooldown_seconds") + + def delay(self, retry_index): + if type(retry_index) is not int or retry_index < 0: + raise ValueError("retry_index must be non-negative") + return min(self.backoff_seconds[min(retry_index, len(self.backoff_seconds) - 1)], self.max_backoff_seconds) + + +@dataclass +class InfraBudget: + attempts: int + create_retries: int + cleanup_reconciliations: int + storage_faults: int + wall_clock_seconds: float + + def __post_init__(self): + for name in ("attempts", "create_retries", "cleanup_reconciliations", "storage_faults"): + value = getattr(self, name) + if type(value) is not int or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not math.isfinite(self.wall_clock_seconds) or self.wall_clock_seconds <= 0: + raise ValueError("wall_clock_seconds must be positive") + self.remaining = { + "attempts": self.attempts, + "create_retries": self.create_retries, + "cleanup_reconciliations": self.cleanup_reconciliations, + "storage_faults": self.storage_faults, + } + self.expires_at = time.monotonic() + self.wall_clock_seconds + + def consume(self, name, amount=1): + if name not in self.remaining: + raise ValueError(f"unknown infrastructure budget: {name}") + if type(amount) is not int or amount < 1: + raise ValueError("budget amount must be positive") + if amount > self.remaining[name] or self.expired(): + raise InfraBudgetExhausted(f"infrastructure budget exhausted: {name}") + self.remaining[name] -= amount + + def expired(self): + return time.monotonic() >= self.expires_at + + def exhausted(self): + return self.expired() or any(value == 0 for value in self.remaining.values()) + + def to_dict(self): + return { + "limits": {"attempts": self.attempts, "create_retries": self.create_retries, + "cleanup_reconciliations": self.cleanup_reconciliations, + "storage_faults": self.storage_faults, + "wall_clock_seconds": self.wall_clock_seconds}, + "remaining": dict(self.remaining), + "wall_clock_expired": self.expired(), + } + + +class InfraBudgetExhausted(RuntimeError): + pass + + +class RetryableRolloutFailure(RuntimeError): + """Infrastructure attempt exhaustion after independently completed cleanup.""" + + +class GatewayTransportFailure(RuntimeError): + """Trusted Gateway transport failure with otherwise valid collected evidence.""" + + +class CleanupUnresolved(RuntimeError): + """Admission must remain closed until independent reconciliation succeeds.""" + + +class ReliabilityLedger: + """Append-only event journal for one run or seed.""" + + def __init__(self, root, *, policy=None, budget=None, clock=time.monotonic): + self.root = Path(root) + self.root.mkdir(parents=True, exist_ok=True) + self.path = self.root / "events.jsonl" + self.policy = policy or RetryPolicy() + self.budget = budget + self.clock = clock + self._sequence = 0 + self._nodes = defaultdict(list) + self._cooldowns = {} + self._last_event_sha256 = None + last_budget = None + if self.path.exists(): + for line in self.path.read_text(encoding="utf-8").splitlines(): + event = json.loads(line) + self._sequence = max(self._sequence, int(event["sequence"])) + if event.get("previous_event_sha256") != self._last_event_sha256: + raise ValueError("event hash chain is not append-only") + expected = event.get("event_sha256") + if expected != _event_digest(event): + raise ValueError("event hash does not match content") + self._last_event_sha256 = expected + last_budget = event.get('budget') + if event.get("node") and event.get("kind") in FAILURE_KINDS: + self._record_node(event["node"], float(event.get("monotonic_time", 0))) + if budget is not None: + from harborrl.trajectories.native import publish, read_json + + path = self.root / 'budget-lock.json' + limits = budget.to_dict()['limits'] + if path.exists(): + locked = read_json(path) + if locked['limits'] != limits: + raise ValueError('seed infrastructure budget changed; use a fresh protocol') + else: + locked = {'limits': limits, 'expires_utc_epoch': time.time() + budget.wall_clock_seconds} + publish(path, locked) + budget.expires_at = time.monotonic() + locked['expires_utc_epoch'] - time.time() + if last_budget is not None: + if last_budget['limits'] != limits: + raise ValueError('seed infrastructure event budget differs from lock') + budget.remaining = dict(last_budget['remaining']) + elif last_budget is not None or (self.root / 'budget-lock.json').exists(): + raise ValueError('cannot reopen a budgeted seed without its infrastructure budget') + + def event(self, attempt_id, state, *, stage="", kind="", node=None, + sandbox_id=None, decision="", detail=None): + if state not in ATTEMPT_STATES: + raise ValueError(f"unknown attempt state: {state}") + if kind and kind not in FAILURE_KINDS: + raise ValueError(f"unknown failure kind: {kind}") + self._sequence += 1 + event = { + "sequence": self._sequence, + "time_utc": _utc_now(), + "monotonic_time": self.clock(), + "attempt_id": str(attempt_id), + "state": state, + "stage": str(stage or ""), + "kind": str(kind or ""), + "node": str(node).lower() if node else None, + "sandbox_id": str(sandbox_id) if sandbox_id else None, + "decision": str(decision or ""), + "budget": self.budget.to_dict() if self.budget else None, + "detail": sanitize_evidence(detail), + } + event["previous_event_sha256"] = self._last_event_sha256 + event["event_sha256"] = _event_digest(event) + self._last_event_sha256 = event["event_sha256"] + encoded = json.dumps(event, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + with self.path.open("a", encoding="utf-8", newline="\n") as stream: + stream.write(encoded + "\n") + stream.flush() + os.fsync(stream.fileno()) + return event + + def _record_node(self, node, timestamp): + failures = [stamp for stamp in self._nodes[node] if timestamp - stamp < self.policy.node_cooldown_seconds] + failures.append(timestamp) + self._nodes[node] = failures + if len(failures) >= self.policy.node_consecutive_failures: + self._cooldowns[node] = timestamp + self.policy.node_cooldown_seconds + return True + return False + + def observe_failure(self, attempt_id, stage, error, *, evidence=None, + sandbox_id=None, retry_index=0): + kind = classify_failure(stage, error, evidence=evidence) + node = extract_node(error, evidence) + delay = self.policy.delay(retry_index) + node_cooled = self._record_node(node, self.clock()) if node else False + decision = "fail-seed" if kind == 'task-invalid' else "retry" + budget_error = None + if self.budget: + try: + if kind == "storage-fault": + self.budget.consume("storage_faults") + elif kind == "cleanup-fault": + self.budget.consume("cleanup_reconciliations") + elif stage in {"create", "allocation"}: + self.budget.consume("create_retries") + if self.budget.expired(): + raise InfraBudgetExhausted('infrastructure wall clock exhausted') + except InfraBudgetExhausted as exc: + decision = "fail-seed" + budget_error = exc + self.event(attempt_id, "failed", stage=stage, kind=kind, node=node, + sandbox_id=sandbox_id, decision=decision, + detail={"error": error if isinstance(error, str) else f"{type(error).__name__}: {error}", + "evidence": evidence, + "retry_delay_s": delay, + "node_cooldown": node_cooled}) + if budget_error is not None: + raise budget_error + return kind, node, delay if decision == "retry" else None + + def node_available(self, node): + return not node or self.clock() >= self._cooldowns.get(node, 0) + + def next_node(self, candidates, preferred=None): + available = [node for node in candidates if self.node_available(node)] + return preferred if preferred in available else (available[0] if available else None) + + def reserve(self, attempt_id, *, task_digest, policy_version, retry_index, node=None): + if self.budget: + self.budget.consume("attempts") + return self.event(attempt_id, "reserved", stage="attempt", node=node, + decision="start", + detail={"task_digest": task_digest, "policy_version": policy_version, + "retry_index": retry_index}) + + +def summarize_reliability(root): + path = Path(root) / "events.jsonl" + if not path.exists(): + raise FileNotFoundError(path) + events = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + if [event["sequence"] for event in events] != list(range(1, len(events) + 1)): + raise ValueError("event sequence is not append-only") + previous = None + for event in events: + if event.get("previous_event_sha256") != previous or event.get("event_sha256") != _event_digest(event): + raise ValueError("event hash chain is not append-only") + previous = event["event_sha256"] + attempts = defaultdict(list) + for event in events: + attempts[event["attempt_id"]].append(event) + states = {attempt_id: items[-1]["state"] for attempt_id, items in attempts.items()} + kinds = Counter(event["kind"] for event in events if event["kind"]) + completed = sum(any(event['state'] == 'completed' for event in items) + for items in attempts.values()) + failed = sum(any(event['state'] == 'failed' for event in items) + for items in attempts.values()) + cleaned = sum(state == "verified_absent" for state in states.values()) + return { + "events": len(events), + "attempts": len(attempts), + "completed_attempts": completed, + "failed_attempts": failed, + "verified_absent_attempts": cleaned, + "terminal_attempts": sum(any(event['state'] in {'completed', 'failed', 'verified_absent'} + for event in items) for items in attempts.values()), + "failure_counts": dict(sorted(kinds.items())), + "retry_decisions": sum(bool(event.get("kind")) and event.get("decision") == "retry" + for event in events), + "fail_seed_decisions": sum(event.get("decision") == "fail-seed" for event in events), + "node_cooldown_events": sum( + bool((event.get("detail") or {}).get("node_cooldown")) for event in events), + } diff --git a/harborrl/rollout/harbor_job/runner.py b/harborrl/rollout/harbor_job/runner.py index 19cfc59ee..6a486ffca 100644 --- a/harborrl/rollout/harbor_job/runner.py +++ b/harborrl/rollout/harbor_job/runner.py @@ -53,6 +53,9 @@ async def execute(request, emit, read_command): publish(root / "manifest.json", {"identity": identity.to_dict(), "task": inspection, "profile": request["profile"], "gateway_url": request["gateway_url"]}) sandbox = request.get('sandbox') + if sandbox is not None: + publish(root / 'sandbox-lifecycle.json', { + 'state': 'pending', 'sandbox_id': None, 'runtime_digest': digest(sandbox)}) agent_gateway = request['gateway_url'] if sandbox is not None: from harborrl.rollout.harbor_job.sandbox_config import environment_class @@ -158,6 +161,9 @@ def emit(value): sys.__stdout__.write(json.dumps(value) + "\n") sys.__stdout__.flush() first = await read() + if first.get('sandbox') is not None: + from harborrl.rollout.harbor_job.reconcile import register_runner + register_runner(Path(first['output']).parent, first['identity']) with contextlib.redirect_stdout(sys.stderr): await execute(first, emit, read) diff --git a/harborrl/rollout/harbor_job/sandbox_config.py b/harborrl/rollout/harbor_job/sandbox_config.py index 1d52b7909..a4f5e11d7 100644 --- a/harborrl/rollout/harbor_job/sandbox_config.py +++ b/harborrl/rollout/harbor_job/sandbox_config.py @@ -136,15 +136,65 @@ def __init__(self, cfg): self.total = asyncio.Semaphore(cfg['max_live_instances']) self.bindings = {b['image']: asyncio.Semaphore(b['max_live_instances']) for b in cfg['bindings']} self.blocked = False + self.debts = {} + self._blocked = asyncio.Event() + + async def _acquire(self, semaphore): + from .reliability import CleanupUnresolved + + acquired = asyncio.create_task(semaphore.acquire()) + blocked = asyncio.create_task(self._blocked.wait()) + handed_off = False + try: + await asyncio.wait((acquired, blocked), return_when=asyncio.FIRST_COMPLETED) + if self.blocked: + raise CleanupUnresolved('sandbox admission blocked by unresolved cleanup') + await acquired + handed_off = True + finally: + for task in (acquired, blocked): + if not task.done(): + task.cancel() + await asyncio.gather(acquired, blocked, return_exceptions=True) + if not handed_off and not acquired.cancelled() and acquired.exception() is None: + semaphore.release() @asynccontextmanager async def lease(self, binding, root): # Wait for image-specific capacity before reserving a global live slot. - async with self.bindings[binding['image']], self.total: + from .reconcile import cleanup_debt + image = self.bindings[binding['image']] + if self.blocked: + raise RuntimeError('sandbox admission blocked by unresolved cleanup') + await self._acquire(image) + acquired_total = False + retained = False + try: + await self._acquire(self.total) + acquired_total = True if self.blocked: raise RuntimeError('sandbox admission blocked by unresolved cleanup') try: yield finally: - if (Path(root) / 'cleanup-required.json').exists(): + if cleanup_debt(root): self.blocked = True + self._blocked.set() + retained = True + self.debts[str(Path(root).resolve())] = image + finally: + if not retained: + if acquired_total: + self.total.release() + image.release() + + def reconcile(self, root): + from .reconcile import cleanup_resolved + key = str(Path(root).resolve()) + if key not in self.debts or not cleanup_resolved(root): + raise RuntimeError('cleanup debt does not have a verified receipt') + self.debts.pop(key).release() + self.total.release() + self.blocked = bool(self.debts) + if not self.blocked: + self._blocked.clear() diff --git a/harborrl/rollout/runtime.py b/harborrl/rollout/runtime.py index 5e3107800..5b0fe5039 100644 --- a/harborrl/rollout/runtime.py +++ b/harborrl/rollout/runtime.py @@ -33,6 +33,14 @@ publish, read_json, ) +from harborrl.rollout.harbor_job.reliability import ( + CleanupUnresolved, + InfraBudget, + InfraBudgetExhausted, + ReliabilityLedger, + RetryableRolloutFailure, + RetryPolicy, +) TASK_ENTRY_KEYS = {"id", "revision", "path", "task_digest", "reward_profile"} SHARD_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,31}") @@ -176,6 +184,9 @@ class RolloutRuntimeConfig: gateway_hosts: tuple = () hf_ckpt: str = None shard_python: str = None + reliability_policy: dict = None + infra_budget: dict = None + generation_policy: dict = None def __post_init__(self): if self.sampling_seed is not None and ( @@ -302,6 +313,16 @@ def from_environment(cls, env, *, endpoint, concurrency_limit, group_size, # more. A declared table keeps the historical static default. declared_routing = env.get("HARBORRL_NATIVE_GATEWAY_ROUTING") declared_routing = declared_routing.strip() if isinstance(declared_routing, str) else "" + try: + reliability_policy = json.loads(env.get("HARBORRL_NATIVE_RELIABILITY_POLICY") or "null") + infra_budget = json.loads(env.get("HARBORRL_NATIVE_INFRA_BUDGET") or "null") + generation_policy = json.loads(env.get('HARBORRL_NATIVE_GENERATION_POLICY') or 'null') + except ValueError as exc: + raise ValueError("invalid reliability control configuration") from exc + if reliability_policy is not None and not isinstance(reliability_policy, dict): + raise ValueError("reliability policy must be a JSON object") + if infra_budget is not None and not isinstance(infra_budget, dict): + raise ValueError("infrastructure budget must be a JSON object") return cls( run_id=cls._required(env, "RUN_ID"), run_root=cls._required(env, "RUN_DIR"), @@ -321,7 +342,7 @@ def from_environment(cls, env, *, endpoint, concurrency_limit, group_size, runner_python=runner_python, workers=tuple(workers), task_worker_overrides=dict(overrides), - max_attempts=int(env.get("HARBORRL_NATIVE_MAX_ATTEMPTS", "2")), + max_attempts=int(env.get("HARBORRL_NATIVE_MAX_ATTEMPTS", "3")), max_output_tokens=int(env.get("ROLLOUT_MAX_RESPONSE_LEN", "8192")), max_context=int(env.get("ROLLOUT_MAX_CONTEXT_LEN", "32768")), concurrency_limit=max(1, int(concurrency_limit)), @@ -336,6 +357,9 @@ def from_environment(cls, env, *, endpoint, concurrency_limit, group_size, runner_transport=env.get('HARBORRL_NATIVE_RUNNER_TRANSPORT', 'ssh'), sampling_seed=(int(env['HARBORRL_TRAINING_SEED']) if 'HARBORRL_TRAINING_SEED' in env else None), + reliability_policy=reliability_policy, + infra_budget=infra_budget, + generation_policy=generation_policy, ) @staticmethod @@ -427,6 +451,12 @@ def environment(self): if self.shard_python else {}), **({'HARBORRL_TRAINING_SEED': str(self.sampling_seed)} if self.sampling_seed is not None else {}), + **({'HARBORRL_NATIVE_RELIABILITY_POLICY': json.dumps(self.reliability_policy)} + if self.reliability_policy is not None else {}), + **({'HARBORRL_NATIVE_INFRA_BUDGET': json.dumps(self.infra_budget)} + if self.infra_budget is not None else {}), + **({'HARBORRL_NATIVE_GENERATION_POLICY': json.dumps(self.generation_policy)} + if self.generation_policy is not None else {}), } @@ -688,6 +718,14 @@ def __init__(self, config, tokenizer, *, backend=None): if config.sandbox: from harborrl.rollout.harbor_job.sandbox_config import SandboxAdmission self.sandbox_admission = SandboxAdmission(config.sandbox) + try: + policy = RetryPolicy(max_attempts_per_slot=config.max_attempts, + **(config.reliability_policy or {})) + budget = InfraBudget(**config.infra_budget) if config.infra_budget else None + except (TypeError, ValueError) as exc: + raise ValueError(f"invalid Sandbox reliability configuration: {exc}") from exc + self.reliability = ReliabilityLedger( + self.run_root / "sandbox-reliability", policy=policy, budget=budget) tokenizer_digest, template_digest = tokenizer_fingerprint(tokenizer) if (tokenizer_digest != config.expected_tokenizer_digest or template_digest != config.expected_template_digest): @@ -698,6 +736,7 @@ def __init__(self, config, tokenizer, *, backend=None): self.backend = backend or SGLangBackend( config.endpoint, tokenizer, model.adapter, tokenizer_digest=tokenizer_digest, template_digest=template_digest, + rejected_root=self.run_root / 'rejected-generations', max_context=config.max_context, audited_raw_logprobs=config.audited_raw_logprobs, sampling_seed=config.sampling_seed, @@ -1156,11 +1195,15 @@ def task_entry(sample): def slot_identity(config, group_index, slot, rollout_id, entry, - reward_digest, sampling_digest, policy_version, *, harness_digest=None): + reward_digest, sampling_digest, policy_version, *, harness_digest=None, + rollout_generation=None): + from harborrl.rollout.generations import generation_batch_id, generation_group_id return Identity( run_id=config.run_id, - batch_id=f"rollout-{rollout_id}", - group_id=f"group-{group_index}", + batch_id=(f'rollout-{rollout_id}' if rollout_generation is None else + generation_batch_id(rollout_id, rollout_generation)), + group_id=(f'group-{group_index}' if rollout_generation is None else + generation_group_id(rollout_id, rollout_generation, group_index)), slot_id=str(slot), attempt_id=secrets.token_hex(16), trajectory_id=secrets.token_hex(16), @@ -1174,17 +1217,47 @@ def slot_identity(config, group_index, slot, rollout_id, entry, def _group_slots(config, runtime_, group_index, rollout_id, entry, sampling_digest, policy_version, size): + from harborrl.rollout.generations import ACTIVE_GENERATION + context = ACTIVE_GENERATION.get() reward_profile = RewardProfile(**entry["reward_profile"]) harness_digest = digest(runtime_.profile) identities = [ slot_identity(config, group_index, index, rollout_id, entry, reward_profile.digest, sampling_digest, policy_version, harness_digest=harness_digest) + if context is None else slot_identity( + config, group_index, index, rollout_id, entry, + reward_profile.digest, sampling_digest, policy_version, + harness_digest=harness_digest, rollout_generation=context['generation']) for index in range(size) ] return GroupSlots(identities, max_attempts=config.max_attempts), reward_profile +def _sandbox_evidence(root): + from harborrl.trajectories.native import read_json + lifecycle_path = Path(root) / 'runner' / 'sandbox-lifecycle.json' + startup_path = Path(root) / 'runner' / 'sandbox-startup-failed.json' + lifecycle = read_json(lifecycle_path) if lifecycle_path.is_file() else {} + startup = read_json(startup_path) if startup_path.is_file() else {} + return lifecycle, startup + + +def _failure_stage(root, *, sandbox, lifecycle=None, startup=None): + if not sandbox: + return 'execute' + if lifecycle is None or startup is None: + lifecycle, startup = _sandbox_evidence(root) + if lifecycle.get('state') in {'pending', 'waiting', 'creating', 'creation_unknown', 'allocated'}: + return 'create' if lifecycle.get('state') != 'allocated' else 'startup' + startup_stage = str(startup.get('stage') or '') + if startup_stage in {'create', 'readiness'}: + return startup_stage + if lifecycle.get('state') in {'delete_failed', 'deleting'}: + return 'cleanup' + return 'execute' + + async def run_slot(config, runtime_, group_index, slot, rollout_id, entry, sampling_digest, policy_version): """Compatibility entry point for executing an individual group slot.""" @@ -1225,6 +1298,25 @@ async def _run_slot(config, runtime_, slots, slot, entry, reward_profile): cleanup.check() for attempt_index in range(slots.max_attempts): identity = slots.start(str(slot)) + from harborrl.rollout.generations import ACTIVE_GENERATION + context = ACTIVE_GENERATION.get() + if context is not None: + from harborrl.rollout.generations import reserve_generation_attempt + try: + reserve_generation_attempt(runtime_.run_root, identity, context) + except RetryableRolloutFailure: + slots.finish(str(slot), error='rollout attempt budget exhausted') + raise + ledger = getattr(runtime_, 'reliability', None) + if ledger is not None: + try: + ledger.reserve(identity.attempt_id, task_digest=identity.task_digest, + policy_version=identity.policy_version, retry_index=attempt_index) + except InfraBudgetExhausted as exc: + slots.finish(str(slot), error=f"{type(exc).__name__}: {exc}") + ledger.event(identity.attempt_id, 'failed', stage='attempt', kind='unknown', + decision='fail-seed', detail={'error': str(exc)}) + raise runner_host = overrides.get(entry["id"]) if config.runner_transport == 'local': runner_host = None @@ -1244,6 +1336,9 @@ async def _run_slot(config, runtime_, slots, slot, entry, reward_profile): admission = runtime_.sandbox_admission.lease(task_binding(config.sandbox, entry['path']), root) try: async with admission, runtime_.semaphore: + if ledger is not None: + ledger.event(identity.attempt_id, 'executing', stage='execute', + decision='start-attempt') cleanup.check() if auto: # Auto routing leases a gateway once this attempt actually @@ -1270,18 +1365,68 @@ async def _run_slot(config, runtime_, slots, slot, entry, reward_profile): runtime_.release_shard(shard) cleanup.observe(root) cleanup.check() + # Validate and settle the slot inside the attempt error boundary. + slots.finish(str(slot), ir) except CleanupRequiredError as exc: slots.finish(str(slot), error=f"{type(exc).__name__}: {exc}") + if ledger is not None: + ledger.event(identity.attempt_id, 'failed', stage='cleanup', + kind='cleanup-fault', decision='fail-seed') + _record_cleanup(ledger, identity, root) + raise + except asyncio.CancelledError: + slots.finish(str(slot), error='attempt cancelled') + if ledger is not None: + ledger.event(identity.attempt_id, 'failed', stage='cancel', kind='cancel-fault', + decision='cancelled') + _record_cleanup(ledger, identity, root) raise except (OSError, ValueError, RuntimeError, asyncio.TimeoutError) as exc: slots.finish(str(slot), error=f"{type(exc).__name__}: {exc}") + lifecycle, startup = _sandbox_evidence(root) if config.sandbox else ({}, {}) + if ledger is not None: + try: + kind, _, _ = ledger.observe_failure( + identity.attempt_id, + 'protocol' if isinstance(exc, ValueError) else _failure_stage( + root, sandbox=config.sandbox, lifecycle=lifecycle, startup=startup), + exc, + evidence={'cleanup_required': (root / 'cleanup-required.json').exists(), + 'sandbox_state': lifecycle.get('state'), + 'startup_stage': startup.get('stage')}, + sandbox_id=lifecycle.get('sandbox_id'), + retry_index=attempt_index) + finally: + _record_cleanup(ledger, identity, root) + from harborrl.rollout.harbor_job.reconcile import cleanup_debt + if config.sandbox and (cleanup_debt(root) or runtime_.sandbox_admission.blocked): + raise CleanupUnresolved('sandbox cleanup unresolved; automatic retry blocked') from exc + if isinstance(exc, (ValueError, InfraBudgetExhausted, CleanupUnresolved)): + raise cleanup.check() - if config.sandbox and ((root / 'cleanup-required.json').exists() or runtime_.sandbox_admission.blocked): - raise RuntimeError('sandbox cleanup unresolved; automatic retry blocked') from exc + if ledger is not None and kind == 'task-invalid': + raise ValueError('protocol or task lock invalid; infrastructure retry forbidden') from exc + if attempt_index + 1 < slots.max_attempts and ledger is not None: + await asyncio.sleep(ledger.policy.delay(attempt_index)) continue - slots.finish(str(slot), ir) + if ledger is not None: + lifecycle, _ = _sandbox_evidence(root) if config.sandbox else ({}, {}) + ledger.event(identity.attempt_id, 'completed', stage='execute', decision='complete', + sandbox_id=lifecycle.get('sandbox_id'), + detail={'cleanup_state': lifecycle.get('state', 'not_applicable')}) + _record_cleanup(ledger, identity, root) return ir - raise RuntimeError(f"native slot {slot} exhausted its retry budget") + raise RetryableRolloutFailure(f"native slot {slot} exhausted its retry budget") + + +def _record_cleanup(ledger, identity, root): + from harborrl.rollout.harbor_job.reconcile import cleanup_resolved + if cleanup_resolved(root): + receipt = read_json(Path(root) / 'cleanup-reconciliation.json') + ledger.event(identity.attempt_id, 'verified_absent', stage='reconcile', + sandbox_id=receipt.get('sandbox_id'), decision='release-slot', + detail={'receipt_sha256': digest(receipt), + 'elapsed_sec': receipt['elapsed_sec'], 'status': receipt['status']}) async def cancel_and_wait(tasks, result): @@ -1313,8 +1458,25 @@ async def run_group(config, runtime_, *, entry, group_index, rollout_id, try: # Cancel children once here, so gather cannot interrupt slower cleanup. return list(await asyncio.shield(result)) - except BaseException: + except BaseException as exc: await cancel_and_wait(tasks, result) + if isinstance(exc, RetryableRolloutFailure): + # A sibling may discover a protocol error or cleanup debt while + # settling. Its terminal failure must veto whole-batch recovery. + if getattr(getattr(runtime_, 'sandbox_admission', None), 'blocked', False): + raise CleanupUnresolved('sibling cleanup unresolved; rollout rerun forbidden') from exc + for task in tasks: + if not task.cancelled() and task.exception() is not None: + other = task.exception() + if not isinstance(other, RetryableRolloutFailure): + raise other + if isinstance(exc, RetryableRolloutFailure): + from harborrl.rollout.generations import ( + ACTIVE_GENERATION, + record_failed_group, + ) + if ACTIVE_GENERATION.get() is not None: + record_failed_group(runtime_.run_root, next(iter(slots.identities.values()))) raise finally: # Settlement (success or failure) is the shrink trigger: every lease diff --git a/harborrl/rollout/service.py b/harborrl/rollout/service.py index fc9b8d6ae..d7c0f367a 100644 --- a/harborrl/rollout/service.py +++ b/harborrl/rollout/service.py @@ -1,769 +1,794 @@ -"""RolloutService (P3): the manager-side HTTP control plane for rollout groups. - -First-phase contract: HTTP JSON, run-scoped tokens, idempotent group -submission. Bulky payloads (trajectory manifests, token ids, logprobs, loss -masks) live on the shared run directory; HTTP responses carry paths plus -SHA-256 digests, and the SlimeAdapter recomputes every digest before -converting anything into training samples. - -Rules that keep the lifecycle safe: -- same group id and same content -> the existing state, never a second run; -- same group id and different content -> rejected; -- after a timeout the client must query, never resubmit; -- a new policy version is admitted only after the whole serving pool is - healthy on it (drain first, publish second). -""" -from __future__ import annotations - -import asyncio -import concurrent.futures -import hashlib -import hmac -import json -import os -import secrets -import threading -import time -from dataclasses import dataclass, field -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import urlsplit - -from harborrl.rollout.exporters.native import export_group -from harborrl.rollout.runtime import run_group -from harborrl.trajectories.native import ( - canonical_sampling, - digest, - finite, - publish, - read_json, -) - -SERVICE_SCHEMA = "harborrl-rollout-service-v1" -GROUP_REQUEST_KEYS = {"group_id", "rollout_id", "group_index", "policy_version", - "task", "sampling", "slots"} -SAMPLING_KEYS = {"temperature", "top_p", "top_k", "max_new_tokens", "stop"} -TASK_ENTRY_KEYS = {"id", "revision", "path", "task_digest", "reward_profile"} -GROUP_DIR = "rollout-service/groups" - - -class ServiceError(Exception): - """Maps onto one HTTP status; carries a machine-readable code.""" - - def __init__(self, status, code, message): - super().__init__(message) - self.status, self.code = status, code - - -def validate_group_request(request): - if not isinstance(request, dict) or set(request) != GROUP_REQUEST_KEYS: - raise ServiceError(400, "invalid_request", - f"group request requires exactly {sorted(GROUP_REQUEST_KEYS)}") - for key in ("group_id", "policy_version"): - if not isinstance(request[key], str) or not request[key].strip(): - raise ServiceError(400, "invalid_request", f"{key} must be a nonempty string") - if request["group_id"] in (".", "..") or any(c in request["group_id"] for c in ("/", "\\")): - raise ServiceError(400, "invalid_request", "group_id must be one directory component") - for key in ("rollout_id", "group_index"): - if type(request[key]) is not int or request[key] < 0: - raise ServiceError(400, "invalid_request", f"{key} must be a nonnegative integer") - task = request["task"] - if not isinstance(task, dict) or set(task) != TASK_ENTRY_KEYS: - raise ServiceError(400, "invalid_request", - f"task requires exactly {sorted(TASK_ENTRY_KEYS)}") - if not isinstance(task["reward_profile"], dict): - raise ServiceError(400, "invalid_request", "task.reward_profile must be a mapping") - sampling = request["sampling"] - if not isinstance(sampling, dict) or set(sampling) != SAMPLING_KEYS: - raise ServiceError(400, "invalid_request", - f"sampling requires exactly {sorted(SAMPLING_KEYS)}") - if not finite(sampling["temperature"]) or not finite(sampling["top_p"]): - raise ServiceError(400, "invalid_request", "sampling probabilities must be finite") - if type(sampling["top_k"]) is not int: - raise ServiceError(400, "invalid_request", "sampling.top_k must be an integer") - if type(sampling["max_new_tokens"]) is not int or sampling["max_new_tokens"] < 1: - raise ServiceError(400, "invalid_request", "sampling.max_new_tokens must be positive") - if (not isinstance(sampling["stop"], list) - or any(not isinstance(stop, str) or not stop for stop in sampling["stop"])): - raise ServiceError(400, "invalid_request", "sampling.stop must be a string list") - slots = request["slots"] - if (not isinstance(slots, list) or len(slots) < 2 - or any(not isinstance(slot, dict) or set(slot) != {"slot_id"} - or not isinstance(slot["slot_id"], str) or not slot["slot_id"].strip() - for slot in slots)): - raise ServiceError(400, "invalid_request", - "slots must describe at least two unique slot ids") - if len({slot["slot_id"] for slot in slots}) != len(slots): - raise ServiceError(400, "invalid_request", "slot ids must be unique") - return request - - -def request_digest(request): - """Canonical digest of the full request content, group id included.""" - return digest(request) - - -def manifest_path_from(run_root, identity): - """Deterministic trajectory manifest path for one identity.""" - return Path(run_root) / "native-rollouts" / identity["group_id"] / \ - identity["attempt_id"] / "trajectory.v2.json" - - -def build_group_result(run_id, request, trajectories, *, runtime, export=None): - if len(trajectories) != len(request["slots"]): - raise ServiceError(500, "incomplete_group", - "executor returned a different slot count") - slots = [] - for descriptor, ir in zip(request["slots"], trajectories): - identity = ir["identity"] - path = runtime.manifest_path(identity) - payload = read_json(path) - seal = ir["trace_seal"] - slots.append({ - "slot_id": descriptor["slot_id"], - "trajectory_id": identity["trajectory_id"], - "attempt_id": identity["attempt_id"], - "manifest_path": str(path), - "manifest_sha256": digest(payload), - "finish_reason": ir["termination"], - "reward": ir["evaluation"]["training_reward"], - "policy_version": identity["policy_version"], - "task_digest": identity["task_digest"], - "harness_digest": identity["harness_digest"], - "sampling_digest": identity["sampling_digest"], - "readiness": ir["readiness"], - "integrity_errors": ir["integrity_errors"], - "trace_seal": {"status": seal["status"], "errors": seal["errors"], - "digest": digest(seal)}, - "verifier_digest": ir["evaluation"].get("source_result_digest"), - }) - result = { - "schema_version": SERVICE_SCHEMA, - "run_id": run_id, - "group_id": request["group_id"], - "rollout_id": request["rollout_id"], - "request_digest": request_digest(request), - "policy_version": request["policy_version"], - "status": "complete", - "slots": slots, - "completed_at": time.time(), - } - if export is not None: - result["group_export"] = export - return result - - -async def default_executor(config, runtime_, request): - """The production executor: the framework-free rollout core.""" - return await run_group( - config, runtime_, entry=request["task"], group_index=request["group_index"], - rollout_id=request["rollout_id"], sampling_digest=digest(canonical_sampling(request["sampling"])), - policy_version=request["policy_version"], group_size=len(request["slots"])) - - -@dataclass -class GroupState: - request: dict - request_sha: str - status: str = "queued" - result: dict = None - error: str = None - created_at: float = field(default_factory=time.time) - future: object = None - task: object = None - cancel_requested: bool = False - - def summary(self, *, include_result=True): - payload = {"group_id": self.request["group_id"], "status": self.status, - "request_digest": self.request_sha, - "created_at": self.created_at} - if self.error: - payload["error"] = self.error - if include_result and self.result is not None: - payload["result"] = self.result - return payload - - -@dataclass -class RunState: - run_id: str - manifest: dict - manifest_sha: str - token_digest: str - config: object = None - runtime: object = None - drained: bool = False - serving: str = None - groups: dict = field(default_factory=dict) - - -class RolloutService: - """Run registry plus a single-threaded asyncio executor for group work.""" - - def __init__(self, *, run_root, executor=None, runtime_factory=None, - token_file=None, group_wait_timeout=3600.0, poll_interval=0.05, - allow_synthetic=False, cleanup_timeout=None): - if cleanup_timeout is not None and (not finite(cleanup_timeout) or cleanup_timeout <= 0): - raise ValueError("cleanup_timeout must be positive and finite") - self.run_root = Path(run_root).resolve() - self.executor = executor or default_executor - self.runtime_factory = runtime_factory - self.allow_synthetic = allow_synthetic - self.token = None - if token_file is not None: - token = Path(token_file).read_text().strip() - if not token: - raise ServiceError(500, "invalid_token_file", "run token file is empty") - self.token = token - self.group_wait_timeout = group_wait_timeout - self.poll_interval = poll_interval - self.runs = {} - self.lock = threading.RLock() - self._close_lock = threading.Lock() - self._closing = self._closed = False - self.cleanup_timeout = cleanup_timeout - self._store_lock = self._lock_run_directory() - self.loop = asyncio.new_event_loop() - self.thread = threading.Thread(target=self._serve_loop, - name="harborrl-rollout-service", daemon=True) - try: - self.thread.start() - except RuntimeError: - self.loop.close() - self._store_lock.close() - raise - - def _lock_run_directory(self): - directory = self.run_root / "rollout-service" - directory.mkdir(parents=True, exist_ok=True) - stream = (directory / "service.lock").open("a+b") - try: - if os.name == "posix": - import fcntl - fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - else: - import msvcrt - stream.seek(0) - if not stream.read(1): - stream.write(b"0") - stream.flush() - stream.seek(0) - msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) - except OSError as exc: - stream.close() - raise ServiceError(409, "run_directory_busy", "another service owns this run directory") from exc - return stream - - def _serve_loop(self): - asyncio.set_event_loop(self.loop) - self.loop.run_forever() - - def _cleanup_budget(self): - if self.cleanup_timeout is not None: - return self.cleanup_timeout - # Runner cancellation allows 120s, or the configured Sandbox deletion - # deadline plus 15s. The service must not cut that lifecycle to 30s. - budgets = [120.0] - with self.lock: - states = list(self.runs.values()) - for state in states: - sandbox = getattr(state.config, "sandbox", None) - if sandbox: - budgets.append(float(sandbox["cleanup_timeout_s"]) + 15) - return max(budgets) + 30 - - def _ensure_open(self): - if self._closing: - raise ServiceError(503, "service_closing", "rollout service is closing") - - def _shutdown_failed(self, error): - marker = self.run_root / "native-rollouts" / "cleanup-required.json" - if not marker.exists(): - publish(marker, {"reason": "RolloutService shutdown incomplete", - "error": str(error), - "groups": {state.run_id: {key: group.status for key, group in state.groups.items()} - for state in self.runs.values()}}) - - async def _shutdown_loop_resources(self): - await self.loop.shutdown_asyncgens() - await self.loop.shutdown_default_executor() - - def close(self): - if threading.current_thread() is self.thread: - raise RuntimeError("close the rollout service outside its executor loop") - with self._close_lock: - if self._closed: - return - with self.lock: - self._closing = True - states = list(self.runs.values()) - for state in states: - state.drained = True - groups = [group for state in states for group in state.groups.values()] - try: - self._cancel_groups(groups) - for state in states: - if state.runtime is None: - continue - registry = getattr(state.runtime, "registry", None) - if registry is not None: - registry.drain(float(getattr(state.config, "drain_timeout", 30))) - close = getattr(state.runtime, "close", None) - if close is not None: - close() - future = asyncio.run_coroutine_threadsafe(self._shutdown_loop_resources(), self.loop) - future.result(timeout=self._cleanup_budget()) - self.loop.call_soon_threadsafe(self.loop.stop) - self.thread.join(5) - if self.thread.is_alive(): - raise ServiceError(409, "shutdown_timeout", "rollout executor thread has not stopped") - self.loop.close() - self._store_lock.close() - self._closed = True - except Exception as exc: - # Keep the executor alive to finish pending cleanup; never claim - # that a deadline or a cancelled wrapper Future proves deletion. - self._shutdown_failed(exc) - raise - - # -- run lifecycle ---------------------------------------------------- - - def _token_digest(self, token): - return hashlib.sha256(token.encode()).hexdigest() - - def register_run(self, run_id, manifest, *, token=None): - if (not isinstance(run_id, str) or not run_id.strip() or run_id in (".", "..") - or any(c in run_id for c in ("/", "\\"))): - raise ServiceError(400, "invalid_request", "run id must be one directory component") - if not isinstance(manifest, dict) or not manifest: - raise ServiceError(400, "invalid_request", "manifest must be a nonempty mapping") - if manifest.get("run_id", run_id) != run_id: - raise ServiceError(400, "invalid_request", "manifest run id must match the path") - manifest_sha = digest(manifest) - with self.lock: - self._ensure_open() - existing = self.runs.get(run_id) - if existing is not None: - if existing.manifest_sha != manifest_sha: - raise ServiceError(409, "conflict", - "run id already registered with a different manifest") - return {"run_id": run_id, "state": "registered", "existed": True} - if self.token is not None and token != self.token: - raise ServiceError(401, "unauthorized", "invalid manager run token") - manifest_path = self.run_root / "rollout-service/runs" / run_id / "manifest.json" - existed = manifest_path.exists() - if existed and digest(read_json(manifest_path)) != manifest_sha: - raise ServiceError(409, "conflict", "persisted run manifest differs from registration") - groups = self._restore_groups(run_id) - publish(manifest_path, manifest) - generated = token is None - if generated: - token = secrets.token_urlsafe(32) - self.runs[run_id] = RunState(run_id=run_id, manifest=manifest, - manifest_sha=manifest_sha, - token_digest=self._token_digest(token), groups=groups, - drained=any(group.status == "unknown" for group in groups.values())) - return {"run_id": run_id, "state": "registered", "existed": existed, - "recovered_groups": len(groups), **({"run_token": token} if generated else {})} - - def authenticate(self, run_id, token): - with self.lock: - state = self.runs.get(run_id) - if state is None: - raise ServiceError(404, "not_found", f"unknown run: {run_id}") - if not isinstance(token, str) or not token or not hmac.compare_digest( - state.token_digest, self._token_digest(token)): - raise ServiceError(401, "unauthorized", "invalid run token") - return state - - def _run(self, run_id): - state = self.runs.get(run_id) - if state is None: - raise ServiceError(404, "not_found", f"unknown run: {run_id}") - return state - - def attach_runtime(self, run_id, config, runtime): - """Bind the rollout runtime that executes this run's groups.""" - with self.lock: - self._ensure_open() - state = self._run(run_id) - state.config, state.runtime = config, runtime - return {"run_id": run_id, "state": "attached"} - - def announce_serving(self, run_id, router_url): - parts = urlsplit(router_url or "") - if (parts.scheme not in ("http", "https") or not parts.hostname - or parts.username or parts.password or parts.query - or parts.fragment or parts.path not in ("", "/")): - raise ServiceError(400, "invalid_request", "router_url must be a plain origin") - with self.lock: - self._ensure_open() - state = self._run(run_id) - state.serving = f"{parts.scheme}://{parts.netloc}".rstrip("/") - if state.runtime is None and self.runtime_factory is not None: - runtime = self.runtime_factory(run_id, state.serving) - state.runtime = runtime - if state.config is None: - # The factory-built runtime carries its own config; the - # executor needs both for group admission. - state.config = getattr(runtime, "config", None) - return {"run_id": run_id, "router_url": state.serving, - "runtime": "attached" if state.runtime is not None else "pending"} - - # -- policy lifecycle (§7) --------------------------------------------- - - def activate_policy(self, run_id, states, expected): - from harborrl.platform.policy_pool import validate_pool - - with self.lock: - self._ensure_open() - state = self._run(run_id) - if state.runtime is None: - raise ServiceError(409, "admission_closed", "run has no serving runtime yet") - try: - version = validate_pool(states, str(expected)) - backend = getattr(state.runtime, 'backend', None) - if backend is not None: - live_states = backend.pool_states() - validate_pool(live_states, version) - if {item['endpoint'] for item in live_states} != {item['endpoint'] for item in states}: - raise ValueError('manager and GPU disagree on serving engine membership') - states = live_states - except (RuntimeError, TypeError, ValueError) as exc: - raise ServiceError(409, "pool_invalid", str(exc)) from exc - with self.lock: - # Pool probes above can race a shutdown. Do not reopen generation - # admission after close has frozen the service. - self._ensure_open() - registry = state.runtime.registry - registry.drain(float(getattr(state.config, "drain_timeout", 30))) - registry.publish_version(states, version) - # Mirror the admitted version into shared storage. - payload = {"weight_version": version, "engines": states, "timestamp": time.time()} - temp = self.run_root / "policy-pool.tmp" - temp.write_text(json.dumps(payload) + "\n") - temp.replace(self.run_root / "policy-pool.json") - return {"run_id": run_id, "policy_version": version, "admission": "open"} - - # -- group lifecycle ---------------------------------------------------- - - def _group_dir(self, run_id, group_id): - return self.run_root / GROUP_DIR / run_id / group_id - - def _restore_groups(self, run_id): - """Restore durable outcomes, never resume an unowned Runner or resample.""" - groups = {} - directory = self.run_root / GROUP_DIR / run_id - for root in sorted(directory.glob("*")): - if not root.is_dir(): - continue - request_path = root / "request.json" - if not request_path.exists(): - if any((root / name).exists() for name in ("running.json", "result.json", "failed.json", "cancelled.json", "unknown.json")): - raise ServiceError(500, "invalid_persisted_group", f"missing request: {root.name}") - continue - try: - request = validate_group_request(read_json(request_path)) - if request["group_id"] != root.name: - raise ValueError("group directory differs from request") - sha = request_digest(request) - terminal = [(name, status) for name, status in ( - ("result.json", "complete"), ("failed.json", "failed"), ("cancelled.json", "cancelled")) - if (root / name).exists()] - if len(terminal) > 1: - raise ValueError("conflicting terminal group records") - if terminal: - name, status = terminal[0] - record = read_json(root / name) - else: - status = "unknown" - record_path = root / "unknown.json" if (root / "unknown.json").exists() else root / "running.json" - record = read_json(record_path) if record_path.exists() else { - "group_id": root.name, "request_digest": sha, "created_at": time.time()} - if not isinstance(record, dict): - raise TypeError("persisted group record must be a mapping") - if record.get("group_id") != root.name or record.get("request_digest") != sha: - raise ValueError("persisted group does not match its request") - if terminal and record.get("status") != status: - raise ValueError("terminal status differs from its record") - if status == "complete" and ( - record.get("run_id") != run_id or record.get("schema_version") != SERVICE_SCHEMA - or record.get("policy_version") != request["policy_version"] - or [slot["slot_id"] for slot in record["slots"]] != [slot["slot_id"] for slot in request["slots"]] - ): - raise ValueError("persisted result identity differs from its request") - created_at = record.get("created_at") - if created_at is None and (root / "running.json").exists(): - running = read_json(root / "running.json") - if (not isinstance(running, dict) or running.get("request_digest") != sha - or running.get("group_id") != root.name): - raise ValueError("running record differs from its request") - created_at = running["created_at"] - group = GroupState(request, sha, status=status, - result=record if status == "complete" else None, - error=record.get("error"), created_at=created_at or 0) - if status == "unknown": - group.error = "Service restarted before durable group completion; confirm Runner cleanup and use a new run" - publish(root / "unknown.json", group.summary(include_result=False)) - marker = self.run_root / "native-rollouts/cleanup-required.json" - if not marker.exists(): - publish(marker, {"run_id": run_id, "group_id": root.name, - "reason": "Interrupted group has unknown Runner cleanup status"}) - groups[root.name] = group - except (OSError, ValueError, KeyError, TypeError) as exc: - raise ServiceError(500, "invalid_persisted_group", f"cannot restore {root.name}: {exc}") from exc - return groups - - def submit_group(self, run_id, request, *, wait=True): - request = validate_group_request(request) - sha = request_digest(request) - with self.lock: - state = self._run(run_id) - existing = state.groups.get(request["group_id"]) - if existing is not None: - if existing.request_sha != sha: - raise ServiceError(409, "conflict", - "group id already submitted with different content") - group = existing - else: - self._ensure_open() - if state.drained: - raise ServiceError(409, "admission_closed", "run is draining") - if state.runtime is None or state.config is None: - raise ServiceError(409, "admission_closed", - "run has no rollout runtime attached") - registry = getattr(state.runtime, "registry", None) - version = getattr(registry, "version", None) if registry is not None else None - accepting = getattr(registry, "accepting", True) if registry is not None else False - if not accepting or version != request["policy_version"]: - raise ServiceError( - 409, "stale_policy", - f"policy {request['policy_version']!r} is not the admitted version " - f"({version!r}, accepting={accepting}); activate first") - group = GroupState(request=request, request_sha=sha) - state.groups[request["group_id"]] = group - future = asyncio.run_coroutine_threadsafe( - self._execute(state, group), self.loop) - group.future = future - if wait: - return self._wait_group(run_id, group) - return group.summary(include_result=False) - - def _wait_group(self, run_id, group): - deadline = time.monotonic() + self.group_wait_timeout - while group.status in ("queued", "running"): - if time.monotonic() >= deadline: - return {**group.summary(include_result=False), - "hint": "query GET /groups/{group_id}; do not resubmit"} - time.sleep(self.poll_interval) - return group.summary() - - async def _execute(self, state, group): - # Immutable state records: each transition gets its own file, and - # publish() refuses to rewrite history. - group.task = asyncio.current_task() - request = group.request - directory = self._group_dir(state.run_id, request["group_id"]) - try: - publish(directory / "request.json", request) - if group.cancel_requested: - raise asyncio.CancelledError - group.status = "running" - publish(directory / "running.json", group.summary(include_result=False)) - trajectories = await self.executor(state.config, state.runtime, request) - export = export_group( - trajectories, len(trajectories), - allow_synthetic=self.allow_synthetic) - export_path = directory / "group-export.json" - publish(export_path, export) - result = build_group_result( - state.run_id, request, trajectories, runtime=state.runtime, - export={"path": str(export_path), "sha256": digest(export)}) - publish(directory / "result.json", result) - group.result = result - group.status = "complete" - except asyncio.CancelledError: - group.status = "cancelled" - publish(directory / "cancelled.json", group.summary(include_result=False)) - raise - except Exception as exc: # noqa: BLE001 — any executor failure is - # recorded as a failed group instead of killing the service - group.status = "failed" - group.error = f"{type(exc).__name__}: {exc}" - publish(directory / "failed.json", group.summary(include_result=False)) - - def group_status(self, run_id, group_id): - with self.lock: - state = self._run(run_id) - group = state.groups.get(group_id) - if group is None: - raise ServiceError(404, "not_found", f"unknown group: {group_id}") - return group.summary() - - def cancel_group(self, run_id, group_id): - with self.lock: - state = self._run(run_id) - group = state.groups.get(group_id) - if group is None: - raise ServiceError(404, "not_found", f"unknown group: {group_id}") - if group.status == "unknown": - raise ServiceError(409, "cleanup_required", "interrupted group has no owned Task; inspect Runner cleanup") - self._cancel_groups([group]) - return group.summary() - - def drain_run(self, run_id): - with self.lock: - state = self._run(run_id) - state.drained = True - runtime = state.runtime - if runtime is not None: - registry = getattr(runtime, "registry", None) - if registry is not None: - timeout = float(getattr(state.config, "drain_timeout", 30)) - try: - registry.drain(timeout) - except TimeoutError as exc: - raise ServiceError(409, "drain_timeout", - f"generation still in flight: {exc}") from exc - return {"run_id": run_id, "state": "drained"} - - def cancel_run(self, run_id): - with self.lock: - state = self._run(run_id) - state.drained = True - groups = list(state.groups.values()) - if any(group.status == "unknown" for group in groups): - raise ServiceError(409, "cleanup_required", "interrupted groups require external cleanup confirmation") - self._cancel_groups(groups) - return {"run_id": run_id, "state": "cancelled", - "groups": {group.request["group_id"]: group.status for group in groups}} - - async def _cancel_and_wait(self, groups): - for group in groups: - if not group.cancel_requested and group.future is not None and not group.future.done(): - group.cancel_requested = True - if group.task is not None: - group.task.cancel() - # Do not cancel the run_coroutine_threadsafe Future: that wrapper can - # become done before the actual Task's asynchronous finally completes. - pending = [asyncio.wrap_future(group.future) for group in groups if group.future is not None] - results = await asyncio.gather(*pending, return_exceptions=True) - for result in results: - if isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError): - raise ServiceError(500, "cleanup_failed", f"group completion failed: {result}") - - def _cancel_groups(self, groups): - if not any(group.future is not None for group in groups): - return - if threading.current_thread() is self.thread: - raise RuntimeError("cancel rollout groups outside their executor loop") - joined = asyncio.run_coroutine_threadsafe(self._cancel_and_wait(groups), self.loop) - try: - joined.result(timeout=self._cleanup_budget()) - except concurrent.futures.TimeoutError as exc: - # Leave the waiter and group cleanup running; a second cancel would - # interrupt their finally blocks. Retrying close may join them later. - raise ServiceError(409, "cleanup_timeout", "rollout groups are still cleaning up") from exc - - -def make_control_server(service, host="127.0.0.1", port=0, *, max_body_bytes=8 * 1024 * 1024): - """Bounded stdlib HTTP transport for the control plane.""" - - class Handler(BaseHTTPRequestHandler): - def setup(self): - super().setup() - self.connection.settimeout(120) - - def log_message(self, *args): - pass - - def reply(self, status, payload): - body = json.dumps(payload).encode() - self.send_response(status) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def token(self): - token = self.headers.get("x-api-key", "") - auth = self.headers.get("Authorization", "") - if auth: - if not auth.startswith("Bearer ") or token: - raise ServiceError(400, "invalid_request", "ambiguous authentication") - token = auth[7:] - return token - - def read_json(self): - if self.headers.get("Transfer-Encoding"): - raise ServiceError(400, "invalid_request", "chunked bodies are not supported") - size = int(self.headers.get("Content-Length", "0")) - if size <= 0 or size > max_body_bytes: - raise ServiceError(400, "invalid_request", "invalid request body size") - return json.loads(self.rfile.read(size)) - - def dispatch(self, method): - parts = [part for part in urlsplit(self.path).path.split("/") if part] - try: - payload = self.route(method, parts) - except ServiceError as exc: - self.reply(exc.status, {"error": {"type": exc.code, "message": str(exc)}}) - except (ValueError, TypeError, KeyError, OSError, json.JSONDecodeError) as exc: - self.reply(400, {"error": {"type": "invalid_request", - "message": f"{type(exc).__name__}: {exc}"}}) - else: - self.reply(200, payload) - - def route(self, method, parts): - if method == "GET" and parts == ["healthz"]: - return {"ok": True, "service": SERVICE_SCHEMA} - if method == "GET" and parts == ["readyz"]: - with service.lock: - attached = sum(1 for state in service.runs.values() - if state.runtime is not None) - return {"ok": True, "runs": len(service.runs), "attached_runs": attached} - if len(parts) < 2 or parts[0] != "runs": - raise ServiceError(404, "not_found", "unsupported endpoint") - run_id = parts[1] - if len(parts) == 3 and method == "POST" and parts[2] == "register": - body = self.read_json() - if not isinstance(body, dict) or set(body) != {"manifest"}: - raise ServiceError(400, "invalid_request", "body must be {manifest}") - return service.register_run(run_id, body["manifest"], token=self.token()) - service.authenticate(run_id, self.token()) - if len(parts) == 3 and method == "POST" and parts[2] == "groups": - return service.submit_group(run_id, self.read_json()) - if (len(parts) == 4 and parts[2] == "groups" - and method == "GET"): - return service.group_status(run_id, parts[3]) - if (len(parts) == 5 and parts[2] == "groups" and parts[4] == "cancel" - and method == "POST"): - return service.cancel_group(run_id, parts[3]) - if len(parts) == 4 and method == "POST" and parts[2] == "policy" \ - and parts[3] == "activate": - body = self.read_json() - if not isinstance(body, dict) or set(body) != {"states", "expected"}: - raise ServiceError(400, "invalid_request", - "body must be {states, expected}") - return service.activate_policy(run_id, body["states"], body["expected"]) - if len(parts) == 4 and method == "POST" and parts[2] == "serving" \ - and parts[3] == "announce": - body = self.read_json() - if not isinstance(body, dict) or set(body) != {"router_url"}: - raise ServiceError(400, "invalid_request", "body must be {router_url}") - return service.announce_serving(run_id, body["router_url"]) - if len(parts) == 3 and method == "POST" and parts[2] == "drain": - return service.drain_run(run_id) - if len(parts) == 3 and method == "POST" and parts[2] == "cancel": - return service.cancel_run(run_id) - raise ServiceError(404, "not_found", "unsupported endpoint") - - def do_GET(self): - self.dispatch("GET") - - def do_POST(self): - self.dispatch("POST") - - server = ThreadingHTTPServer((host, port), Handler) - server.daemon_threads = True - return server +"""RolloutService (P3): the manager-side HTTP control plane for rollout groups. + +First-phase contract: HTTP JSON, run-scoped tokens, idempotent group +submission. Bulky payloads (trajectory manifests, token ids, logprobs, loss +masks) live on the shared run directory; HTTP responses carry paths plus +SHA-256 digests, and the SlimeAdapter recomputes every digest before +converting anything into training samples. + +Rules that keep the lifecycle safe: +- same group id and same content -> the existing state, never a second run; +- same group id and different content -> rejected; +- after a timeout the client must query, never resubmit; +- a new policy version is admitted only after the whole serving pool is + healthy on it (drain first, publish second). +""" +from __future__ import annotations + +import asyncio +import concurrent.futures +import hashlib +import hmac +import json +import os +import secrets +import threading +import time +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlsplit + +from harborrl.rollout.exporters.native import export_group +from harborrl.rollout.runtime import run_group +from harborrl.trajectories.native import ( + canonical_sampling, + digest, + finite, + publish, + read_json, +) + +SERVICE_SCHEMA = "harborrl-rollout-service-v1" +GROUP_REQUEST_KEYS = {"group_id", "rollout_id", "group_index", "policy_version", + "task", "sampling", "slots"} +SAMPLING_KEYS = {"temperature", "top_p", "top_k", "max_new_tokens", "stop"} +TASK_ENTRY_KEYS = {"id", "revision", "path", "task_digest", "reward_profile"} +GROUP_DIR = "rollout-service/groups" + + +class ServiceError(Exception): + """Maps onto one HTTP status; carries a machine-readable code.""" + + def __init__(self, status, code, message): + super().__init__(message) + self.status, self.code = status, code + + +def validate_group_request(request): + if (not isinstance(request, dict) or not GROUP_REQUEST_KEYS <= set(request) + or set(request) - GROUP_REQUEST_KEYS - {'rollout_generation'}): + raise ServiceError(400, "invalid_request", + f"group request requires exactly {sorted(GROUP_REQUEST_KEYS)}") + for key in ("group_id", "policy_version"): + if not isinstance(request[key], str) or not request[key].strip(): + raise ServiceError(400, "invalid_request", f"{key} must be a nonempty string") + if request["group_id"] in (".", "..") or any(c in request["group_id"] for c in ("/", "\\")): + raise ServiceError(400, "invalid_request", "group_id must be one directory component") + for key in ("rollout_id", "group_index"): + if type(request[key]) is not int or request[key] < 0: + raise ServiceError(400, "invalid_request", f"{key} must be a nonnegative integer") + if 'rollout_generation' in request: + from harborrl.rollout.generations import generation_group_id + generation = request['rollout_generation'] + if type(generation) is not int or generation < 0 or request['group_id'] != generation_group_id( + request['rollout_id'], generation, request['group_index']): + raise ServiceError(400, 'invalid_request', 'invalid rollout generation identity') + task = request["task"] + if not isinstance(task, dict) or set(task) != TASK_ENTRY_KEYS: + raise ServiceError(400, "invalid_request", + f"task requires exactly {sorted(TASK_ENTRY_KEYS)}") + if not isinstance(task["reward_profile"], dict): + raise ServiceError(400, "invalid_request", "task.reward_profile must be a mapping") + sampling = request["sampling"] + if not isinstance(sampling, dict) or set(sampling) != SAMPLING_KEYS: + raise ServiceError(400, "invalid_request", + f"sampling requires exactly {sorted(SAMPLING_KEYS)}") + if not finite(sampling["temperature"]) or not finite(sampling["top_p"]): + raise ServiceError(400, "invalid_request", "sampling probabilities must be finite") + if type(sampling["top_k"]) is not int: + raise ServiceError(400, "invalid_request", "sampling.top_k must be an integer") + if type(sampling["max_new_tokens"]) is not int or sampling["max_new_tokens"] < 1: + raise ServiceError(400, "invalid_request", "sampling.max_new_tokens must be positive") + if (not isinstance(sampling["stop"], list) + or any(not isinstance(stop, str) or not stop for stop in sampling["stop"])): + raise ServiceError(400, "invalid_request", "sampling.stop must be a string list") + slots = request["slots"] + if (not isinstance(slots, list) or len(slots) < 2 + or any(not isinstance(slot, dict) or set(slot) != {"slot_id"} + or not isinstance(slot["slot_id"], str) or not slot["slot_id"].strip() + for slot in slots)): + raise ServiceError(400, "invalid_request", + "slots must describe at least two unique slot ids") + if len({slot["slot_id"] for slot in slots}) != len(slots): + raise ServiceError(400, "invalid_request", "slot ids must be unique") + return request + + +def request_digest(request): + """Canonical digest of the full request content, group id included.""" + return digest(request) + + +def manifest_path_from(run_root, identity): + """Deterministic trajectory manifest path for one identity.""" + return Path(run_root) / "native-rollouts" / identity["group_id"] / \ + identity["attempt_id"] / "trajectory.v2.json" + + +def build_group_result(run_id, request, trajectories, *, runtime, export=None): + if len(trajectories) != len(request["slots"]): + raise ServiceError(500, "incomplete_group", + "executor returned a different slot count") + slots = [] + for descriptor, ir in zip(request["slots"], trajectories): + identity = ir["identity"] + path = runtime.manifest_path(identity) + payload = read_json(path) + seal = ir["trace_seal"] + slots.append({ + "slot_id": descriptor["slot_id"], + "trajectory_id": identity["trajectory_id"], + "attempt_id": identity["attempt_id"], + "manifest_path": str(path), + "manifest_sha256": digest(payload), + "finish_reason": ir["termination"], + "reward": ir["evaluation"]["training_reward"], + "policy_version": identity["policy_version"], + "task_digest": identity["task_digest"], + "harness_digest": identity["harness_digest"], + "sampling_digest": identity["sampling_digest"], + "readiness": ir["readiness"], + "integrity_errors": ir["integrity_errors"], + "trace_seal": {"status": seal["status"], "errors": seal["errors"], + "digest": digest(seal)}, + "verifier_digest": ir["evaluation"].get("source_result_digest"), + }) + result = { + "schema_version": SERVICE_SCHEMA, + "run_id": run_id, + "group_id": request["group_id"], + "rollout_id": request["rollout_id"], + "request_digest": request_digest(request), + "policy_version": request["policy_version"], + "status": "complete", + "slots": slots, + "completed_at": time.time(), + } + if export is not None: + result["group_export"] = export + return result + + +async def default_executor(config, runtime_, request): + """The production executor: the framework-free rollout core.""" + from harborrl.rollout.generations import ACTIVE_GENERATION, GenerationPolicy + token = None + if 'rollout_generation' in request: + policy = GenerationPolicy(**(config.generation_policy or {})) + token = ACTIVE_GENERATION.set({'generation': request['rollout_generation'], + 'policy_version': request['policy_version'], + 'max_attempts': policy.max_attempts_per_rollout, + 'max_failed_groups': policy.max_failed_groups_per_rollout}) + try: + return await run_group( + config, runtime_, entry=request["task"], group_index=request["group_index"], + rollout_id=request["rollout_id"], sampling_digest=digest(canonical_sampling(request["sampling"])), + policy_version=request["policy_version"], group_size=len(request["slots"])) + finally: + if token is not None: + ACTIVE_GENERATION.reset(token) + + +@dataclass +class GroupState: + request: dict + request_sha: str + status: str = "queued" + result: dict = None + error: str = None + failure_code: str = None + created_at: float = field(default_factory=time.time) + future: object = None + task: object = None + cancel_requested: bool = False + + def summary(self, *, include_result=True): + payload = {"group_id": self.request["group_id"], "status": self.status, + "request_digest": self.request_sha, + "created_at": self.created_at} + if self.error: + payload["error"] = self.error + if self.failure_code: + payload['failure_code'] = self.failure_code + if include_result and self.result is not None: + payload["result"] = self.result + return payload + + +@dataclass +class RunState: + run_id: str + manifest: dict + manifest_sha: str + token_digest: str + config: object = None + runtime: object = None + drained: bool = False + serving: str = None + groups: dict = field(default_factory=dict) + + +class RolloutService: + """Run registry plus a single-threaded asyncio executor for group work.""" + + def __init__(self, *, run_root, executor=None, runtime_factory=None, + token_file=None, group_wait_timeout=3600.0, poll_interval=0.05, + allow_synthetic=False, cleanup_timeout=None): + if cleanup_timeout is not None and (not finite(cleanup_timeout) or cleanup_timeout <= 0): + raise ValueError("cleanup_timeout must be positive and finite") + self.run_root = Path(run_root).resolve() + self.executor = executor or default_executor + self.runtime_factory = runtime_factory + self.allow_synthetic = allow_synthetic + self.token = None + if token_file is not None: + token = Path(token_file).read_text().strip() + if not token: + raise ServiceError(500, "invalid_token_file", "run token file is empty") + self.token = token + self.group_wait_timeout = group_wait_timeout + self.poll_interval = poll_interval + self.runs = {} + self.lock = threading.RLock() + self._close_lock = threading.Lock() + self._closing = self._closed = False + self.cleanup_timeout = cleanup_timeout + self._store_lock = self._lock_run_directory() + self.loop = asyncio.new_event_loop() + self.thread = threading.Thread(target=self._serve_loop, + name="harborrl-rollout-service", daemon=True) + try: + self.thread.start() + except RuntimeError: + self.loop.close() + self._store_lock.close() + raise + + def _lock_run_directory(self): + directory = self.run_root / "rollout-service" + directory.mkdir(parents=True, exist_ok=True) + stream = (directory / "service.lock").open("a+b") + try: + if os.name == "posix": + import fcntl + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + else: + import msvcrt + stream.seek(0) + if not stream.read(1): + stream.write(b"0") + stream.flush() + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + except OSError as exc: + stream.close() + raise ServiceError(409, "run_directory_busy", "another service owns this run directory") from exc + return stream + + def _serve_loop(self): + asyncio.set_event_loop(self.loop) + self.loop.run_forever() + + def _cleanup_budget(self): + if self.cleanup_timeout is not None: + return self.cleanup_timeout + # Runner cancellation allows 120s, or the configured Sandbox deletion + # deadline plus 15s. The service must not cut that lifecycle to 30s. + budgets = [120.0] + with self.lock: + states = list(self.runs.values()) + for state in states: + sandbox = getattr(state.config, "sandbox", None) + if sandbox: + budgets.append(float(sandbox["cleanup_timeout_s"]) + 15) + return max(budgets) + 30 + + def _ensure_open(self): + if self._closing: + raise ServiceError(503, "service_closing", "rollout service is closing") + + def _shutdown_failed(self, error): + marker = self.run_root / "native-rollouts" / "cleanup-required.json" + if not marker.exists(): + publish(marker, {"reason": "RolloutService shutdown incomplete", + "error": str(error), + "groups": {state.run_id: {key: group.status for key, group in state.groups.items()} + for state in self.runs.values()}}) + + async def _shutdown_loop_resources(self): + await self.loop.shutdown_asyncgens() + await self.loop.shutdown_default_executor() + + def close(self): + if threading.current_thread() is self.thread: + raise RuntimeError("close the rollout service outside its executor loop") + with self._close_lock: + if self._closed: + return + with self.lock: + self._closing = True + states = list(self.runs.values()) + for state in states: + state.drained = True + groups = [group for state in states for group in state.groups.values()] + try: + self._cancel_groups(groups) + for state in states: + if state.runtime is None: + continue + registry = getattr(state.runtime, "registry", None) + if registry is not None: + registry.drain(float(getattr(state.config, "drain_timeout", 30))) + close = getattr(state.runtime, "close", None) + if close is not None: + close() + future = asyncio.run_coroutine_threadsafe(self._shutdown_loop_resources(), self.loop) + future.result(timeout=self._cleanup_budget()) + self.loop.call_soon_threadsafe(self.loop.stop) + self.thread.join(5) + if self.thread.is_alive(): + raise ServiceError(409, "shutdown_timeout", "rollout executor thread has not stopped") + self.loop.close() + self._store_lock.close() + self._closed = True + except Exception as exc: + # Keep the executor alive to finish pending cleanup; never claim + # that a deadline or a cancelled wrapper Future proves deletion. + self._shutdown_failed(exc) + raise + + # -- run lifecycle ---------------------------------------------------- + + def _token_digest(self, token): + return hashlib.sha256(token.encode()).hexdigest() + + def register_run(self, run_id, manifest, *, token=None): + if (not isinstance(run_id, str) or not run_id.strip() or run_id in (".", "..") + or any(c in run_id for c in ("/", "\\"))): + raise ServiceError(400, "invalid_request", "run id must be one directory component") + if not isinstance(manifest, dict) or not manifest: + raise ServiceError(400, "invalid_request", "manifest must be a nonempty mapping") + if manifest.get("run_id", run_id) != run_id: + raise ServiceError(400, "invalid_request", "manifest run id must match the path") + manifest_sha = digest(manifest) + with self.lock: + self._ensure_open() + existing = self.runs.get(run_id) + if existing is not None: + if existing.manifest_sha != manifest_sha: + raise ServiceError(409, "conflict", + "run id already registered with a different manifest") + return {"run_id": run_id, "state": "registered", "existed": True} + if self.token is not None and token != self.token: + raise ServiceError(401, "unauthorized", "invalid manager run token") + manifest_path = self.run_root / "rollout-service/runs" / run_id / "manifest.json" + existed = manifest_path.exists() + if existed and digest(read_json(manifest_path)) != manifest_sha: + raise ServiceError(409, "conflict", "persisted run manifest differs from registration") + groups = self._restore_groups(run_id) + publish(manifest_path, manifest) + generated = token is None + if generated: + token = secrets.token_urlsafe(32) + self.runs[run_id] = RunState(run_id=run_id, manifest=manifest, + manifest_sha=manifest_sha, + token_digest=self._token_digest(token), groups=groups, + drained=any(group.status == "unknown" for group in groups.values())) + return {"run_id": run_id, "state": "registered", "existed": existed, + "recovered_groups": len(groups), **({"run_token": token} if generated else {})} + + def authenticate(self, run_id, token): + with self.lock: + state = self.runs.get(run_id) + if state is None: + raise ServiceError(404, "not_found", f"unknown run: {run_id}") + if not isinstance(token, str) or not token or not hmac.compare_digest( + state.token_digest, self._token_digest(token)): + raise ServiceError(401, "unauthorized", "invalid run token") + return state + + def _run(self, run_id): + state = self.runs.get(run_id) + if state is None: + raise ServiceError(404, "not_found", f"unknown run: {run_id}") + return state + + def attach_runtime(self, run_id, config, runtime): + """Bind the rollout runtime that executes this run's groups.""" + with self.lock: + self._ensure_open() + state = self._run(run_id) + state.config, state.runtime = config, runtime + return {"run_id": run_id, "state": "attached"} + + def announce_serving(self, run_id, router_url): + parts = urlsplit(router_url or "") + if (parts.scheme not in ("http", "https") or not parts.hostname + or parts.username or parts.password or parts.query + or parts.fragment or parts.path not in ("", "/")): + raise ServiceError(400, "invalid_request", "router_url must be a plain origin") + with self.lock: + self._ensure_open() + state = self._run(run_id) + state.serving = f"{parts.scheme}://{parts.netloc}".rstrip("/") + if state.runtime is None and self.runtime_factory is not None: + runtime = self.runtime_factory(run_id, state.serving) + state.runtime = runtime + if state.config is None: + # The factory-built runtime carries its own config; the + # executor needs both for group admission. + state.config = getattr(runtime, "config", None) + return {"run_id": run_id, "router_url": state.serving, + "runtime": "attached" if state.runtime is not None else "pending"} + + # -- policy lifecycle (§7) --------------------------------------------- + + def activate_policy(self, run_id, states, expected): + from harborrl.platform.policy_pool import validate_pool + + with self.lock: + self._ensure_open() + state = self._run(run_id) + if state.runtime is None: + raise ServiceError(409, "admission_closed", "run has no serving runtime yet") + try: + version = validate_pool(states, str(expected)) + backend = getattr(state.runtime, 'backend', None) + if backend is not None: + live_states = backend.pool_states() + validate_pool(live_states, version) + if {item['endpoint'] for item in live_states} != {item['endpoint'] for item in states}: + raise ValueError('manager and GPU disagree on serving engine membership') + states = live_states + except (RuntimeError, TypeError, ValueError) as exc: + raise ServiceError(409, "pool_invalid", str(exc)) from exc + with self.lock: + # Pool probes above can race a shutdown. Do not reopen generation + # admission after close has frozen the service. + self._ensure_open() + registry = state.runtime.registry + registry.drain(float(getattr(state.config, "drain_timeout", 30))) + registry.publish_version(states, version) + # Mirror the admitted version into shared storage. + payload = {"weight_version": version, "engines": states, "timestamp": time.time()} + temp = self.run_root / "policy-pool.tmp" + temp.write_text(json.dumps(payload) + "\n") + temp.replace(self.run_root / "policy-pool.json") + return {"run_id": run_id, "policy_version": version, "admission": "open"} + + # -- group lifecycle ---------------------------------------------------- + + def _group_dir(self, run_id, group_id): + return self.run_root / GROUP_DIR / run_id / group_id + + def _restore_groups(self, run_id): + """Restore durable outcomes, never resume an unowned Runner or resample.""" + groups = {} + directory = self.run_root / GROUP_DIR / run_id + for root in sorted(directory.glob("*")): + if not root.is_dir(): + continue + request_path = root / "request.json" + if not request_path.exists(): + if any((root / name).exists() for name in ("running.json", "result.json", "failed.json", "cancelled.json", "unknown.json")): + raise ServiceError(500, "invalid_persisted_group", f"missing request: {root.name}") + continue + try: + request = validate_group_request(read_json(request_path)) + if request["group_id"] != root.name: + raise ValueError("group directory differs from request") + sha = request_digest(request) + terminal = [(name, status) for name, status in ( + ("result.json", "complete"), ("failed.json", "failed"), ("cancelled.json", "cancelled")) + if (root / name).exists()] + if len(terminal) > 1: + raise ValueError("conflicting terminal group records") + if terminal: + name, status = terminal[0] + record = read_json(root / name) + else: + status = "unknown" + record_path = root / "unknown.json" if (root / "unknown.json").exists() else root / "running.json" + record = read_json(record_path) if record_path.exists() else { + "group_id": root.name, "request_digest": sha, "created_at": time.time()} + if not isinstance(record, dict): + raise TypeError("persisted group record must be a mapping") + if record.get("group_id") != root.name or record.get("request_digest") != sha: + raise ValueError("persisted group does not match its request") + if terminal and record.get("status") != status: + raise ValueError("terminal status differs from its record") + if status == "complete" and ( + record.get("run_id") != run_id or record.get("schema_version") != SERVICE_SCHEMA + or record.get("policy_version") != request["policy_version"] + or [slot["slot_id"] for slot in record["slots"]] != [slot["slot_id"] for slot in request["slots"]] + ): + raise ValueError("persisted result identity differs from its request") + created_at = record.get("created_at") + if created_at is None and (root / "running.json").exists(): + running = read_json(root / "running.json") + if (not isinstance(running, dict) or running.get("request_digest") != sha + or running.get("group_id") != root.name): + raise ValueError("running record differs from its request") + created_at = running["created_at"] + group = GroupState(request, sha, status=status, + result=record if status == "complete" else None, + error=record.get("error"), created_at=created_at or 0) + if status == "unknown": + group.error = "Service restarted before durable group completion; confirm Runner cleanup and use a new run" + publish(root / "unknown.json", group.summary(include_result=False)) + marker = self.run_root / "native-rollouts/cleanup-required.json" + if not marker.exists(): + publish(marker, {"run_id": run_id, "group_id": root.name, + "reason": "Interrupted group has unknown Runner cleanup status"}) + groups[root.name] = group + except (OSError, ValueError, KeyError, TypeError) as exc: + raise ServiceError(500, "invalid_persisted_group", f"cannot restore {root.name}: {exc}") from exc + return groups + + def submit_group(self, run_id, request, *, wait=True): + request = validate_group_request(request) + sha = request_digest(request) + with self.lock: + state = self._run(run_id) + existing = state.groups.get(request["group_id"]) + if existing is not None: + if existing.request_sha != sha: + raise ServiceError(409, "conflict", + "group id already submitted with different content") + group = existing + else: + self._ensure_open() + if state.drained: + raise ServiceError(409, "admission_closed", "run is draining") + if state.runtime is None or state.config is None: + raise ServiceError(409, "admission_closed", + "run has no rollout runtime attached") + registry = getattr(state.runtime, "registry", None) + version = getattr(registry, "version", None) if registry is not None else None + accepting = getattr(registry, "accepting", True) if registry is not None else False + if not accepting or version != request["policy_version"]: + raise ServiceError( + 409, "stale_policy", + f"policy {request['policy_version']!r} is not the admitted version " + f"({version!r}, accepting={accepting}); activate first") + group = GroupState(request=request, request_sha=sha) + state.groups[request["group_id"]] = group + future = asyncio.run_coroutine_threadsafe( + self._execute(state, group), self.loop) + group.future = future + if wait: + return self._wait_group(run_id, group) + return group.summary(include_result=False) + + def _wait_group(self, run_id, group): + deadline = time.monotonic() + self.group_wait_timeout + while group.status in ("queued", "running"): + if time.monotonic() >= deadline: + return {**group.summary(include_result=False), + "hint": "query GET /groups/{group_id}; do not resubmit"} + time.sleep(self.poll_interval) + return group.summary() + + async def _execute(self, state, group): + # Immutable state records: each transition gets its own file, and + # publish() refuses to rewrite history. + group.task = asyncio.current_task() + request = group.request + directory = self._group_dir(state.run_id, request["group_id"]) + try: + publish(directory / "request.json", request) + if group.cancel_requested: + raise asyncio.CancelledError + group.status = "running" + publish(directory / "running.json", group.summary(include_result=False)) + trajectories = await self.executor(state.config, state.runtime, request) + export = export_group( + trajectories, len(trajectories), + allow_synthetic=self.allow_synthetic) + export_path = directory / "group-export.json" + publish(export_path, export) + result = build_group_result( + state.run_id, request, trajectories, runtime=state.runtime, + export={"path": str(export_path), "sha256": digest(export)}) + publish(directory / "result.json", result) + group.result = result + group.status = "complete" + except asyncio.CancelledError: + group.status = "cancelled" + publish(directory / "cancelled.json", group.summary(include_result=False)) + raise + except Exception as exc: # noqa: BLE001 — any executor failure is + # recorded as a failed group instead of killing the service + group.status = "failed" + group.error = f"{type(exc).__name__}: {exc}" + from harborrl.rollout.harbor_job.reliability import RetryableRolloutFailure + group.failure_code = ('retryable_infrastructure' if isinstance(exc, RetryableRolloutFailure) + else 'non_retryable') + publish(directory / "failed.json", group.summary(include_result=False)) + + def group_status(self, run_id, group_id): + with self.lock: + state = self._run(run_id) + group = state.groups.get(group_id) + if group is None: + raise ServiceError(404, "not_found", f"unknown group: {group_id}") + return group.summary() + + def cancel_group(self, run_id, group_id): + with self.lock: + state = self._run(run_id) + group = state.groups.get(group_id) + if group is None: + raise ServiceError(404, "not_found", f"unknown group: {group_id}") + if group.status == "unknown": + raise ServiceError(409, "cleanup_required", "interrupted group has no owned Task; inspect Runner cleanup") + self._cancel_groups([group]) + return group.summary() + + def drain_run(self, run_id): + with self.lock: + state = self._run(run_id) + state.drained = True + runtime = state.runtime + if runtime is not None: + registry = getattr(runtime, "registry", None) + if registry is not None: + timeout = float(getattr(state.config, "drain_timeout", 30)) + try: + registry.drain(timeout) + except TimeoutError as exc: + raise ServiceError(409, "drain_timeout", + f"generation still in flight: {exc}") from exc + return {"run_id": run_id, "state": "drained"} + + def cancel_run(self, run_id): + with self.lock: + state = self._run(run_id) + state.drained = True + groups = list(state.groups.values()) + if any(group.status == "unknown" for group in groups): + raise ServiceError(409, "cleanup_required", "interrupted groups require external cleanup confirmation") + self._cancel_groups(groups) + return {"run_id": run_id, "state": "cancelled", + "groups": {group.request["group_id"]: group.status for group in groups}} + + async def _cancel_and_wait(self, groups): + for group in groups: + if not group.cancel_requested and group.future is not None and not group.future.done(): + group.cancel_requested = True + if group.task is not None: + group.task.cancel() + # Do not cancel the run_coroutine_threadsafe Future: that wrapper can + # become done before the actual Task's asynchronous finally completes. + pending = [asyncio.wrap_future(group.future) for group in groups if group.future is not None] + results = await asyncio.gather(*pending, return_exceptions=True) + for result in results: + if isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError): + raise ServiceError(500, "cleanup_failed", f"group completion failed: {result}") + + def _cancel_groups(self, groups): + if not any(group.future is not None for group in groups): + return + if threading.current_thread() is self.thread: + raise RuntimeError("cancel rollout groups outside their executor loop") + joined = asyncio.run_coroutine_threadsafe(self._cancel_and_wait(groups), self.loop) + try: + joined.result(timeout=self._cleanup_budget()) + except concurrent.futures.TimeoutError as exc: + # Leave the waiter and group cleanup running; a second cancel would + # interrupt their finally blocks. Retrying close may join them later. + raise ServiceError(409, "cleanup_timeout", "rollout groups are still cleaning up") from exc + + +def make_control_server(service, host="127.0.0.1", port=0, *, max_body_bytes=8 * 1024 * 1024): + """Bounded stdlib HTTP transport for the control plane.""" + + class Handler(BaseHTTPRequestHandler): + def setup(self): + super().setup() + self.connection.settimeout(120) + + def log_message(self, *args): + pass + + def reply(self, status, payload): + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def token(self): + token = self.headers.get("x-api-key", "") + auth = self.headers.get("Authorization", "") + if auth: + if not auth.startswith("Bearer ") or token: + raise ServiceError(400, "invalid_request", "ambiguous authentication") + token = auth[7:] + return token + + def read_json(self): + if self.headers.get("Transfer-Encoding"): + raise ServiceError(400, "invalid_request", "chunked bodies are not supported") + size = int(self.headers.get("Content-Length", "0")) + if size <= 0 or size > max_body_bytes: + raise ServiceError(400, "invalid_request", "invalid request body size") + return json.loads(self.rfile.read(size)) + + def dispatch(self, method): + parts = [part for part in urlsplit(self.path).path.split("/") if part] + try: + payload = self.route(method, parts) + except ServiceError as exc: + self.reply(exc.status, {"error": {"type": exc.code, "message": str(exc)}}) + except (ValueError, TypeError, KeyError, OSError, json.JSONDecodeError) as exc: + self.reply(400, {"error": {"type": "invalid_request", + "message": f"{type(exc).__name__}: {exc}"}}) + else: + self.reply(200, payload) + + def route(self, method, parts): + if method == "GET" and parts == ["healthz"]: + return {"ok": True, "service": SERVICE_SCHEMA} + if method == "GET" and parts == ["readyz"]: + with service.lock: + attached = sum(1 for state in service.runs.values() + if state.runtime is not None) + return {"ok": True, "runs": len(service.runs), "attached_runs": attached} + if len(parts) < 2 or parts[0] != "runs": + raise ServiceError(404, "not_found", "unsupported endpoint") + run_id = parts[1] + if len(parts) == 3 and method == "POST" and parts[2] == "register": + body = self.read_json() + if not isinstance(body, dict) or set(body) != {"manifest"}: + raise ServiceError(400, "invalid_request", "body must be {manifest}") + return service.register_run(run_id, body["manifest"], token=self.token()) + service.authenticate(run_id, self.token()) + if len(parts) == 3 and method == "POST" and parts[2] == "groups": + return service.submit_group(run_id, self.read_json()) + if (len(parts) == 4 and parts[2] == "groups" + and method == "GET"): + return service.group_status(run_id, parts[3]) + if (len(parts) == 5 and parts[2] == "groups" and parts[4] == "cancel" + and method == "POST"): + return service.cancel_group(run_id, parts[3]) + if len(parts) == 4 and method == "POST" and parts[2] == "policy" \ + and parts[3] == "activate": + body = self.read_json() + if not isinstance(body, dict) or set(body) != {"states", "expected"}: + raise ServiceError(400, "invalid_request", + "body must be {states, expected}") + return service.activate_policy(run_id, body["states"], body["expected"]) + if len(parts) == 4 and method == "POST" and parts[2] == "serving" \ + and parts[3] == "announce": + body = self.read_json() + if not isinstance(body, dict) or set(body) != {"router_url"}: + raise ServiceError(400, "invalid_request", "body must be {router_url}") + return service.announce_serving(run_id, body["router_url"]) + if len(parts) == 3 and method == "POST" and parts[2] == "drain": + return service.drain_run(run_id) + if len(parts) == 3 and method == "POST" and parts[2] == "cancel": + return service.cancel_run(run_id) + raise ServiceError(404, "not_found", "unsupported endpoint") + + def do_GET(self): + self.dispatch("GET") + + def do_POST(self): + self.dispatch("POST") + + server = ThreadingHTTPServer((host, port), Handler) + server.daemon_threads = True + return server diff --git a/practices/h_cluster/HISTORICAL_VALIDATION.md b/practices/h_cluster/HISTORICAL_VALIDATION.md deleted file mode 100644 index 664de6e68..000000000 --- a/practices/h_cluster/HISTORICAL_VALIDATION.md +++ /dev/null @@ -1,32 +0,0 @@ -# Historical platform validation, 2026-10-20 - -This predates the controller integration and practice package extraction. -See README.md for the subsequent relay results and current validation limits. - -Project identity was verified through authenticated Sandbox and registry APIs. -The platform AccessKey can log into the primary registry. The Sandbox registry -uses separate credentials obtained through the platform's Harbor v2 account API; -the same AccessKey is not itself the Sandbox registry username/password. - -A dedicated task image was pushed successfully and a dedicated Environment was -created with capacity 2 and prewarm 0. A GPU-local runner completed real Sandbox -creation/readiness, positive and negative command exit-code checks, binary file -upload/download, and acknowledged deletion. These checks used the existing -prepared humanevalfix task image, not a newly built GPU environment image. - -Gateway reachability is blocked. The GPU-local HTTP probe responds with HTTP 200 -on loopback. Sandbox connections to two GPU interface addresses timed out. The -Environment initially ignored egressEnabled during creation. A subsequent PATCH -requires networkPolicy; setting default deny with explicit GPU /32 allow rules -succeeded, but the connection still timed out. No training was launched. - -One allocation timed out during SDK endpoint initialization. SDK cleanup was -followed by an explicit API check: the instance returned 404 and the Sandbox list -was empty. Subsequent controlled validation succeeded through command/files but -again failed Gateway reachability, then acknowledged instance deletion. - -Next gate: platform networking must provide a Sandbox-reachable GPU listener or -resolve the current route/policy restriction. Do not claim RL_READY or training -acceptance until a live group passes the existing session and token audits. -Deployment-specific IDs, addresses and detailed probe evidence are maintained -outside the public source tree in the validation directory on shared storage. diff --git a/practices/h_cluster/VALIDATION.md b/practices/h_cluster/VALIDATION.md deleted file mode 100644 index c5e525328..000000000 --- a/practices/h_cluster/VALIDATION.md +++ /dev/null @@ -1,76 +0,0 @@ -# Merged Controller and Sandbox validation - -Validation date: 2026-10-22. This is an infrastructure acceptance record, not a -model benchmark. Private addresses, credentials, task artifacts and platform IDs -are intentionally excluded. - -## Setup - -- One developer host runs Controller, RolloutService, Gateway and Harbor Runner. -- The optional H-cluster adapter creates real instances through OpenSandbox SDK - 0.1.9. Harbor 0.23.0 runs a pinned Claude Code 2.1.141 binary in each instance. -- Sandbox model requests use the developer mailbox relay. The developer reaches - GPU SGLang; Sandbox does not need a direct GPU route. -- Eight H200 GPUs run Qwen3-8B: four actor GPUs with TP4 and four serving GPUs - with TP4. All tests retain strict serving and consumption evidence checks. - -## Observed results - -| Test | Running instance peak | Actual agent execution peak | Result | -|---|---:|---:|---| -| Serial baseline | 1 | 1 | Four real trajectories, two training iterations and two checkpoints | -| SDK command capacity probe | 8 ready | Not an agent test | Eight concurrent ten-second commands completed in 11.037 seconds | -| Four-dataset stress | 4 | 2 | Batch rejected; four valid trajectories, three failed groups | -| Eight-dataset stress | 6 | 3 | Batch rejected; four valid trajectories, six failed groups | -| Three-dataset regression | 6 | 6 | Batch rejected after an agent API error | -| Two-dataset regression before actor fix | 6 | 6 | Six valid trajectories; actor incorrectly rejected two groups' weights | -| Identical regression after actor fix | 6 | 6 | First complete batch trained and saved a checkpoint; second batch hit an unknown generated tool | - -The two-dataset regression uses AARR and an existing HumanEvalFix task, three -samples per group, two groups per batch, a total instance limit of six, three -instances per Environment, startup concurrency four, and a 32-turn CLI limit. -These tasks were selected after the broad stress tests to isolate infrastructure -behavior. They are not an unbiased dataset sample. Each test starts from the -reference model; successful subsets from rejected batches are never repackaged -as new training batches. - -The SDK path demonstrably supports three simultaneous instances from one -Environment in this deployment. This does not override per-Environment capacity, -project quotas or platform scheduling. Pending allocations can take minutes. - -## Core fixes - -- `9a84641a`: port preflight handles immediate HTTP-server restarts after - TIME_WAIT while rejecting an existing listener. Real socket tests cover both. -- `dc208dc9`: actor postprocessing validates each group's local weight budget - using its unique rollout ID, rather than limiting a multi-group batch to one. - Partial actor shards remain valid; excess weight in one group cannot be hidden - by another group's smaller weight. Regression tests cover both properties. - -After these fixes, all 217 CPU tests passed, including the optional practice -tests. Changed Python files passed Ruff and the public-tree audit passed. - -## Limits - -Stable eight-agent mixed-dataset training has not passed. Observed failures -include Pending/startup errors, missing offline verifier dependencies, CLI turn -limits, unknown generated tools, and CLI tool-argument normalization that fails -exact consumption auditing. The relay is not a general internet proxy. - -In the second batch of the final regression, the model generated an undeclared -`finish` tool. Gateway returned a protocol error and the trial was rejected even -though its verifier reward was positive. This must not be bypassed or converted -into a synthetic successful trajectory. - -Successful training batches had uniform rewards within each group and zero -gradient norm. Optimizer execution, checkpoint creation and serving policy -version changes establish workflow execution, not learning improvement or -nonzero-gradient scaling correctness. The current `native_group_count` training -metric rounds microbatch weights and must not be used to count complete groups; -use RolloutService group results and audited trajectories instead. - -To repeat this test, configure private site files using the practice examples, -pin task/image/binary digests, start with a serial complete-group test, then -increase binding and global concurrency within actual platform limits. Record -agent start/end intervals separately from instance states. Retain rejected -groups and verify deletion of every allocated instance after completion. diff --git a/practices/h_cluster/src/harborrl_h_cluster/environment.py b/practices/h_cluster/src/harborrl_h_cluster/environment.py index 9639c1515..f204b0997 100644 --- a/practices/h_cluster/src/harborrl_h_cluster/environment.py +++ b/practices/h_cluster/src/harborrl_h_cluster/environment.py @@ -91,8 +91,9 @@ async def validate_binding(self): def extensions(self): return {'environmentId': self.binding['options']['environment_id']} - def api_params(self): - return {'project': self.cfg['options']['project']} + @classmethod + def cleanup_api_params(cls, cfg): + return {'project': cfg['options']['project']} def startup_transport(self, allocated): return SandboxStartupTransport(self.cfg['domain'].rstrip('/') + '/v1', allocated, diff --git a/scripts/audit_public_tree.sh b/scripts/audit_public_tree.sh index 917f58819..705f0dd0e 100755 --- a/scripts/audit_public_tree.sh +++ b/scripts/audit_public_tree.sh @@ -20,6 +20,7 @@ public_documents = { "configs/harbor_hub/public_compatibility_summary_zh.md", "docs/agents/environment-check.md", "docs/configuration-wizard.md", "docs/deployment.md", "docs/math-distill.md", "docs/sandbox-rollout.md", + "docs/rollout-runtime-lifecycle.md", "docs/train-inference-consistency.md", "docs/web-console.md", "practices/h_cluster/README.md", "harborrl/webui/static/lucide-LICENSE.txt", } @@ -100,6 +101,15 @@ for path in files: value = match.group(0) if b"127.0.0.1" in value or b"localhost" in value: continue + # Docker's documented host alias is public configuration. + if label == "internal DNS" and value == b"host.docker.internal": + continue + # The optional GPU pod bootstrap provisions the root SSH service; + # this fixed container system directory is not a personal checkout. + if (label == "personal path" and value == b"/root" + b"/" + and path.as_posix() == "practices/h_cluster/src/harborrl_h_cluster/rjob.py" + and re.match(rb"\.ssh(?:/authorized_keys)?(?=\s)", data[match.end():])): + continue raise SystemExit(f"{path} contains {label}: {value.decode(errors='replace')}") pyproject = Path("pyproject.toml").read_text() diff --git a/tests/harborrl/test_checkpoint_guard.py b/tests/harborrl/test_checkpoint_guard.py new file mode 100644 index 000000000..16ba83eef --- /dev/null +++ b/tests/harborrl/test_checkpoint_guard.py @@ -0,0 +1,93 @@ +import json +from pathlib import Path +import subprocess +import sys +import zipfile + +from harborrl.platform.checkpoint_guard import complete_checkpoints, prune + + +def checkpoint(root, step): + path = root / f'iter_{step:07d}' + path.mkdir(parents=True) + (path / '.metadata').write_bytes(b'metadata') + (path / 'common.pt').write_bytes(b'common') + (path / 'metadata.json').write_text(json.dumps({'sharded_backend': 'torch_dist'})) + with zipfile.ZipFile(path / '0.distcp', 'w') as stream: + stream.writestr('tensor', b'data') + (root / 'latest_checkpointed_iteration.txt').write_text(str(step)) + return path + + +def test_prune_waits_for_published_complete_successor(tmp_path): + first = checkpoint(tmp_path, 0) + second = checkpoint(tmp_path, 1) + (tmp_path / 'latest_checkpointed_iteration.txt').write_text('0') + assert prune(tmp_path, 1) == [] + (tmp_path / 'latest_checkpointed_iteration.txt').write_text('1') + archive = (second / '0.distcp').read_bytes() + (second / '0.distcp').write_bytes(archive[:20]) + assert prune(tmp_path, 1) == [] + assert first.exists() + (second / '0.distcp').write_bytes(archive) + journal = tmp_path / 'retention.jsonl' + assert prune(tmp_path, 1, journal=journal) == [str(first)] + assert second.exists() + assert [json.loads(line)['event'] for line in journal.read_text().splitlines()] == ['prune_planned', 'pruned'] + + +def test_prune_preserves_checkpoint_until_hf_export_complete(tmp_path): + root = tmp_path / 'checkpoints' + first = checkpoint(root, 0) + second = checkpoint(root, 1) + template = str(tmp_path / 'hf' / 'rollout-{rollout_id}') + for step in (0, 1): + hf = Path(template.format(rollout_id=step)) + hf.mkdir(parents=True) + (hf / 'model.safetensors.index.json').write_text(json.dumps({'weight_map': {'w': 'model.safetensors'}})) + header = json.dumps({'w': {'data_offsets': [0, 4]}}).encode() + (hf / 'model.safetensors').write_bytes(len(header).to_bytes(8, 'little') + header + b'data') + tail = Path(template.format(rollout_id=1)) / 'model.safetensors' + good = tail.read_bytes() + tail.write_bytes(good[:-1]) + assert prune(root, 1, hf_template=template) == [] + assert first.exists() + tail.write_bytes(good) + assert len(prune(root, 1, hf_template=template)) == 2 + assert not first.exists() and second.exists() and tail.exists() + + +def test_symlink_generation_is_never_pruned(tmp_path): + outside = tmp_path / 'outside' + external = checkpoint(outside, 0) + root = tmp_path / 'root' + checkpoint(root, 1) + (root / 'iter_0000000').symlink_to(external, target_is_directory=True) + assert [record['step'] for record in complete_checkpoints(root)] == [1] + assert prune(root, 1) == [] + assert external.exists() + + +def test_supervisor_returns_child_status_and_checks_space_before_launch(tmp_path): + prefix = [sys.executable, '-m', 'harborrl.platform.checkpoint_guard', + '--checkpoint-root', str(tmp_path / 'cp')] + result = subprocess.run(prefix + ['--min-free-gb', '0', '--', sys.executable, '-c', 'raise SystemExit(7)'], + capture_output=True, text=True, timeout=15) + assert result.returncode == 7, result.stderr + marker = tmp_path / 'should-not-exist' + result = subprocess.run(prefix + ['--min-free-gb', '1000000000', '--', sys.executable, '-c', + f'from pathlib import Path; Path({str(marker)!r}).touch()'], capture_output=True, text=True, timeout=15) + assert result.returncode != 0 and 'checkpoint preflight requires' in result.stderr + assert not marker.exists() + + +def test_resume_refuses_corrupt_latest_even_with_valid_older_checkpoint(tmp_path): + root = tmp_path / 'source' + checkpoint(root, 0) + second = checkpoint(root, 1) + (second / '0.distcp').write_bytes(b'partial') + result = subprocess.run([sys.executable, '-m', 'harborrl.platform.checkpoint_guard', + '--checkpoint-root', str(tmp_path / 'target'), '--resume-root', str(root), + '--min-free-gb', '0', '--', sys.executable, '-c', 'raise SystemExit(0)'], + capture_output=True, text=True, timeout=15) + assert result.returncode != 0 and 'no complete published checkpoint' in result.stderr diff --git a/tests/harborrl/test_deployment_config.py b/tests/harborrl/test_deployment_config.py index 8e6eb9f46..57884bdef 100644 --- a/tests/harborrl/test_deployment_config.py +++ b/tests/harborrl/test_deployment_config.py @@ -77,6 +77,22 @@ def test_valid_deployment_normalizes_and_summarizes(tmp_path): assert summary(config, "deployment.yaml")["digest"] == plan_summary["digest"] +def test_hub_deployment_retains_pull_configuration(tmp_path): + raw = deployment_mapping(tmp_path) + gpu = dict(raw['gpu_target'], transport='http_pull', ssh=None) + raw['gpu_target'] = gpu + raw['manager'].update(mode='hub', hub_port=49300, + hub_url='http://manager-a:49300', + gpu_pool=[dict(gpu, pull_url='http://manager-a:49300')]) + raw['rollout'] = dict(provider='hub_pull', workers=[]) + actual = validate(raw) + assert actual['manager']['mode'] == 'hub' + assert actual['manager']['hub_url'] == 'http://manager-a:49300' + assert actual['manager']['gpu_pool'][0]['transport'] == 'http_pull' + assert actual['gpu_target']['transport'] == 'http_pull' + assert actual['rollout']['provider'] == 'hub_pull' + + @pytest.mark.parametrize("mutation, message", [ ({"manager": {"mode": "service", "control_url": "http://127.0.0.1:49200"}}, "loopback"), ({"manager": {"control_url": "http://manager-a:49300"}}, "matching its declared port"), diff --git a/tests/harborrl/test_gateway_auto_shards.py b/tests/harborrl/test_gateway_auto_shards.py index d57823cbc..de59bf3fd 100644 --- a/tests/harborrl/test_gateway_auto_shards.py +++ b/tests/harborrl/test_gateway_auto_shards.py @@ -788,7 +788,7 @@ def test_failed_attempt_releases_its_gateway_lease(tmp_path, monkeypatch): async def flaky_attempt(identity, **kwargs): calls.append(identity.slot_id) if identity.slot_id == "0" and calls.count("0") == 1: - raise ValueError("sandbox exploded") + raise RuntimeError("sandbox transport failed") await asyncio.sleep(0) return {"identity": identity.to_dict()} @@ -883,7 +883,7 @@ def test_failed_group_settlement_still_retires_spawned_gateways(tmp_path, monkey async def broken_attempt(identity, **kwargs): await asyncio.sleep(0) # overlap so gw1 spawns before both fail - raise ValueError("sandbox exploded") + raise RuntimeError("sandbox transport failed") monkeypatch.setattr(rollout_runtime, "GroupSlots", PermissiveSlots) monkeypatch.setattr(rollout_runtime, "run_attempt", broken_attempt) diff --git a/tests/harborrl/test_gateway_recovery.py b/tests/harborrl/test_gateway_recovery.py new file mode 100644 index 000000000..2f59ce750 --- /dev/null +++ b/tests/harborrl/test_gateway_recovery.py @@ -0,0 +1,218 @@ +"""Synthetic CPU Gateway/coordinator recovery, never real training evidence.""" +import asyncio +import errno +import sys +import threading +from types import SimpleNamespace +from urllib.error import HTTPError, URLError + +import pytest +from test_native_contracts import identity +from test_native_gateway import Backend, payload, setup +from test_native_lifecycle import PROFILE +from test_sandbox_reliability import _reliability_runtime_config + +from harborrl.gateway.messages import ProtocolError +from harborrl.gateway.server import Gateway, make_server +from harborrl.gateway.trace import TraceRegistry +from harborrl.rollout.harbor_job.coordinator import GroupSlots +from harborrl.rollout.harbor_job.reliability import ( + InfraBudget, + InfraBudgetExhausted, + ReliabilityLedger, + RetryableRolloutFailure, + RetryPolicy, + summarize_reliability, +) +from harborrl.rollout.runtime import _run_slot +from harborrl.trajectories.native import RewardProfile, read_json + + +@pytest.mark.parametrize('error,retryable', [ + (OSError('transport failed'), True), (ConnectionResetError(), True), + (TimeoutError(), True), (URLError(ConnectionRefusedError()), True), + (HTTPError('http://engine', 503, 'unavailable', {}, None), True), + (HTTPError('http://engine', 400, 'invalid', {}, None), False), + (HTTPError('http://engine', 401, 'unauthorized', {}, None), False), + (URLError('unknown url type'), False), (ProtocolError('malformed output'), False), + (ValueError('policy mismatch'), False), (PermissionError(), False), + (OSError(errno.ENOSPC, 'no space left'), False), +]) +def test_gateway_records_trusted_transport_origin(tmp_path, error, retryable): + registry, ident, token, gateway = setup(tmp_path) + def fail(*args): + raise error + gateway.backend.generate = fail + with pytest.raises(type(error)): + gateway.generate(token, payload()) + assert not registry.transport_failure_only(ident.attempt_id) + registry.close(ident.attempt_id) + _, seal = registry.seal(ident.attempt_id) + assert seal['errors'] == [type(error).__name__] + assert registry.transport_failure_only(ident.attempt_id) is retryable + files = list((registry.attempts[ident.attempt_id]['root'] / 'generated').glob('*.json')) + assert len(files) == 1 + assert (read_json(files[0]).get('failure_kind') == 'upstream-transport') is retryable + + +def test_exception_name_alone_does_not_authorize_recovery(tmp_path): + registry, ident, token, _ = setup(tmp_path) + aid, rid, *_ = registry.begin(token) + registry.finish(aid, rid, error='OSError') + registry.close(aid) + registry.seal(aid) + assert not registry.transport_failure_only(ident.attempt_id) + + +WORKER = '''import json, sys, time +from pathlib import Path +from urllib import request, error +req = json.loads(sys.stdin.readline()) +trial = 'trial-' + req['identity']['attempt_id'] +print(json.dumps({'type': 'prepared', 'trial_id': trial}), flush=True) +sys.stdin.readline() +opener = request.build_opener(request.ProxyHandler({})) +messages = [] +for index in range(2): + for retry in range(2): + data = json.dumps({'model': 'policy', 'max_tokens': 64, + 'messages': [{'role': 'user', 'content': 'hello'}]}).encode() + try: + with opener.open(request.Request(req['gateway_url'] + '/v1/messages', data, + {'x-api-key': req['credential']}), timeout=5) as response: + messages.append(json.load(response)) + time.sleep(.05) # Let the synthetic HTTP handler acknowledge delivery. + break + except error.HTTPError: + if retry: + raise +root = Path(req['output']) / 'harbor' / trial +session = root / 'agent/sessions/projects/session.jsonl' +session.parent.mkdir(parents=True) +session.write_text(''.join(json.dumps({'type': 'assistant', 'sessionId': 's', + 'version': '2.1.0', 'message': message}) + chr(10) for message in messages)) +(root / 'verifier').mkdir() +(root / 'verifier/reward.json').write_text('{"reward": 0}') +(root / 'result.json').write_text(json.dumps({'id': trial, 'finished_at': 'test', + 'verifier_environment_mode': 'shared', 'verifier_result': {'rewards': {'reward': 0}}})) +print(json.dumps({'type': 'terminal', 'trial_id': trial, 'trial_dir': str(root), + 'result_path': str(root / 'result.json')}), flush=True) +''' + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX immutable trace publication') +@pytest.mark.parametrize('fault', ['once', 'persistent', 'protocol', 'policy', 'tokenizer', 'consumption']) +def test_real_coordinator_retries_only_proven_transport_and_records_terminal(tmp_path, monkeypatch, fault): + from harborrl.trajectories import native + + worker = tmp_path / 'synthetic-worker.py' + worker.write_text(WORKER) + spawn = asyncio.create_subprocess_exec + async def fake_spawn(*args, **kwargs): + return await spawn(sys.executable, '-S', str(worker), **kwargs) + monkeypatch.setattr(asyncio, 'create_subprocess_exec', fake_spawn) + # Permit synthetic evidence in this CPU fixture only; keep every IR check. + require_ready = native.require_ready + monkeypatch.setattr(native, 'require_ready', lambda ir: require_ready(ir, allow_synthetic=True)) + registry = TraceRegistry(tmp_path / 'traces') + seen, generated = [], {} + class FaultyBackend(Backend): + def generate(self, converted, ident, response_id): + aid = ident.attempt_id + if aid not in seen: + seen.append(aid) + if fault == 'persistent' or len(seen) == 1: + raise ProtocolError('malformed output') if fault == 'protocol' else OSError('transport failed') + generated[aid] = generated.get(aid, 0) + 1 + turn = super().generate(converted, ident, response_id) + if fault == 'policy': + turn['policy_version'] = 'wrong' + if fault == 'tokenizer' and generated[aid] == 2: + turn['tokenizer_digest'] = 'different' + return turn + if fault == 'consumption': + monkeypatch.setattr(registry, 'consume', lambda *args, **kwargs: None) + server = make_server(Gateway(registry, FaultyBackend(), model='policy')) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + config = _reliability_runtime_config(tmp_path) + config.gateway_url = f'http://127.0.0.1:{server.server_port}' + ledger = ReliabilityLedger(tmp_path / 'ledger', policy=RetryPolicy(backoff_seconds=(0,))) + runtime = SimpleNamespace(rollout_root=tmp_path / 'attempts', semaphore=asyncio.Semaphore(1), + profile=PROFILE, registry=registry, reliability=ledger, + shards=(SimpleNamespace(url=config.gateway_url, registry=registry),)) + slots = GroupSlots([identity('0'), identity('1')], max_attempts=2) + call = _run_slot(config, runtime, slots, 0, {'id': 'task', 'path': str(tmp_path)}, RewardProfile()) + try: + if fault == 'once': + result = asyncio.run(call) + assert result['identity']['attempt_id'] == seen[1] != seen[0] + assert result['evaluation']['training_reward'] == 0 + assert len(slots.completed) == 1 + require_ready(result, allow_synthetic=True) + else: + with pytest.raises(RetryableRolloutFailure if fault == 'persistent' else ValueError): + asyncio.run(call) + assert not slots.completed + finally: + server.shutdown() + server.server_close() + thread.join(5) + summary = summarize_reliability(ledger.root) + expected = 2 if fault in {'once', 'persistent'} else 1 + assert len(seen) == summary['attempts'] == summary['terminal_attempts'] == expected + assert summary['completed_attempts'] == (1 if fault == 'once' else 0) + assert summary['retry_decisions'] == (1 if fault == 'once' else 2 if fault == 'persistent' else 0) + assert all(row['status'] != 'running' for row in slots.history['0']) + assert all(state['closed'] and state['sealed'] for state in registry.attempts.values()) + if fault in {'once', 'persistent', 'tokenizer'}: + failed = read_json(runtime.rollout_root / 'group' / seen[0] / 'trajectory.v2.json') + assert failed['readiness'] == 'EVAL_ONLY' + assert failed['trace_seal']['errors'] + with pytest.raises(ValueError): + require_ready(failed, allow_synthetic=True) + + +def test_rejection_of_wrong_identity_records_failure_and_no_retry(tmp_path, monkeypatch): + from test_native_contracts import make_ir + + from harborrl.rollout import runtime as module + from harborrl.trajectories import native + + require_ready = native.require_ready + monkeypatch.setattr(native, 'require_ready', lambda ir: require_ready(ir, allow_synthetic=True)) + async def wrong_identity(*args, **kwargs): + return make_ir(tmp_path, slot='1') + monkeypatch.setattr(module, 'run_attempt', wrong_identity) + ledger = ReliabilityLedger(tmp_path / 'ledger') + runtime = SimpleNamespace(rollout_root=tmp_path, semaphore=asyncio.Semaphore(1), + profile={}, registry=None, reliability=ledger, + shards=(SimpleNamespace(url='http://gateway', registry=None),)) + slots = GroupSlots([identity('0'), identity('1')]) + with pytest.raises(ValueError, match='active attempt'): + asyncio.run(_run_slot(_reliability_runtime_config(tmp_path), runtime, slots, 0, + {'id': 'task', 'path': '/task'}, RewardProfile())) + summary = summarize_reliability(ledger.root) + assert summary['attempts'] == summary['terminal_attempts'] == summary['failed_attempts'] == 1 + assert summary['retry_decisions'] == 0 + assert slots.history['0'][0]['status'] == 'invalid' + + +def test_failure_budget_exhaustion_still_records_cleanup(tmp_path, monkeypatch): + from harborrl.rollout import runtime as module + + ledger = ReliabilityLedger(tmp_path / 'ledger', budget=InfraBudget(2, 1, 1, 1, 3600)) + ledger.budget.remaining['storage_faults'] = 0 + runtime = SimpleNamespace(rollout_root=tmp_path, semaphore=asyncio.Semaphore(1), + profile={}, registry=None, reliability=ledger, + shards=(SimpleNamespace(url='http://gateway', registry=None),)) + async def fail(*args, **kwargs): + raise OSError(errno.ENOSPC, 'no space left') + cleaned = [] + monkeypatch.setattr(module, 'run_attempt', fail) + monkeypatch.setattr(module, '_record_cleanup', lambda ledger, ident, root: cleaned.append(ident.attempt_id)) + slots = GroupSlots([identity('0'), identity('1')]) + with pytest.raises(InfraBudgetExhausted): + asyncio.run(_run_slot(_reliability_runtime_config(tmp_path), runtime, slots, 0, + {'id': 'task', 'path': '/task'}, RewardProfile())) + assert cleaned == ['attempt-0'] + assert summarize_reliability(ledger.root)['failed_attempts'] == 1 diff --git a/tests/harborrl/test_hub_rollout_client.py b/tests/harborrl/test_hub_rollout_client.py new file mode 100644 index 000000000..a0fa99499 --- /dev/null +++ b/tests/harborrl/test_hub_rollout_client.py @@ -0,0 +1,274 @@ +"""Worker-published IR acceptance and trust-boundary regression checks.""" +import json + +import pytest + +from harborrl.backends.slime_v032.hub_rollout_client import HubRolloutError, load_attempt_ir +from harborrl.trajectories.native import digest, publish + + +@pytest.mark.parametrize('mirror', [None, '', 'relative/attempts']) +def test_worker_requires_shared_mirror_before_starting_attempt(monkeypatch, tmp_path, mirror): + from harborrl.deployment.hub_rollout_executor import RolloutExecutor + + if mirror is None: + monkeypatch.delenv('HARBORRL_HUB_ATTEMPT_MIRROR', raising=False) + else: + monkeypatch.setenv('HARBORRL_HUB_ATTEMPT_MIRROR', mirror) + run_root = tmp_path / 'attempts' + executor = RolloutExecutor( + run_root=run_root, task_path=tmp_path / 'task', profile={}, + runner_python='python', source_dir=tmp_path, gateway_host='127.0.0.1') + with pytest.raises(ValueError, match='absolute shared directory'): + executor.execute({}) + assert not run_root.exists() + +def test_worker_publishes_ir_to_configured_shared_storage(monkeypatch, tmp_path): + from types import SimpleNamespace + from harborrl.deployment import hub_rollout_executor + from harborrl.rollout.harbor_job import coordinator + + mirror = tmp_path / 'shared' + monkeypatch.setenv('HARBORRL_HUB_ATTEMPT_MIRROR', str(mirror)) + closed = [] + server = SimpleNamespace( + server_address=('127.0.0.1', 12345), serve_forever=lambda: None, + shutdown=lambda: closed.append('shutdown'), + server_close=lambda: closed.append('close')) + monkeypatch.setattr(hub_rollout_executor, 'make_server', lambda *a, **k: server) + + async def attempt(identity, *, root, **kwargs): + root.mkdir(parents=True, exist_ok=True) + ir = {'identity': {'policy_version': identity.policy_version}, + 'readiness': 'RL_READY', 'integrity_errors': [], + 'evaluation': {'training_reward': 1.0}} + publish(root / 'trajectory.v2.json', ir) + publish(root / 'evaluation.json', ir['evaluation']) + return ir + + monkeypatch.setattr(coordinator, 'run_attempt', attempt) + executor = hub_rollout_executor.RolloutExecutor( + run_root=tmp_path / 'worker', task_path=tmp_path / 'task', + profile={'model': 'policy'}, runner_python='python', source_dir='.', + gateway_host='127.0.0.1', log=lambda _: None) + result = executor.execute({'task_id': 'task-1', 'task_digest': 'task-sha', 'synthetic': True}) + expected = mirror / 'task-1-0' / 'trajectory.v2.json' + assert result['ir_path'] == str(expected) + assert load_attempt_ir('task-1', result, expected_policy_version='1') == json.loads( + expected.read_text(encoding='utf-8')) + assert (expected.parent / 'evaluation.json').is_file() + assert closed == ['shutdown', 'close'] + + +def test_hub_requires_explicit_configuration(monkeypatch, tmp_path): + from harborrl.backends.slime_v032 import rollout, hub_rollout_client + + monkeypatch.delenv('HARBORRL_HUB_URL', raising=False) + monkeypatch.delenv('HARBORRL_HUB_ENV_FILE', raising=False) + reads = [] + monkeypatch.setattr(rollout.Path, 'read_text', lambda *a, **k: reads.append(a) or '{}') + assert rollout.hub_rollout_enabled() is False + with pytest.raises(HubRolloutError, match='is not set'): + hub_rollout_client.client_from_environment() + assert reads == [] + + +def test_explicit_hub_file_is_passed_to_training_and_ray(monkeypatch, tmp_path): + from harborrl.deployment.training_target import local_target + from harborrl.platform.hub_train import rollout_environment + + filename = str(tmp_path / 'hub.json') + monkeypatch.setenv('HARBORRL_HUB_ENV_FILE', filename) + monkeypatch.setenv('UNRELATED_SECRET', 'must-not-propagate') + target = local_target({'training_command': ['true']}, environment={'RUN_ID': 'run-1'}) + forwarded = rollout_environment(target.env) + assert forwarded['HARBORRL_HUB_ENV_FILE'] == filename + assert forwarded['RUN_ID'] == 'run-1' + assert 'UNRELATED_SECRET' not in forwarded + + +@pytest.fixture +def published_ir(tmp_path): + ir = {"identity": {"policy_version": "3", "task_digest": "task-sha"}, + "readiness": "RL_READY", "integrity_errors": [], + "evaluation": {"training_reward": 1.0}} + path = tmp_path / "trajectory.v2.json" + publish(path, ir) + return ir, path, {"ir_path": str(path), "ir_sha256": digest(ir)} + + +def test_accepts_worker_publication_with_trailing_newline(published_ir): + ir, path, report = published_ir + assert path.read_bytes().endswith(b"\n") + assert load_attempt_ir("task", report, expected_policy_version="3", + expected_task_digest="task-sha") == ir + + +def test_structural_digest_is_independent_of_json_whitespace(published_ir): + ir, path, report = published_ir + path.write_text(json.dumps(ir, indent=2), encoding="utf-8") + assert load_attempt_ir("task", report) == ir + + +def test_accepts_worker_report_envelope(published_ir): + ir, _, report = published_ir + envelope = {"success": True, "result": {"success": True, **report}} + assert load_attempt_ir("task", envelope, expected_policy_version="3") == ir + + +@pytest.mark.parametrize("envelope", [ + {"success": False, "result": {}}, + {"success": True, "result": None}, + {"success": True, "result": {"success": False}}, +]) +def test_rejects_failed_worker_envelope(envelope): + with pytest.raises(HubRolloutError, match="unsuccessful|failed attempt"): + load_attempt_ir("task", envelope) + + +def test_enveloped_synthetic_ir_is_still_rejected(published_ir): + ir, path, report = published_ir + ir["readiness"] = "CONTRACT_READY" + path.write_text(json.dumps(ir), encoding="utf-8") + report["ir_sha256"] = digest(ir) + with pytest.raises(HubRolloutError, match="not RL_READY"): + load_attempt_ir("task", {"success": True, "result": report}) + + +def test_hub_refreshes_policy_lock_after_weight_update(monkeypatch, tmp_path): + import asyncio + from types import SimpleNamespace + from harborrl.backends.slime_v032 import rollout, rollout_service_client + from harborrl.backends.slime_v032 import hub_rollout_client + + monkeypatch.setenv("RUN_DIR", str(tmp_path)) + monkeypatch.setenv("HARBORRL_HUB_ENV_FILE", str(tmp_path / "missing.json")) + monkeypatch.setenv("HARBORRL_HUB_SERVING_ENDPOINT", "http://worker:30001") + monkeypatch.setenv("HARBORRL_HUB_HF_CKPT", "checkpoint") + monkeypatch.setenv("HARBORRL_CONSISTENCY_MODE", "off") + monkeypatch.setattr(hub_rollout_client, "client_from_environment", lambda: object()) + states = [dict(endpoint="http://engine:15000", healthy=True, weight_version="1")] + monkeypatch.setattr(rollout_service_client, "fetch_pool_states", lambda _: states) + args = SimpleNamespace(sglang_router_ip="router", sglang_router_port=8000, + rollout_max_response_len=2048) + for step in (0, 1): + states[0]["weight_version"] = str(step + 1) + assert asyncio.run(rollout.run_hub_groups(args, [], step)) == [] + assert json.loads((tmp_path / "policy-pool.json").read_text())["weight_version"] == str(step + 1) + history = (tmp_path / "policy-pool-history.jsonl").read_text().splitlines() + assert [json.loads(line)["weight_version"] for line in history] == ["1", "2"] + states[0]["healthy"] = False + with pytest.raises(RuntimeError, match="unhealthy"): + asyncio.run(rollout.run_hub_groups(args, [], 2)) + + +@pytest.mark.parametrize("audited", [False, True]) +def test_hub_request_preserves_explicit_logprob_audit(audited): + from harborrl.backends.slime_v032.hub_rollout_client import hub_attempt_request + group = dict(task=dict(path="/task", task_digest="sha"), rollout_id=0, + group_id="group", policy_version="1") + result = hub_attempt_request(group, dict(slot_id="0"), serving_endpoint="http://engine", + hf_ckpt="model", tokenizer_digest="tok", template_digest="tpl", model_tag="qwen3-8B", + max_output_tokens=2048, max_context=32768, task_path="/task", + audited_raw_logprobs=audited) + assert result["audited_raw_logprobs"] is audited + + +@pytest.mark.parametrize('generation', [0, 1]) +def test_hub_dispatch_identity_satisfies_generation_journal(monkeypatch, generation): + from types import SimpleNamespace + from harborrl.backends.slime_v032 import rollout_service_client + from harborrl.backends.slime_v032.hub_rollout_client import hub_attempt_request + from harborrl.rollout.generations import ACTIVE_GENERATION, GenerationJournal + + task = dict(path='/task', task_digest='sha') + monkeypatch.setattr(rollout_service_client, 'task_entry', lambda _: task) + token = ACTIVE_GENERATION.set({'generation': generation}) + try: + group = rollout_service_client.service_group_request( + [SimpleNamespace(group_index=0), SimpleNamespace(group_index=0)], {}, 2, '3') + finally: + ACTIVE_GENERATION.reset(token) + kwargs = dict(serving_endpoint='http://engine', hf_ckpt='model', + tokenizer_digest='tok', template_digest='tpl', model_tag='qwen3-8B', + max_output_tokens=512, max_context=32768, task_path='/task') + identities = [hub_attempt_request(group, slot, **kwargs) for slot in group['slots']] + inputs = {'groups': [{'group_index': 0, 'slots': ['0', '1'], 'tasks': [task, task]}]} + assert GenerationJournal.validate_result( + [[{'identity': identity} for identity in identities]], inputs, 2, generation, '3') + with pytest.raises(ValueError, match='conflicts with rollout generation'): + hub_attempt_request(group, group['slots'][0], batch_id='batch', **kwargs) + + +@pytest.mark.parametrize('sandbox', [None, {'adapter': 'example:Sandbox', 'credential_file': '/run/key'}]) +def test_hub_dispatch_preserves_sandbox_runtime(monkeypatch, tmp_path, sandbox): + import asyncio + from types import SimpleNamespace + from harborrl.backends.slime_v032 import rollout, rollout_service_client, hub_rollout_client + from harborrl.platform import policy_pool + + class Submitted(Exception): + pass + + captured = [] + class Client: + def submit_attempt(self, request): + captured.append(request) + raise Submitted() + + monkeypatch.setenv('RUN_DIR', str(tmp_path)) + monkeypatch.setenv('HARBORRL_HUB_ENV_FILE', str(tmp_path / 'missing.json')) + monkeypatch.setenv('HARBORRL_HUB_SERVING_ENDPOINT', 'http://engine:15000') + monkeypatch.setenv('HARBORRL_HUB_HF_CKPT', 'model') + monkeypatch.setenv('HARBORRL_NATIVE_SANDBOX', json.dumps(sandbox)) + monkeypatch.setattr(hub_rollout_client, 'client_from_environment', Client) + monkeypatch.setattr(rollout_service_client, 'fetch_pool_states', lambda _: []) + monkeypatch.setattr(policy_pool, 'publish_pool', lambda _: None) + monkeypatch.setattr(rollout, 'lock_policy_version', lambda _: '1') + group = dict(task=dict(path='/task', task_digest='sha'), rollout_id=0, + group_id='group', policy_version='1', slots=[dict(slot_id='0')]) + monkeypatch.setattr(rollout_service_client, 'service_group_request', lambda *a: group) + args = SimpleNamespace(sglang_router_ip='router', sglang_router_port=8000, + rollout_max_response_len=512) + with pytest.raises(Submitted): + asyncio.run(rollout.run_hub_groups(args, [object()], 0)) + assert captured[0].get('sandbox') == sandbox + assert ('sandbox' in captured[0]) is (sandbox is not None) + + +def test_rejects_changed_reward(published_ir): + ir, path, report = published_ir + ir["evaluation"]["training_reward"] = 0.0 + path.write_text(json.dumps(ir), encoding="utf-8") + with pytest.raises(HubRolloutError, match="digest mismatch"): + load_attempt_ir("task", report) + + +@pytest.mark.parametrize("raw", ['{"a":1,"a":2}', '{"a":NaN}', 'broken']) +def test_rejects_invalid_or_ambiguous_json(published_ir, raw): + _, path, report = published_ir + path.write_text(raw, encoding="utf-8") + with pytest.raises(HubRolloutError, match="invalid IR"): + load_attempt_ir("task", report) + + +@pytest.mark.parametrize("field,value,error", [ + ("readiness", "CONTRACT_READY", "not RL_READY"), + ("integrity_errors", ["bad seal"], "integrity errors"), +]) +def test_keeps_training_readiness_gate(published_ir, field, value, error): + ir, path, report = published_ir + ir[field] = value + path.write_text(json.dumps(ir), encoding="utf-8") + report["ir_sha256"] = digest(ir) + with pytest.raises(HubRolloutError, match=error): + load_attempt_ir("task", report) + + +@pytest.mark.parametrize("expected,error", [ + ({"expected_policy_version": "4"}, "policy version"), + ({"expected_task_digest": "other"}, "task digest"), +]) +def test_keeps_identity_locks(published_ir, expected, error): + with pytest.raises(HubRolloutError, match=error): + load_attempt_ir("task", published_ir[2], **expected) diff --git a/tests/harborrl/test_math.py b/tests/harborrl/test_math.py index 97c68e521..d5ee0c663 100644 --- a/tests/harborrl/test_math.py +++ b/tests/harborrl/test_math.py @@ -32,6 +32,11 @@ def test_gsm8k_numeric_verifier(response, reference, status): assert result["reward"] == (1.0 if status == "correct" else 0.0) +@pytest.mark.parametrize("response", ["####16", "work\n####16\n", "#### 16"]) +def test_gsm8k_accepts_marker_without_space(response): + assert verify(response, "16", "gsm8k_numeric_v1")["status"] == "correct" + + def test_verifier_version_is_locked_in_task_import(tmp_path): row = {**load_tasks(ROOT / "examples/math/tasks.jsonl")[0], "verifier": "gsm8k_numeric_v1"} tasks = tmp_path / "tasks.jsonl" @@ -48,6 +53,38 @@ def test_verifier_version_is_locked_in_task_import(tmp_path): verify("2", "2", "unknown") +math_verify = pytest.importorskip("math_verify", reason="math_latex_v1 cases need math_verify") + + +@pytest.mark.parametrize("response,reference,status", [ + (r"The sum is $\frac{1}{2}$", r"\frac{1}{2}", "correct"), + (r"so the answer is 0.5", r"\frac{1}{2}", "correct"), + (r"$\boxed{\sqrt{12}}$", r"2\sqrt{3}", "correct"), + (r"$\boxed{5}$", "5", "correct"), + (r"#### 5", "5", "correct"), + (r"$\boxed{6}$", "5", "incorrect"), + ("I cannot solve this", "5", "unparseable"), + ("x" * 20000, "5", "unsupported"), +]) +def test_math_latex_verifier(response, reference, status): + result = verify(response, reference, "math_latex_v1") + assert result["status"] == status + assert result["verifier"] == "math_latex_v1" + assert result["reward"] == (1.0 if status == "correct" else 0.0) + + +def test_math_latex_reference_validation(tmp_path): + row = {**load_tasks(ROOT / "examples/math/tasks.jsonl")[0], "task_id": "math-latex-1", + "problem_id": "math-latex-1", "verifier": "math_latex_v1", "reference": r"2\sqrt{3}"} + tasks = tmp_path / "tasks.jsonl" + tasks.write_text(json.dumps(row)) + assert load_tasks(tasks)[0]["reference"] == r"2\sqrt{3}" + row["reference"] = "line\nbreak" + tasks.write_text(json.dumps(row)) + with pytest.raises(ValueError, match="bounded single-line LaTeX"): + load_tasks(tasks) + + def test_split_lock_and_curated_import(tmp_path): source = ROOT / "examples/math/tasks.jsonl" tasks = load_tasks(source) diff --git a/tests/harborrl/test_native_training.py b/tests/harborrl/test_native_training.py index 33100ede4..656c3a3a9 100644 --- a/tests/harborrl/test_native_training.py +++ b/tests/harborrl/test_native_training.py @@ -124,6 +124,41 @@ def test_schema2_launch_plan_and_strict_override(tmp_path, capsys): +def test_native_checkpoint_and_token_settings_reach_child(tmp_path, monkeypatch): + path, task = native_config(tmp_path) + from harborrl.data.harbor.native_inspector import inspect_native + from harborrl.deployment.training_target import local_target + from harborrl.platform.evidence import run_environment + + config = load_config(path, ['training.resume=checkpoints/prior', + 'training.max_tokens_per_gpu=32768', 'training.max_ckpt_keep=1']) + catalog_path = Path(config['tasks']['catalog']) + entries = json.loads(catalog_path.read_text()) + entries[0]['task_digest'] = inspect_native(task)['task_digest'] + catalog_path.write_text(json.dumps(entries)) + plan = launch_plan(config) + # Ambient launcher variables are deliberately filtered; declared config wins. + monkeypatch.setenv('RESUME_LOAD', '/wrong-checkpoint') + monkeypatch.setenv('MAX_TOKENS_PER_GPU', '8') + monkeypatch.setenv('MAX_CKPT_KEEP', '99') + environment = run_environment(plan, tmp_path, catalog_path, tmp_path / 'prompts.jsonl') + child = local_target(plan, environment=environment) + assert child.env['RESUME_LOAD'] == str(tmp_path / 'checkpoints/prior') + assert child.env['MAX_TOKENS_PER_GPU'] == '32768' + assert child.env['MAX_CKPT_KEEP'] == '1' + defaults = launch_plan(load_config(path))['environment'] + assert 'RESUME_LOAD' not in defaults + assert defaults['MAX_TOKENS_PER_GPU'] == '16384' + assert defaults['MAX_CKPT_KEEP'] == '2' + for key in ('max_tokens_per_gpu', 'max_ckpt_keep'): + for value in ('0', '-1', 'true', '1.5', 'null'): + with pytest.raises(ValueError, match=f'training.{key}'): + load_config(path, [f'training.{key}={value}']) + for value in ('true', '1', '""', '" "'): + with pytest.raises(ValueError, match='training.resume'): + load_config(path, [f'training.resume={value}']) + + def test_cli_command_mode_selects_experiment_dimensions(tmp_path, capsys, monkeypatch): path, task = native_config(tmp_path) from harborrl.data.harbor.native_inspector import inspect_native @@ -485,6 +520,7 @@ def test_native_batch_waits_for_all_group_cleanup( from harborrl.rollout import runtime as rollout_runtime monkeypatch.delenv('HARBORRL_ROLLOUT_SERVICE_URL', raising=False) + monkeypatch.setattr(rollout, 'hub_rollout_enabled', lambda: False) cleaned, closed = [], [] failure = RuntimeError('one group failed') diff --git a/tests/harborrl/test_rejected_generations.py b/tests/harborrl/test_rejected_generations.py new file mode 100644 index 000000000..ae9187d2f --- /dev/null +++ b/tests/harborrl/test_rejected_generations.py @@ -0,0 +1,123 @@ +"""Rejected model outputs are evidence, never retry or training inputs.""" +import errno +import json +from copy import deepcopy + +import pytest +from test_native_gateway import payload, setup + +from harborrl.gateway.messages import ProtocolError +from harborrl.gateway.sglang_backend import SGLangBackend +from harborrl.models.qwen import QwenModelAdapter +from harborrl.trajectories.native import digest, read_json + + +def backend_for(root, output): + class Tokenizer: + def apply_chat_template(self, *args, **kwargs): + return [11, 12] + + def decode(self, ids, skip_special_tokens): + return output['text'] + + class Response: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self): + return json.dumps(output).encode() + + class Opener: + calls = 0 + + def open(self, request, timeout): + self.calls += 1 + return Response() + + backend = SGLangBackend('http://engine', Tokenizer(), QwenModelAdapter(), + tokenizer_digest='tok', template_digest='tpl', rejected_root=root) + backend.opener = Opener() + return backend + + +def serving_output(text): + return {'text': text, 'meta_info': {'weight_version': '1', + 'output_token_logprobs': [[-.2, 13]], 'finish_reason': {'type': 'stop'}}} + + +@pytest.mark.parametrize('fault', ['json', 'incomplete', 'version', 'logprobs', 'finish']) +def test_rejected_output_is_preserved_but_not_delivered_or_retryable(tmp_path, fault): + output = serving_output('done') + if fault == 'json': + output['text'] = '{"name":"Edit","arguments":oops}' + elif fault == 'incomplete': + output['text'] = '{"name":' + elif fault == 'version': + output['meta_info']['weight_version'] = 'wrong' + elif fault == 'logprobs': + output['meta_info']['output_token_logprobs'] = [[None, 13]] + else: + output['meta_info']['finish_reason'] = {'type': 'abort'} + original = deepcopy(output) + registry, ident, token, gateway = setup(tmp_path) + rejected = tmp_path / 'rejected' + backend = gateway.backend = backend_for(rejected, output) + with pytest.raises(ValueError): + gateway.generate(token, payload()) + assert backend.opener.calls == 1 and output == original + paths = list(rejected.glob('*/*.json')) + assert len(paths) == 1 + record = read_json(paths[0]) + assert record['identity'] == ident.to_dict() + assert record['serving_output'] == original + assert record['serving_output_digest'] == digest(original) + assert record['serving_input']['input_ids'] == [11, 12] + assert record['converted_request']['messages'] == [{'role': 'user', 'content': 'hello'}] + assert record['training_use'] is False and token not in paths[0].read_text() + assert paths[0].parent.name == digest(ident.to_dict()) + assert paths[0].stem == digest(record['response_id']) + registry.close(ident.attempt_id) + turns, seal = registry.seal(ident.attempt_id) + assert turns == [] and seal['errors'] + assert registry.has_nontransport_failure(ident.attempt_id) + assert not registry.transport_failure_only(ident.attempt_id) + + +def test_valid_output_creates_no_rejected_evidence(tmp_path): + _registry, ident, token, gateway = setup(tmp_path) + rejected = tmp_path / 'rejected' + gateway.backend = backend_for(rejected, serving_output('done')) + aid, message = gateway.generate(token, payload()) + assert aid == ident.attempt_id and message['content'] == [{'type': 'text', 'text': 'done'}] + assert not rejected.exists() + + +@pytest.mark.parametrize('error', [OSError(errno.ECONNRESET, 'write failed'), + OSError(errno.ENOSPC, 'full'), ValueError('conflict')]) +def test_diagnostic_write_failure_cannot_authorize_transport_retry(tmp_path, monkeypatch, error): + from harborrl.gateway import sglang_backend + + registry, ident, token, gateway = setup(tmp_path) + gateway.backend = backend_for(tmp_path / 'rejected', serving_output('bad')) + def fail(*args): + raise error + monkeypatch.setattr(sglang_backend, 'publish', fail) + with pytest.raises(ValueError, match='could not be persisted'): + gateway.generate(token, payload()) + registry.close(ident.attempt_id) + turns, seal = registry.seal(ident.attempt_id) + assert turns == [] and seal['errors'] == ['ValueError'] + assert not registry.transport_failure_only(ident.attempt_id) + assert registry.has_nontransport_failure(ident.attempt_id) + + +def test_record_without_sink_keeps_protocol_rejection(tmp_path): + registry, ident, token, gateway = setup(tmp_path) + gateway.backend = backend_for(None, serving_output('bad')) + with pytest.raises(ProtocolError, match='invalid generated tool JSON'): + gateway.generate(token, payload()) + registry.close(ident.attempt_id) + assert registry.seal(ident.attempt_id)[1]['errors'] == ['ProtocolError'] diff --git a/tests/harborrl/test_rollout_generations.py b/tests/harborrl/test_rollout_generations.py new file mode 100644 index 000000000..0c5defc56 --- /dev/null +++ b/tests/harborrl/test_rollout_generations.py @@ -0,0 +1,133 @@ +import asyncio +import sys +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace + +import pytest + +from harborrl.rollout.generations import ( + ACTIVE_GENERATION, + GenerationJournal, + GenerationPolicy, + generation_batch_id, + reserve_generation_attempt, +) +from harborrl.rollout.harbor_job.reliability import ( + InfraBudgetExhausted, + RetryableRolloutFailure, +) +from harborrl.trajectories.native import Identity, read_json + +pytestmark = pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced immutable manifests') + + +def result(rollout, generation, version='1'): + return [[{'identity': {'batch_id': generation_batch_id(rollout, generation), + 'policy_version': version, 'trajectory_id': f't-{generation}-{group}'}}] + for group in range(2)] + + +def test_entire_rollout_reruns_with_fixed_inputs_and_no_partial_selection(tmp_path): + journal = GenerationJournal(tmp_path) + calls, discarded, partial = [], [], [] + async def run(generation): + calls.append(dict(ACTIVE_GENERATION.get())) + if generation == 0: + partial.append(result(2, 0)[0]) + raise RetryableRolloutFailure('sibling exhausted attempts') + assert not partial + return result(2, generation) + def discard(): + discarded.append(True) + partial.clear() + output = asyncio.run(journal.execute(2, {'tasks': ['a', 'b']}, '1', run, discard=discard)) + assert output == result(2, 1) and len(discarded) == 1 + assert len(calls) == 2 and calls[0]['input_sha256'] == calls[1]['input_sha256'] + root = tmp_path / 'rollout-generations/rollout-2' + assert read_json(root / 'generation-0/superseded.json')['export_allowed'] is False + assert read_json(root / 'selected.json')['generation'] == 1 + assert ACTIVE_GENERATION.get() is None + + +def test_rerun_budget_is_seed_scoped_across_batches_and_restarts(tmp_path): + policy = GenerationPolicy(max_reruns_per_seed=1) + async def run(generation): + if generation == 0: + raise RetryableRolloutFailure('failure') + return result(0, generation) + asyncio.run(GenerationJournal(tmp_path, policy).execute(0, {}, '1', run)) + async def failed(generation): + raise RetryableRolloutFailure('failure') + with pytest.raises(InfraBudgetExhausted): + asyncio.run(GenerationJournal(tmp_path, policy).execute(1, {}, '1', failed)) + assert not (tmp_path / 'rollout-generations/rollout-1/selected.json').exists() + with pytest.raises(ValueError, match='already exists'): + asyncio.run(GenerationJournal(tmp_path, policy).execute(0, {}, '1', run)) + + +@pytest.mark.parametrize('fault', ['protocol', 'cancel', 'stale-policy', 'old-generation']) +def test_protocol_cancel_and_cross_generation_errors_never_trigger_rerun(tmp_path, fault): + calls = [] + async def run(generation): + calls.append(generation) + if fault == 'protocol': + raise ValueError('task lock mismatch') + if fault == 'cancel': + raise asyncio.CancelledError + return result(0, generation + (fault == 'old-generation'), + version='2' if fault == 'stale-policy' else '1') + with pytest.raises(asyncio.CancelledError if fault == 'cancel' else ValueError): + asyncio.run(GenerationJournal(tmp_path).execute(0, {}, '1', run)) + assert calls == [0] + assert not (tmp_path / 'rollout-generations/rollout-0/selected.json').exists() + assert (tmp_path / 'rollout-generations/rollout-0/generation-0/failed.json').exists() + + +def test_concurrent_reservations_and_restart_cannot_exceed_rollout_budget(tmp_path): + owner = Identity('run', 'rollout-0-generation-0', 'group', '0', 'attempt', 'trajectory', + 'd' * 64, '1', 'h' * 64, 'r' * 64, 's' * 64) + def reserve(index): + try: + reserve_generation_attempt(tmp_path, replace(owner, attempt_id=f'attempt-{index}'), + {'max_attempts': 3, 'max_failed_groups': 2}) + return True + except RetryableRolloutFailure: + return False + with ThreadPoolExecutor(max_workers=8) as pool: + outcomes = list(pool.map(reserve, range(16))) + assert sum(outcomes) == 3 + assert reserve(17) is False + + +@pytest.mark.parametrize('fault', ['empty', 'duplicate', 'mutated-input', 'export-audit']) +def test_invalid_generation_is_journaled_and_never_selected(tmp_path, fault): + inputs, discarded = {}, [] + async def run(generation): + output = result(0, generation) + if fault == 'empty': + return [] + if fault == 'duplicate': + output[1] = output[0] + if fault == 'mutated-input': + inputs['sampling'] = 'changed' + return output + def audit(_): + if fault == 'export-audit': + raise ValueError('training export audit rejected') + with pytest.raises(ValueError): + asyncio.run(GenerationJournal(tmp_path).execute(0, inputs, '1', run, + validate=audit, discard=lambda: discarded.append(True))) + assert discarded == [True] + assert not (tmp_path / 'rollout-generations/rollout-0/selected.json').exists() + + +def test_generation_limits_cannot_increase_on_a_new_batch_or_worker_restart(tmp_path): + GenerationJournal(tmp_path) + with pytest.raises(ValueError, match='conflicting immutable record'): + GenerationJournal(tmp_path, GenerationPolicy(max_reruns_per_seed=3)) + owner = Identity('run', 'rollout-0-generation-0', 'group', '0', 'attempt', 'trajectory', + 'd' * 64, '1', 'h' * 64, 'r' * 64, 's' * 64) + reserve_generation_attempt(tmp_path, owner, {'max_attempts': 1, 'max_failed_groups': 2}) + with pytest.raises(ValueError, match='conflicting immutable record'): + reserve_generation_attempt(tmp_path, replace(owner, attempt_id='new'), + {'max_attempts': 2, 'max_failed_groups': 2}) diff --git a/tests/harborrl/test_rollout_runtime.py b/tests/harborrl/test_rollout_runtime.py index e51fab2b7..5f0b408f4 100644 --- a/tests/harborrl/test_rollout_runtime.py +++ b/tests/harborrl/test_rollout_runtime.py @@ -1,339 +1,371 @@ -"""Extracted rollout core (P2): config mapping, slot scheduling, boundaries.""" -from __future__ import annotations - -import asyncio -import json -from pathlib import Path -from types import SimpleNamespace - -import pytest - - -def test_runtime_config_maps_environment(tmp_path, monkeypatch): - from harborrl.rollout.runtime import RolloutRuntimeConfig - - environment = { - "RUN_ID": "run-1", "RUN_DIR": str(tmp_path), - "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), - "HARBORRL_NATIVE_PROFILE": str(tmp_path / "profile.json"), - "HARBORRL_NATIVE_GATEWAY_HOST": "127.0.0.1", - "HARBORRL_NATIVE_GATEWAY_PORT": "49183", - "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:49183", - "HARBORRL_NATIVE_RUNNER_PYTHON": "/runner/python", - "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), - "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps({"task": "worker-b"}), - "HARBORRL_NATIVE_MAX_ATTEMPTS": "3", - "ROLLOUT_MAX_RESPONSE_LEN": "128", - "ROLLOUT_MAX_CONTEXT_LEN": "1024", - "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, - "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, - "HARBORRL_NATIVE_AUDITED_LOGPROBS": "1", - "HARBORRL_NATIVE_DRAIN_TIMEOUT": "5", - "MODEL_TAG": "qwen3-8B", - "HARBORRL_TRAINING_SEED": "0", - } - for key, value in environment.items(): - monkeypatch.setenv(key, value) - config = RolloutRuntimeConfig.from_environment( - environment, endpoint="http://router:30000/", concurrency_limit=4, group_size=2) - assert config.workers == ("worker-a", "worker-b") - assert config.task_worker_overrides == {"task": "worker-b"} - assert config.max_attempts == 3 and config.max_output_tokens == 128 - assert config.endpoint == "http://router:30000" - assert config.sampling_seed == 0 - assert config.environment()['HARBORRL_TRAINING_SEED'] == '0' - assert config.environment()["HARBORRL_NATIVE_RUNNER_WORKERS"] == \ - json.dumps(["worker-a", "worker-b"]) - with pytest.raises(ValueError, match="group size"): - RolloutRuntimeConfig.from_environment(environment, endpoint="x", concurrency_limit=1, - group_size=1) - stripped = dict(environment) - stripped.pop("HARBORRL_NATIVE_RUNNER_WORKERS") - with pytest.raises(ValueError, match="RUNNER_WORKERS"): - RolloutRuntimeConfig.from_environment(stripped, endpoint="x", - concurrency_limit=1, group_size=2) - - -def test_runtime_binds_gateway_with_registry_and_backend(tmp_path, monkeypatch): - from harborrl.gateway import server as gateway_server - from harborrl.gateway import sglang_backend, trace - from harborrl.rollout import runtime as rollout_runtime - - catalog = tmp_path / "catalog.json" - catalog.write_text("[]") - profile = tmp_path / "profile.json" - profile.write_text(json.dumps({"model": "policy"})) - tokenizer = SimpleNamespace( - apply_chat_template=lambda *args, **kwargs: [1, 2], - get_vocab=lambda: {"token": 1}, - ) - tokenizer_digest, template_digest = rollout_runtime.tokenizer_fingerprint(tokenizer) - environment = { - "RUN_DIR": str(tmp_path), "RUN_ID": "run-1", - "HARBORRL_NATIVE_CATALOG": str(catalog), - "HARBORRL_NATIVE_PROFILE": str(profile), - "HARBORRL_NATIVE_TOKENIZER_DIGEST": tokenizer_digest, - "HARBORRL_NATIVE_TEMPLATE_DIGEST": template_digest, - "HARBORRL_NATIVE_GATEWAY_HOST": "127.0.0.1", - "HARBORRL_NATIVE_GATEWAY_PORT": "49183", - "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:49183", - "HARBORRL_NATIVE_RUNNER_PYTHON": "/runner/python", - "HARBORRL_NATIVE_RUNNER_WORKERS": '["worker-a"]', - "ROLLOUT_MAX_RESPONSE_LEN": "128", - "ROLLOUT_MAX_CONTEXT_LEN": "1024", - } - for key, value in environment.items(): - monkeypatch.setenv(key, value) - - calls = {} - - class FakeGateway: - def __init__(self, registry, backend, *, model, max_output_tokens): - calls["gateway"] = (registry, backend, model, max_output_tokens) - calls["gateway_object"] = self - - class FakeServer: - def serve_forever(self): - pass - - def shutdown(self): - pass - - def server_close(self): - pass - - class FakeTraceRegistry: - def __init__(self, path): - calls["registry_path"] = path - - class FakeBackend: - def __init__(self, *args, **kwargs): - calls["backend_args"] = (args, kwargs) - - def weight_version(self): - return "7" - - def fake_make_server(gateway, host, port, *, max_inflight=None): - calls["server"] = (gateway, host, port) - calls["server_max_inflight"] = max_inflight - return FakeServer() - - monkeypatch.setattr(gateway_server, "Gateway", FakeGateway) - monkeypatch.setattr(gateway_server, "make_server", fake_make_server) - monkeypatch.setattr(sglang_backend, "SGLangBackend", FakeBackend) - monkeypatch.setattr(trace, "TraceRegistry", FakeTraceRegistry) - - config = rollout_runtime.RolloutRuntimeConfig.from_environment( - environment, endpoint="http://127.0.0.1:30000", concurrency_limit=4, group_size=2) - runtime_ = rollout_runtime.RolloutRuntime(config, tokenizer) - try: - assert calls["gateway"][2:] == ("policy", 128) - assert calls["server"][0] is calls["gateway_object"] - assert calls["server"][1:] == ("127.0.0.1", 49183) - # The implicit single gateway keeps the historical trace layout. - assert calls["registry_path"] == runtime_.run_root / "native-traces" - # Twice the scheduler budget (concurrency_limit=4) with a floor of 4. - assert calls["server_max_inflight"] == 8 - assert calls["backend_args"][0][0] == "http://127.0.0.1:30000" - assert runtime_.backend.weight_version() == "7" - finally: - runtime_.close() - - # A tokenizer that disagrees with the native lock fails closed. - other = SimpleNamespace(apply_chat_template=lambda *a, **k: [9], - get_vocab=lambda: {"other": 2}) - with pytest.raises(ValueError, match="digest"): - rollout_runtime.RolloutRuntime(config, other) - - -def test_policy_identity_uses_synchronized_pool_version(tmp_path, monkeypatch): - from harborrl.rollout import runtime as rollout_runtime - - class Backend: - endpoint = "http://router:30000" - - def pool_states(self): - return [{"endpoint": self.endpoint, "healthy": True, "weight_version": "2"}] - - class Registry: - def __init__(self): - self.published = None - - def drain(self, timeout): - self.timeout = timeout - - def publish_version(self, states, expected): - self.published = (states, expected) - - monkeypatch.setenv("RUN_DIR", str(tmp_path)) - registry = Registry() - runtime_ = SimpleNamespace(run_root=tmp_path, backend=Backend(), registry=registry, - config=SimpleNamespace(drain_timeout=30)) - assert rollout_runtime.current_policy_version(runtime_) == "2" - payload = json.loads((tmp_path / "policy-pool.json").read_text()) - assert payload["weight_version"] == "2" - assert registry.published[1] == "2" - assert registry.timeout == 30 - - -def test_group_shares_slot_state_and_shifts_retry_workers(tmp_path, monkeypatch): - from harborrl.rollout import runtime as rollout_runtime - - entry = {"id": "task", "revision": "1", "path": "/task", "task_digest": "d" * 64, - "reward_profile": {"key": "reward", "scale": 1.0, "offset": 0.0, - "raw_range": [0.0, 1.0]}} - profile = tmp_path / "profile.json" - profile.write_text(json.dumps({"model": "policy"})) - environment = { - "RUN_ID": "run", "RUN_DIR": str(tmp_path), "HARBORRL_NATIVE_PROFILE": str(profile), - "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), - "HARBORRL_NATIVE_MAX_ATTEMPTS": "2", - "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:32123", - "HARBORRL_NATIVE_GATEWAY_PORT": "32123", - # Fake runtimes carry no lease bookkeeping: pin static routing. - "HARBORRL_NATIVE_GATEWAY_ROUTING": "modulo", - "HARBORRL_NATIVE_RUNNER_PYTHON": "/python", - "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), - "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, - "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, - } - for key, value in environment.items(): - monkeypatch.setenv(key, value) - config = rollout_runtime.RolloutRuntimeConfig.from_environment( - environment, endpoint="http://router:30000", concurrency_limit=8, group_size=4) - - class FakeSlots: - max_attempts = 2 - - def __init__(self): - self.started = {} - - def start(self, slot): - self.started[slot] = self.started.get(slot, 0) + 1 - return SimpleNamespace(attempt_id=f"{slot}-{self.started[slot]}", - group_id="group-0", slot_id=slot, - attempt_no=self.started[slot]) - - def finish(self, slot, ir=None, error=None): - assert (ir is None) != (error is None) - - created_groups = [] - - def fake_group_slots(identities, *, max_attempts=2): - created_groups.append(identities) - return FakeSlots() - - calls = [] - - async def fake_run_attempt(identity, *, runner_host, **kwargs): - calls.append((identity.slot_id, runner_host)) - if identity.slot_id == "1" and identity.attempt_no == 1: - raise RuntimeError("simulated first-attempt failure") - return {"identity": identity.__dict__} - - monkeypatch.setattr(rollout_runtime, "GroupSlots", fake_group_slots) - monkeypatch.setattr(rollout_runtime, "run_attempt", fake_run_attempt) - - runtime_ = SimpleNamespace( - rollout_root=tmp_path, semaphore=asyncio.Semaphore(8), - shards=(SimpleNamespace(name="gateway", url="http://gateway:32123", - registry=SimpleNamespace()),), - profile={"model": "policy"}) - - # The run owns its loaded profile; group setup must not reread the source file. - profile.unlink() - results = asyncio.run(rollout_runtime.run_group( - config, runtime_, entry=entry, group_index=0, rollout_id=0, - sampling_digest="sampling", policy_version="1")) - assert len(results) == 4 - assert len(created_groups) == 1 - assert len(created_groups[0]) == 4 - assert {item.harness_digest for item in created_groups[0]} == { - rollout_runtime.digest(runtime_.profile)} - by_slot = {} - for slot, host in calls: - by_slot.setdefault(slot, []).append(host) - assert by_slot == {"0": ["worker-a"], "1": ["worker-b", "worker-a"], - "2": ["worker-a"], "3": ["worker-b"]} - - -def test_task_worker_override_wins(tmp_path, monkeypatch): - from harborrl.rollout import runtime as rollout_runtime - - entry = {"id": "task", "revision": "1", "path": "/task", "task_digest": "d" * 64, - "reward_profile": {"key": "reward"}} - profile = tmp_path / "profile.json" - profile.write_text(json.dumps({"model": "policy"})) - environment = { - "RUN_ID": "run", "RUN_DIR": str(tmp_path), "HARBORRL_NATIVE_PROFILE": str(profile), - "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), - "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps({"task": "worker-b"}), - "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:32123", - "HARBORRL_NATIVE_GATEWAY_PORT": "32123", "HARBORRL_NATIVE_RUNNER_PYTHON": "/python", - # Fake runtimes carry no lease bookkeeping: pin static routing. - "HARBORRL_NATIVE_GATEWAY_ROUTING": "modulo", - "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), - "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, - "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, - } - for key, value in environment.items(): - monkeypatch.setenv(key, value) - config = rollout_runtime.RolloutRuntimeConfig.from_environment( - environment, endpoint="http://router:30000", concurrency_limit=2, group_size=2) - - seen = [] - - class PermissiveSlots: - max_attempts = 2 - - def __init__(self, identities, *, max_attempts=2): - self.identities = {identity.slot_id: identity for identity in identities} - - def start(self, slot): - return self.identities[slot] - - def finish(self, slot, ir=None, error=None): - assert (ir is None) != (error is None) - - async def fake_run_attempt(identity, *, runner_host, **kwargs): - seen.append(runner_host) - return {"identity": identity.to_dict()} - - monkeypatch.setattr(rollout_runtime, "GroupSlots", PermissiveSlots) - monkeypatch.setattr(rollout_runtime, "run_attempt", fake_run_attempt) - runtime_ = SimpleNamespace( - rollout_root=tmp_path, semaphore=asyncio.Semaphore(2), - shards=(SimpleNamespace(name="gateway", url="http://gateway:32123", - registry=SimpleNamespace()),), - profile={"model": "policy"}) - irs = asyncio.run(rollout_runtime.run_group( - config, runtime_, entry=entry, group_index=0, rollout_id=0, - sampling_digest="sampling", policy_version="1")) - assert len(irs) == 2 - assert seen == ["worker-b", "worker-b"] - - -def test_rollout_core_does_not_import_training_frameworks(): - import re - - import harborrl.rollout - - root = Path(harborrl.rollout.__file__).parent - offenders = [] - for path in sorted(root.rglob("*.py")): - for number, line in enumerate(path.read_text().splitlines(), 1): - if re.match(r"\s*(from|import)\s+(slime|ray)(\.|\s|$)", line): - offenders.append(f"{path.relative_to(root)}:{number}: {line.strip()}") - assert not offenders, "rollout core must stay framework-free: " + "; ".join(offenders) - - -def test_native_generate_shim_reexports_the_core(): - from harborrl import rollout as package - from harborrl.rollout import native_generate, runtime - - for name in ("NativeRolloutRuntime", "RolloutRuntime", "RolloutRuntimeConfig", - "close_runtime", "current_policy_version", "publish_native_version", - "run_attempt", "run_group", "run_slot", "runtime", "task_entry", - "tokenizer_fingerprint", "GroupSlots"): - assert getattr(native_generate, name) is getattr(runtime, name), name - assert package.native_generate.__doc__ is not None +"""Extracted rollout core (P2): config mapping, slot scheduling, boundaries.""" +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +def test_runtime_config_maps_environment(tmp_path, monkeypatch): + from harborrl.rollout.runtime import RolloutRuntimeConfig + + environment = { + "RUN_ID": "run-1", "RUN_DIR": str(tmp_path), + "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), + "HARBORRL_NATIVE_PROFILE": str(tmp_path / "profile.json"), + "HARBORRL_NATIVE_GATEWAY_HOST": "127.0.0.1", + "HARBORRL_NATIVE_GATEWAY_PORT": "49183", + "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:49183", + "HARBORRL_NATIVE_RUNNER_PYTHON": "/runner/python", + "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), + "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps({"task": "worker-b"}), + "HARBORRL_NATIVE_MAX_ATTEMPTS": "3", + "ROLLOUT_MAX_RESPONSE_LEN": "128", + "ROLLOUT_MAX_CONTEXT_LEN": "1024", + "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, + "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, + "HARBORRL_NATIVE_AUDITED_LOGPROBS": "1", + "HARBORRL_NATIVE_DRAIN_TIMEOUT": "5", + "MODEL_TAG": "qwen3-8B", + "HARBORRL_TRAINING_SEED": "0", + } + for key, value in environment.items(): + monkeypatch.setenv(key, value) + config = RolloutRuntimeConfig.from_environment( + environment, endpoint="http://router:30000/", concurrency_limit=4, group_size=2) + assert config.workers == ("worker-a", "worker-b") + assert config.task_worker_overrides == {"task": "worker-b"} + assert config.max_attempts == 3 and config.max_output_tokens == 128 + assert config.endpoint == "http://router:30000" + assert config.sampling_seed == 0 + assert config.environment()['HARBORRL_TRAINING_SEED'] == '0' + assert config.environment()["HARBORRL_NATIVE_RUNNER_WORKERS"] == \ + json.dumps(["worker-a", "worker-b"]) + with pytest.raises(ValueError, match="group size"): + RolloutRuntimeConfig.from_environment(environment, endpoint="x", concurrency_limit=1, + group_size=1) + stripped = dict(environment) + stripped.pop("HARBORRL_NATIVE_RUNNER_WORKERS") + with pytest.raises(ValueError, match="RUNNER_WORKERS"): + RolloutRuntimeConfig.from_environment(stripped, endpoint="x", + concurrency_limit=1, group_size=2) + + +def test_runtime_binds_gateway_with_registry_and_backend(tmp_path, monkeypatch): + from harborrl.gateway import server as gateway_server + from harborrl.gateway import sglang_backend, trace + from harborrl.rollout import runtime as rollout_runtime + + catalog = tmp_path / "catalog.json" + catalog.write_text("[]") + profile = tmp_path / "profile.json" + profile.write_text(json.dumps({"model": "policy"})) + tokenizer = SimpleNamespace( + apply_chat_template=lambda *args, **kwargs: [1, 2], + get_vocab=lambda: {"token": 1}, + ) + tokenizer_digest, template_digest = rollout_runtime.tokenizer_fingerprint(tokenizer) + environment = { + "RUN_DIR": str(tmp_path), "RUN_ID": "run-1", + "HARBORRL_NATIVE_CATALOG": str(catalog), + "HARBORRL_NATIVE_PROFILE": str(profile), + "HARBORRL_NATIVE_TOKENIZER_DIGEST": tokenizer_digest, + "HARBORRL_NATIVE_TEMPLATE_DIGEST": template_digest, + "HARBORRL_NATIVE_GATEWAY_HOST": "127.0.0.1", + "HARBORRL_NATIVE_GATEWAY_PORT": "49183", + "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:49183", + "HARBORRL_NATIVE_RUNNER_PYTHON": "/runner/python", + "HARBORRL_NATIVE_RUNNER_WORKERS": '["worker-a"]', + "ROLLOUT_MAX_RESPONSE_LEN": "128", + "ROLLOUT_MAX_CONTEXT_LEN": "1024", + } + for key, value in environment.items(): + monkeypatch.setenv(key, value) + + calls = {} + + class FakeGateway: + def __init__(self, registry, backend, *, model, max_output_tokens): + calls["gateway"] = (registry, backend, model, max_output_tokens) + calls["gateway_object"] = self + + class FakeServer: + def serve_forever(self): + pass + + def shutdown(self): + pass + + def server_close(self): + pass + + class FakeTraceRegistry: + def __init__(self, path): + calls["registry_path"] = path + + class FakeBackend: + def __init__(self, *args, **kwargs): + calls["backend_args"] = (args, kwargs) + + def weight_version(self): + return "7" + + def fake_make_server(gateway, host, port, *, max_inflight=None): + calls["server"] = (gateway, host, port) + calls["server_max_inflight"] = max_inflight + return FakeServer() + + monkeypatch.setattr(gateway_server, "Gateway", FakeGateway) + monkeypatch.setattr(gateway_server, "make_server", fake_make_server) + monkeypatch.setattr(sglang_backend, "SGLangBackend", FakeBackend) + monkeypatch.setattr(trace, "TraceRegistry", FakeTraceRegistry) + + config = rollout_runtime.RolloutRuntimeConfig.from_environment( + environment, endpoint="http://127.0.0.1:30000", concurrency_limit=4, group_size=2) + runtime_ = rollout_runtime.RolloutRuntime(config, tokenizer) + try: + assert calls["gateway"][2:] == ("policy", 128) + assert calls["server"][0] is calls["gateway_object"] + assert calls["server"][1:] == ("127.0.0.1", 49183) + # The implicit single gateway keeps the historical trace layout. + assert calls["registry_path"] == runtime_.run_root / "native-traces" + # Twice the scheduler budget (concurrency_limit=4) with a floor of 4. + assert calls["server_max_inflight"] == 8 + assert calls["backend_args"][0][0] == "http://127.0.0.1:30000" + assert runtime_.backend.weight_version() == "7" + finally: + runtime_.close() + + # A tokenizer that disagrees with the native lock fails closed. + other = SimpleNamespace(apply_chat_template=lambda *a, **k: [9], + get_vocab=lambda: {"other": 2}) + with pytest.raises(ValueError, match="digest"): + rollout_runtime.RolloutRuntime(config, other) + + +def test_policy_identity_uses_synchronized_pool_version(tmp_path, monkeypatch): + from harborrl.rollout import runtime as rollout_runtime + + class Backend: + endpoint = "http://router:30000" + + def pool_states(self): + return [{"endpoint": self.endpoint, "healthy": True, "weight_version": "2"}] + + class Registry: + def __init__(self): + self.published = None + + def drain(self, timeout): + self.timeout = timeout + + def publish_version(self, states, expected): + self.published = (states, expected) + + monkeypatch.setenv("RUN_DIR", str(tmp_path)) + registry = Registry() + runtime_ = SimpleNamespace(run_root=tmp_path, backend=Backend(), registry=registry, + config=SimpleNamespace(drain_timeout=30)) + assert rollout_runtime.current_policy_version(runtime_) == "2" + payload = json.loads((tmp_path / "policy-pool.json").read_text()) + assert payload["weight_version"] == "2" + assert registry.published[1] == "2" + assert registry.timeout == 30 + + +def test_group_shares_slot_state_and_shifts_retry_workers(tmp_path, monkeypatch): + from harborrl.rollout import runtime as rollout_runtime + + entry = {"id": "task", "revision": "1", "path": "/task", "task_digest": "d" * 64, + "reward_profile": {"key": "reward", "scale": 1.0, "offset": 0.0, + "raw_range": [0.0, 1.0]}} + profile = tmp_path / "profile.json" + profile.write_text(json.dumps({"model": "policy"})) + environment = { + "RUN_ID": "run", "RUN_DIR": str(tmp_path), "HARBORRL_NATIVE_PROFILE": str(profile), + "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), + "HARBORRL_NATIVE_MAX_ATTEMPTS": "2", + "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:32123", + "HARBORRL_NATIVE_GATEWAY_PORT": "32123", + # Fake runtimes carry no lease bookkeeping: pin static routing. + "HARBORRL_NATIVE_GATEWAY_ROUTING": "modulo", + "HARBORRL_NATIVE_RUNNER_PYTHON": "/python", + "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), + "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, + "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, + } + for key, value in environment.items(): + monkeypatch.setenv(key, value) + config = rollout_runtime.RolloutRuntimeConfig.from_environment( + environment, endpoint="http://router:30000", concurrency_limit=8, group_size=4) + + class FakeSlots: + max_attempts = 2 + + def __init__(self): + self.started = {} + + def start(self, slot): + self.started[slot] = self.started.get(slot, 0) + 1 + return SimpleNamespace(attempt_id=f"{slot}-{self.started[slot]}", + group_id="group-0", slot_id=slot, + attempt_no=self.started[slot]) + + def finish(self, slot, ir=None, error=None): + assert (ir is None) != (error is None) + + created_groups = [] + + def fake_group_slots(identities, *, max_attempts=2): + created_groups.append(identities) + return FakeSlots() + + calls = [] + + async def fake_run_attempt(identity, *, runner_host, **kwargs): + calls.append((identity.slot_id, runner_host)) + if identity.slot_id == "1" and identity.attempt_no == 1: + raise RuntimeError("simulated first-attempt failure") + return {"identity": identity.__dict__} + + monkeypatch.setattr(rollout_runtime, "GroupSlots", fake_group_slots) + monkeypatch.setattr(rollout_runtime, "run_attempt", fake_run_attempt) + + runtime_ = SimpleNamespace( + rollout_root=tmp_path, semaphore=asyncio.Semaphore(8), + shards=(SimpleNamespace(name="gateway", url="http://gateway:32123", + registry=SimpleNamespace()),), + profile={"model": "policy"}) + + # The run owns its loaded profile; group setup must not reread the source file. + profile.unlink() + results = asyncio.run(rollout_runtime.run_group( + config, runtime_, entry=entry, group_index=0, rollout_id=0, + sampling_digest="sampling", policy_version="1")) + assert len(results) == 4 + assert len(created_groups) == 1 + assert len(created_groups[0]) == 4 + assert {item.harness_digest for item in created_groups[0]} == { + rollout_runtime.digest(runtime_.profile)} + by_slot = {} + for slot, host in calls: + by_slot.setdefault(slot, []).append(host) + assert by_slot == {"0": ["worker-a"], "1": ["worker-b", "worker-a"], + "2": ["worker-a"], "3": ["worker-b"]} + + +def test_task_worker_override_wins(tmp_path, monkeypatch): + from harborrl.rollout import runtime as rollout_runtime + + entry = {"id": "task", "revision": "1", "path": "/task", "task_digest": "d" * 64, + "reward_profile": {"key": "reward"}} + profile = tmp_path / "profile.json" + profile.write_text(json.dumps({"model": "policy"})) + environment = { + "RUN_ID": "run", "RUN_DIR": str(tmp_path), "HARBORRL_NATIVE_PROFILE": str(profile), + "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(["worker-a", "worker-b"]), + "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps({"task": "worker-b"}), + "HARBORRL_NATIVE_GATEWAY_URL": "http://gateway:32123", + "HARBORRL_NATIVE_GATEWAY_PORT": "32123", "HARBORRL_NATIVE_RUNNER_PYTHON": "/python", + # Fake runtimes carry no lease bookkeeping: pin static routing. + "HARBORRL_NATIVE_GATEWAY_ROUTING": "modulo", + "HARBORRL_NATIVE_CATALOG": str(tmp_path / "catalog.json"), + "HARBORRL_NATIVE_TOKENIZER_DIGEST": "0" * 64, + "HARBORRL_NATIVE_TEMPLATE_DIGEST": "1" * 64, + } + for key, value in environment.items(): + monkeypatch.setenv(key, value) + config = rollout_runtime.RolloutRuntimeConfig.from_environment( + environment, endpoint="http://router:30000", concurrency_limit=2, group_size=2) + + seen = [] + + class PermissiveSlots: + max_attempts = 2 + + def __init__(self, identities, *, max_attempts=2): + self.identities = {identity.slot_id: identity for identity in identities} + + def start(self, slot): + return self.identities[slot] + + def finish(self, slot, ir=None, error=None): + assert (ir is None) != (error is None) + + async def fake_run_attempt(identity, *, runner_host, **kwargs): + seen.append(runner_host) + return {"identity": identity.to_dict()} + + monkeypatch.setattr(rollout_runtime, "GroupSlots", PermissiveSlots) + monkeypatch.setattr(rollout_runtime, "run_attempt", fake_run_attempt) + runtime_ = SimpleNamespace( + rollout_root=tmp_path, semaphore=asyncio.Semaphore(2), + shards=(SimpleNamespace(name="gateway", url="http://gateway:32123", + registry=SimpleNamespace()),), + profile={"model": "policy"}) + irs = asyncio.run(rollout_runtime.run_group( + config, runtime_, entry=entry, group_index=0, rollout_id=0, + sampling_digest="sampling", policy_version="1")) + assert len(irs) == 2 + assert seen == ["worker-b", "worker-b"] + + +def test_rollout_core_does_not_import_training_frameworks(): + import re + + import harborrl.rollout + + root = Path(harborrl.rollout.__file__).parent + offenders = [] + for path in sorted(root.rglob("*.py")): + for number, line in enumerate(path.read_text().splitlines(), 1): + if re.match(r"\s*(from|import)\s+(slime|ray)(\.|\s|$)", line): + offenders.append(f"{path.relative_to(root)}:{number}: {line.strip()}") + assert not offenders, "rollout core must stay framework-free: " + "; ".join(offenders) + + +def test_native_generate_shim_reexports_the_core(): + from harborrl import rollout as package + from harborrl.rollout import native_generate, runtime + + for name in ("NativeRolloutRuntime", "RolloutRuntime", "RolloutRuntimeConfig", + "close_runtime", "current_policy_version", "publish_native_version", + "run_attempt", "run_group", "run_slot", "runtime", "task_entry", + "tokenizer_fingerprint", "GroupSlots"): + assert getattr(native_generate, name) is getattr(runtime, name), name + assert package.native_generate.__doc__ is not None + + +@pytest.mark.parametrize('terminal', ['protocol', 'cleanup']) +def test_group_terminal_sibling_failure_vetoes_generation_rerun(tmp_path, monkeypatch, terminal): + from harborrl.rollout import runtime as rollout_runtime + from harborrl.rollout.harbor_job.reliability import ( + CleanupUnresolved, + RetryableRolloutFailure, + ) + + started = asyncio.Event() + async def slot(config, runtime_, slots, index, entry, reward): + if index == 0: + await started.wait() + raise RetryableRolloutFailure('infrastructure exhausted') + started.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + if terminal == 'cleanup': + runtime_.sandbox_admission.blocked = True + raise CleanupUnresolved('independent cleanup failed') from None + raise ValueError('task lock mismatch discovered during cleanup') from None + + monkeypatch.setattr(rollout_runtime, '_run_slot', slot) + monkeypatch.setattr(rollout_runtime, '_group_slots', lambda *args: (object(), None)) + runtime_ = SimpleNamespace(sandbox_admission=SimpleNamespace(blocked=False)) + error = CleanupUnresolved if terminal == 'cleanup' else ValueError + with pytest.raises(error): + asyncio.run(rollout_runtime.run_group( + SimpleNamespace(group_size=2), runtime_, entry={}, group_index=0, + rollout_id=0, sampling_digest='s', policy_version='1')) diff --git a/tests/harborrl/test_rollout_runtime_lifecycle.py b/tests/harborrl/test_rollout_runtime_lifecycle.py index 29ec250ec..d63a5c13c 100644 --- a/tests/harborrl/test_rollout_runtime_lifecycle.py +++ b/tests/harborrl/test_rollout_runtime_lifecycle.py @@ -86,6 +86,58 @@ def test_cached_runtime_rejects_foreign_loop_and_config(tmp_path, monkeypatch): runtime.close_runtime() +def test_slime_hook_reuses_runtime_across_rollouts_and_closes_after_failure(tmp_path, monkeypatch): + from harborrl.backends.slime_v032 import rollout + + runtime.close_runtime() + config, tokenizer = cached_runtime_fixture(tmp_path, monkeypatch) + args = SimpleNamespace(rollout_batch_size=1, n_samples_per_prompt=2) + source = SimpleNamespace(get_samples=lambda _: [[object(), object()]]) + seen, loops, completed = [], [], [] + fail = False + + async def runner(args_, groups, policy_version): + current = await runtime.runtime(config, tokenizer=tokenizer) + seen.append(current) + loops.append(asyncio.get_running_loop()) + + async def slot(index): + async with current.semaphore: + await asyncio.sleep(.001) + completed.append(index) + + await asyncio.gather(slot(0), slot(1)) + if fail: + raise ValueError('rollout failed') + return [] + + monkeypatch.setattr(rollout, 'lock_policy_version', lambda _: '1') + monkeypatch.setattr(rollout, 'export_training_batch', lambda *a, **k: object()) + monkeypatch.setattr(rollout, 'to_slime_samples', lambda *a, **k: []) + monkeypatch.setattr(rollout, 'collect_metrics', lambda *a, **k: {}) + + def generate(index): + return rollout.generate_rollout(args, index, source, runner=runner, + output_factory=SimpleNamespace) + + try: + for index in range(3): + assert generate(index).samples == [] + assert len({id(item) for item in seen}) == 1 + assert len({id(loop) for loop in loops}) == 1 + assert completed == [0, 1] * 3 + fail = True + with pytest.raises(ValueError, match='rollout failed'): + generate(3) + assert loops[0].is_closed() + assert runtime._RUNTIME is None and runtime._EMBEDDED_LOOP is None + fail = False + generate(4) + assert seen[-1] is not seen[0] and loops[-1] is not loops[0] + finally: + runtime.close_runtime() + + def test_embedded_shutdown_awaits_tasks_before_closing_gateway(monkeypatch): runtime.close_runtime() events = [] diff --git a/tests/harborrl/test_sandbox_reconciliation.py b/tests/harborrl/test_sandbox_reconciliation.py new file mode 100644 index 000000000..7e49bdeab --- /dev/null +++ b/tests/harborrl/test_sandbox_reconciliation.py @@ -0,0 +1,392 @@ +import asyncio +import json +import os +import socket +import subprocess +import sys +from pathlib import Path + +import httpx +import pytest + +from harborrl.rollout.harbor_job.reconcile import ( + cleanup_debt, + cleanup_resolved, + close_owned_processes, + owned_processes, + process_info, + processes_verified_absent, + reconcile_instance, +) +from harborrl.rollout.harbor_job.sandbox_config import SandboxAdmission +from harborrl.trajectories.native import digest, publish + + +def config(): + return {'domain': 'https://sandbox.test', 'cleanup_timeout_s': .08, 'request_timeout_s': .03} + + +def process_proof(): + return {'verified_absent': True, 'observations': [{'signal': None, 'processes': []}]} + + +def run_reconciliation(handler, *, lifecycle=None, proof=None): + cfg = config() + lifecycle = lifecycle or {'runtime_digest': digest(cfg), 'sandbox_id': 'owned', 'state': 'deleted'} + return asyncio.run(reconcile_instance(cfg, lifecycle, params={'project': 'test'}, + credential='test-secret', process_proof=proof if proof is not None else process_proof(), + transport=httpx.MockTransport(handler), retry_interval=.001)) + + +def test_delete_acknowledgement_is_not_independent_absence(): + calls = [] + def handler(request): + calls.append(request.method) + return httpx.Response(204 if request.method == 'DELETE' else 200) + result = run_reconciliation(handler) + assert result['status'] == 'unresolved' + assert 'DELETE' in calls and not result.get('get404') + assert 'test-secret' not in json.dumps(result) + + +def test_cleanup_retries_delete_and_complete_inventory_with_owned_id_only(): + calls, gets, inventories = [], 0, 0 + def handler(request): + nonlocal gets, inventories + assert request.url.params['project'] == 'test' + calls.append((request.method, request.url.path)) + if request.url.path.endswith('/owned'): + if request.method == 'DELETE': + return httpx.Response(503 if gets == 1 else 204) + gets += 1 + return httpx.Response(200 if gets <= 2 else 404) + inventories += 1 + if inventories == 1: + return httpx.Response(503) + return httpx.Response(200, json={'items': [{'id': 'someone-else'}], + 'pagination': {'hasNextPage': False, 'totalItems': 1}}) + result = run_reconciliation(handler) + assert result['status'] == 'verified_absent' + assert result['inventory_ids'] == ['someone-else'] + assert result['inventory_complete'] and result['get404'] + assert all(path.endswith('/owned') for method, path in calls if method == 'DELETE') + + +@pytest.mark.parametrize('kind', ['stale', 'missing-pagination', 'lying-total', 'repeated-page']) +def test_stale_or_incomplete_inventory_never_releases_capacity(kind): + def handler(request): + if request.url.path.endswith('/owned'): + return httpx.Response(404) + data = {'items': [{'id': 'owned'}], 'pagination': {'hasNextPage': False, 'totalItems': 1}} + if kind == 'missing-pagination': + data.pop('pagination') + elif kind == 'lying-total': + data['pagination']['totalItems'] = 5 + elif kind == 'repeated-page': + data['pagination'].update(hasNextPage=True, totalItems=2) + return httpx.Response(200, json=data) + assert run_reconciliation(handler)['status'] == 'unresolved' + + +def test_complete_paginated_inventory_is_required(): + pages = [] + def handler(request): + if request.url.path.endswith('/owned'): + return httpx.Response(404) + page = int(request.url.params['page']) + pages.append(page) + return httpx.Response(200, json={'items': [{'id': f'other-{page}'}], + 'pagination': {'hasNextPage': page == 1, 'totalItems': 2}}) + result = run_reconciliation(handler) + assert result['status'] == 'verified_absent' and pages == [1, 2] + assert result['inventory_ids'] == ['other-1', 'other-2'] + + +def test_unknown_allocation_and_surviving_processes_fail_closed(): + def handler(request): + pytest.fail('must not query or delete unowned allocations') + cfg = config() + result = run_reconciliation(handler, lifecycle={ + 'runtime_digest': digest(cfg), 'state': 'creation_unknown', 'sandbox_id': None}) + assert result['status'] == 'unresolved' + result = run_reconciliation(handler, proof={'verified_absent': False}) + assert result['status'] == 'unresolved' + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process/session observer') +def test_observer_closes_owned_runner_and_child_without_killing_other_processes(): + code = "import os,subprocess,time; child=subprocess.Popen(['sleep','60']); print(child.pid,flush=True); time.sleep(60)" + process = subprocess.Popen([sys.executable, '-c', code], start_new_session=True, + env={**os.environ, 'HARBORRL_ATTEMPT_ID': 'cleanup-test'}, stdout=subprocess.PIPE, text=True) + child = int(process.stdout.readline()) + try: + owner = {**process_info(process.pid), 'host': socket.gethostname(), 'attempt_id': 'cleanup-test'} + assert {process.pid, child} <= {row['pid'] for row in owned_processes(owner)} + result = asyncio.run(close_owned_processes(owner, deadline=__import__('time').monotonic() + 5)) + assert result['verified_absent'] + assert os.getpid() not in {row['pid'] for obs in result['observations'] for row in obs['processes']} + finally: + if process.poll() is None: + os.killpg(process.pid, __import__('signal').SIGKILL) + process.wait(timeout=5) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process/session observer') +def test_observer_finds_escaped_tagged_child_and_preserves_unrelated_session(): + code = ("import subprocess,time; child=subprocess.Popen(['sleep','60'],start_new_session=True); " + "print(child.pid,flush=True); time.sleep(60)") + runner = subprocess.Popen([sys.executable, '-c', code], start_new_session=True, + env={**os.environ, 'HARBORRL_ATTEMPT_ID': 'escaped-cleanup-test'}, + stdout=subprocess.PIPE, text=True) + other = subprocess.Popen(['sleep', '60'], start_new_session=True, + env={**os.environ, 'HARBORRL_ATTEMPT_ID': 'another-attempt'}) + child = int(runner.stdout.readline()) + try: + owner = {**process_info(runner.pid), 'host': socket.gethostname(), + 'attempt_id': 'escaped-cleanup-test'} + assert process_info(child)['session'] != owner['session'] + assert {runner.pid, child} == {row['pid'] for row in owned_processes(owner)} + proof = asyncio.run(close_owned_processes(owner, deadline=__import__('time').monotonic() + 5)) + assert processes_verified_absent(proof) and other.poll() is None + finally: + for pid in (child, runner.pid, other.pid): + try: + os.kill(pid, __import__('signal').SIGKILL) + except ProcessLookupError: + pass + runner.wait(timeout=5) + other.wait(timeout=5) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='fsynced immutable receipts require POSIX directory fd') +def test_admission_retains_debt_until_independent_receipt_and_preserves_marker(tmp_path): + binding = {'image': 'test', 'max_live_instances': 1} + admission = SandboxAdmission({'max_live_instances': 1, 'bindings': [binding]}) + publish(tmp_path / 'cleanup-required.json', {'reason': 'old delete failure'}) + async def scenario(): + async with admission.lease(binding, tmp_path): + pass + assert admission.blocked and admission.total.locked() + with pytest.raises(RuntimeError, match='blocked'): + async with admission.lease(binding, tmp_path / 'new'): + pytest.fail('new create admitted with debt') + asyncio.run(scenario()) + cfg = config() + lifecycle = {'state': 'delete_failed', 'runtime_digest': digest(cfg), 'sandbox_id': 'owned'} + owner = {'attempt_id': 'a'} + publish(tmp_path / 'runner/sandbox-lifecycle.json', lifecycle) + publish(tmp_path / 'runner-process.json', owner) + publish(tmp_path / 'cleanup-reconciliation.json', {'status': 'verified_absent', + 'schema': 'harborrl-cleanup-v1', 'runtime_digest': digest(cfg), 'sandbox_id': 'owned', + 'get404': True, 'inventory_complete': True, 'inventory_ids': [], + 'reconciled_lifecycle': 'deleted', 'elapsed_sec': .1, + 'observations': [{'operation': 'get', 'http_status': 404}, + {'operation': 'inventory', 'page': 1, 'ids': [], 'total_items': 0, + 'has_next_page': False, 'http_status': 200}], + 'lifecycle_sha256': digest(lifecycle), 'owner_sha256': digest(owner), + 'process_proof': process_proof()}) + admission.reconcile(tmp_path) + assert not admission.blocked and not admission.total.locked() + assert (tmp_path / 'cleanup-required.json').is_file() and not cleanup_debt(tmp_path) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_protected_preexisting_process_is_excluded_but_possible_escaped_child_fails_closed(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + owner = {'host': socket.gethostname(), 'pid': 71, 'session': 71, + 'start_ticks': 100, 'attempt_id': 'test'} + monkeypatch.setattr(Path, 'iterdir', lambda _: iter([Path('/proc/72')])) + def unreadable(_): + raise PermissionError('protected process') + monkeypatch.setattr(Path, 'read_bytes', unreadable) + monkeypatch.setattr(reconcile, 'observer_ancestors', lambda _: {}) + def info(pid): + return {'pid': pid, 'session': pid, 'start_ticks': 100 if pid == 71 else 99, 'state': 'S'} + monkeypatch.setattr(reconcile, 'process_info', info) + assert owned_processes(owner) == [] + monkeypatch.setattr(reconcile, 'process_info', lambda pid: { + 'pid': pid, 'session': pid, 'start_ticks': 100, 'state': 'S'}) + with pytest.raises(PermissionError): + owned_processes(owner) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_protected_observer_ancestor_is_excluded_by_pid_and_start_ticks(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + owner = {'host': socket.gethostname(), 'pid': 71, 'session': 71, + 'start_ticks': 100, 'attempt_id': 'test'} + monkeypatch.setattr(Path, 'iterdir', lambda _: iter([Path('/proc/72')])) + monkeypatch.setattr(reconcile, 'observer_ancestors', lambda _: {72: 101}) + monkeypatch.setattr(reconcile, 'process_info', lambda pid: { + 'pid': pid, 'session': pid, 'start_ticks': 100 if pid == 71 else 101, 'state': 'S'}) + def unreadable(_): + raise PermissionError('protected observer ancestor') + monkeypatch.setattr(Path, 'read_bytes', unreadable) + assert owned_processes(owner) == [] + # The same PID with a new start tick cannot inherit that exclusion. + monkeypatch.setattr(reconcile, 'observer_ancestors', lambda _: {72: 99}) + with pytest.raises(PermissionError): + owned_processes(owner) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +@pytest.mark.parametrize('fault', ['runner-ancestor', 'changed-parent']) +def test_untrusted_observer_ancestry_fails_closed(monkeypatch, fault): + from harborrl.rollout.harbor_job import reconcile + + observer = os.getpid() + calls = 0 + def info(pid): + nonlocal calls + calls += 1 + if pid == observer: + return {'pid': observer, 'ppid': 71 if calls == 1 or fault != 'changed-parent' else 72, + 'session': observer, 'start_ticks': 200} + return {'pid': 71, 'ppid': 1, 'session': 71, 'start_ticks': 100} + monkeypatch.setattr(reconcile, 'process_info', info) + with pytest.raises(RuntimeError, match='observer'): + reconcile.observer_ancestors({'pid': 71, 'session': 71, 'start_ticks': 100, 'attempt_id': 'test'}) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +@pytest.mark.parametrize('kind', ['same-session', 'inherited-tag']) +def test_reparented_observer_cannot_certify_its_own_runner_absent(monkeypatch, kind): + from harborrl.rollout.harbor_job import reconcile + + owner = {'pid': 71, 'session': 71, 'start_ticks': 100, 'attempt_id': 'owned-attempt'} + observer = os.getpid() + monkeypatch.setattr(reconcile, 'process_info', lambda _: { + 'pid': observer, 'ppid': 0, 'session': 71 if kind == 'same-session' else observer, + 'start_ticks': 101}) + monkeypatch.setenv('HARBORRL_ATTEMPT_ID', 'owned-attempt' if kind == 'inherited-tag' else 'other') + with pytest.raises(RuntimeError, match='independent observer required'): + reconcile.observer_ancestors(owner) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_transient_unreadable_process_requires_a_new_complete_scan(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + scans = 0 + def scan(_): + nonlocal scans + scans += 1 + if scans == 1: + raise PermissionError(13, 'process changed during observation') + return [] + monkeypatch.setattr(reconcile, 'owned_processes', scan) + result = asyncio.run(close_owned_processes({}, deadline=__import__('time').monotonic() + 1)) + assert scans == 2 and result['verified_absent'] + assert result['observations'][0]['error_type'] == 'PermissionError' + assert result['observations'][0]['processes'] is None + assert result['observations'][-1]['processes'] == [] + assert processes_verified_absent(result) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_persistent_unreadable_process_exhausts_deadline_without_signalling(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + def scan(_): + raise PermissionError(13, 'process remains protected') + monkeypatch.setattr(reconcile, 'owned_processes', scan) + monkeypatch.setattr(os, 'kill', lambda *_: pytest.fail('unverified process must not be killed')) + result = asyncio.run(close_owned_processes({}, deadline=__import__('time').monotonic() + .02)) + assert not result['verified_absent'] and len(result['observations']) >= 2 + assert all(row['processes'] is None for row in result['observations']) + assert not processes_verified_absent({**result, 'verified_absent': True}) + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_pid_reuse_is_terminal_and_retains_an_unresolved_process_receipt(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + def scan(_): + raise RuntimeError('runner PID was reused; process ownership uncertain') + monkeypatch.setattr(reconcile, 'owned_processes', scan) + result = asyncio.run(close_owned_processes({}, deadline=__import__('time').monotonic() + 5)) + assert not result['verified_absent'] and len(result['observations']) == 1 + assert result['observations'][0]['error_type'] == 'RuntimeError' + + +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux process observer') +def test_signal_permission_error_retains_debt_and_is_not_an_empty_scan(monkeypatch): + from harborrl.rollout.harbor_job import reconcile + + process = {'pid': 123, 'session': 123, 'start_ticks': 100} + monkeypatch.setattr(reconcile, 'owned_processes', lambda _: [process]) + monkeypatch.setattr(reconcile, 'process_info', lambda _: process) + async def no_wait(_): + pass + monkeypatch.setattr(asyncio, 'sleep', no_wait) + def denied(*_): + raise PermissionError(1, 'signal forbidden') + monkeypatch.setattr(os, 'kill', denied) + result = asyncio.run(close_owned_processes({}, deadline=__import__('time').monotonic() + 5)) + assert not result['verified_absent'] + assert result['observations'][-1]['error_type'] == 'PermissionError' + assert result['observations'][-1]['processes'] is None + assert not processes_verified_absent({**result, 'verified_absent': True}) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced evidence') +def test_waiting_admission_wakes_and_fails_when_cleanup_retains_all_capacity(tmp_path): + binding = {'image': 'test', 'max_live_instances': 1} + admission = SandboxAdmission({'max_live_instances': 1, 'bindings': [binding]}) + async def scenario(): + async with admission.lease(binding, tmp_path / 'first'): + async def waiting(): + async with admission.lease(binding, tmp_path / 'second'): + pytest.fail('queued create bypassed cleanup debt') + task = asyncio.create_task(waiting()) + await asyncio.sleep(.01) + assert not task.done() + publish(tmp_path / 'first/cleanup-required.json', {'reason': 'injected delete failure'}) + with pytest.raises(RuntimeError, match='blocked'): + await asyncio.wait_for(task, .5) + assert admission.total.locked() and admission.bindings['test'].locked() + asyncio.run(scenario()) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced evidence') +def test_cleanup_status_and_sdk_receipt_alone_do_not_resolve_debt(tmp_path): + lifecycle, owner = {'state': 'deleted', 'sandbox_id': 'owned'}, {'attempt_id': 'a'} + publish(tmp_path / 'runner/sandbox-lifecycle.json', lifecycle) + publish(tmp_path / 'runner-process.json', owner) + publish(tmp_path / 'cleanup-reconciliation.json', {'status': 'verified_absent', + 'lifecycle_sha256': digest(lifecycle), 'owner_sha256': digest(owner), + 'process_proof': {'verified_absent': True}}) + assert not cleanup_resolved(tmp_path) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced evidence') +@pytest.mark.parametrize('fault', ['missing-process-scan', 'surviving-process', 'missing-page', + 'inventory-total', 'get404-after-inventory']) +def test_malformed_independent_proof_does_not_release_capacity(tmp_path, fault): + cfg = config() + lifecycle = {'runtime_digest': digest(cfg), 'sandbox_id': 'owned', 'state': 'deleted'} + def handler(request): + if request.url.path.endswith('/owned'): + return httpx.Response(404) + return httpx.Response(200, json={'items': [], + 'pagination': {'hasNextPage': False, 'totalItems': 0}}) + receipt = run_reconciliation(handler, lifecycle=lifecycle) + owner = {'attempt_id': 'a'} + receipt['owner_sha256'] = digest(owner) + if fault == 'missing-process-scan': + receipt['process_proof'].pop('observations') + elif fault == 'surviving-process': + receipt['process_proof']['observations'][-1]['processes'] = [ + {'pid': 123, 'session': 123, 'start_ticks': 100}] + elif fault == 'missing-page': + receipt['observations'][-1]['page'] = 2 + elif fault == 'inventory-total': + receipt['observations'][-1]['total_items'] = 1 + else: + receipt['observations'].reverse() + publish(tmp_path / 'runner/sandbox-lifecycle.json', lifecycle) + publish(tmp_path / 'runner-process.json', owner) + publish(tmp_path / 'cleanup-reconciliation.json', receipt) + assert cleanup_debt(tmp_path) and not cleanup_resolved(tmp_path) diff --git a/tests/harborrl/test_sandbox_reliability.py b/tests/harborrl/test_sandbox_reliability.py new file mode 100644 index 000000000..80c19eaca --- /dev/null +++ b/tests/harborrl/test_sandbox_reliability.py @@ -0,0 +1,261 @@ +import asyncio +import json +import sys +from types import SimpleNamespace + +import pytest + +from harborrl.rollout.harbor_job.reliability import ( + InfraBudget, + InfraBudgetExhausted, + ReliabilityLedger, + RetryPolicy, + classify_failure, + sanitize_evidence, + summarize_reliability, +) +from harborrl.rollout.runtime import _failure_stage, _run_slot + + +class RetrySlots: + max_attempts = 2 + + def __init__(self, identities): + self.identities = identities + self.history = [] + + def start(self, slot): + return self.identities[min(self._starts, len(self.identities) - 1)] + + _starts = 0 + + def finish(self, slot, ir=None, *, error=None): + assert (ir is None) != (error is None) + self.history.append((slot, "valid" if ir is not None else "invalid")) + if error is not None: + self._starts += 1 + + +def test_classifier_covers_phase6_faults_and_sanitizes_evidence(): + evidence = { + "event": "node sbx-011 failed", + "url": "https://secret.example/path?token=value", + } + cases = [ + ("create", "FailedCreatePodSandBox/DeadlineExceeded", "create-deadline"), + ("startup", "agent not ready", "startup-timeout"), + ("execute", "command exited 137", "runtime-fault"), + ("cleanup", "GET did not become 404", "cleanup-fault"), + ("storage", "write read-back mismatch", "storage-fault"), + ] + for stage, error, expected in cases: + assert classify_failure(stage, error, evidence=evidence) == expected + sanitized = json.dumps(sanitize_evidence(evidence)) + assert "secret.example" not in sanitized and "token=value" not in sanitized + + +def test_failure_events_are_append_only_and_summarized(tmp_path): + ledger = ReliabilityLedger(tmp_path) + ledger.reserve("a0", task_digest="d" * 64, policy_version="1", + retry_index=0, node="node-a") + ledger.event("a0", "creating", stage="create", node="node-a", decision="retry") + kind, node, delay = ledger.observe_failure( + "a0", "create", "FailedCreatePodSandBox node node-a") + + assert (kind, node, delay) == ("create-deadline", "node-a", 5.0) + ledger.reserve("a1", task_digest="d" * 64, policy_version="1", + retry_index=1, node="node-b") + ledger.event("a1", "completed", stage="execute", decision="complete") + assert summarize_reliability(tmp_path) == { + "events": 5, + "attempts": 2, + "completed_attempts": 1, + "failed_attempts": 1, + "verified_absent_attempts": 0, + "terminal_attempts": 2, + "failure_counts": {"create-deadline": 1}, + "retry_decisions": 1, + "fail_seed_decisions": 0, + "node_cooldown_events": 0, + } + + +def test_event_journal_rejects_history_rewrites(tmp_path): + ledger = ReliabilityLedger(tmp_path) + ledger.reserve("a0", task_digest="d" * 64, policy_version="1", retry_index=0) + path = tmp_path / "events.jsonl" + lines = path.read_text(encoding="utf-8").splitlines() + event = json.loads(lines[0]) + event["state"] = "completed" + lines[0] = json.dumps(event) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="append-only"): + summarize_reliability(tmp_path) + + +def test_node_cooling_selects_another_candidate(tmp_path): + now = [100.0] + ledger = ReliabilityLedger(tmp_path, policy=RetryPolicy( + node_consecutive_failures=2, node_cooldown_seconds=900), clock=lambda: now[0]) + ledger.observe_failure("a0", "create", "CRI-O timeout node sbx-011") + ledger.observe_failure("a1", "create", "FailedCreatePodSandBox node sbx-011") + + assert ledger.next_node(["sbx-011", "sbx-014"]) == "sbx-014" + assert summarize_reliability(tmp_path)["node_cooldown_events"] == 1 + now[0] += 900 + assert ledger.next_node(["sbx-011", "sbx-014"], preferred="sbx-011") == "sbx-011" + + +@pytest.mark.parametrize("lifecycle_state,startup_stage,expected", [ + ("creation_unknown", None, "create"), + ("allocated", None, "startup"), + ("created", "readiness", "readiness"), + ("delete_failed", None, "cleanup"), + ("deleted", None, "execute"), +]) +def test_failure_stage_uses_sanitized_runner_evidence( + tmp_path, lifecycle_state, startup_stage, expected): + runner = tmp_path / "runner" + runner.mkdir() + (runner / "sandbox-lifecycle.json").write_text( + json.dumps({"state": lifecycle_state, "sandbox_id": "sbx-test"}), encoding="utf-8") + if startup_stage: + (runner / "sandbox-startup-failed.json").write_text( + json.dumps({"stage": startup_stage}), encoding="utf-8") + assert _failure_stage(tmp_path, sandbox=True) == expected + + +def test_infrastructure_budget_bounds_create_retries(tmp_path): + ledger = ReliabilityLedger(tmp_path, budget=InfraBudget( + attempts=4, create_retries=1, cleanup_reconciliations=1, + storage_faults=1, wall_clock_seconds=3600)) + ledger.reserve("a0", task_digest="d" * 64, policy_version="1", retry_index=0) + kind, _, delay = ledger.observe_failure("a0", "create", "endpoint 503") + assert (kind, delay) == ("create-deadline", 5.0) + + ledger.reserve("a1", task_digest="d" * 64, policy_version="1", retry_index=1) + with pytest.raises(InfraBudgetExhausted, match="create_retries"): + ledger.observe_failure("a1", "create", "endpoint 504") + + +def _reliability_runtime_config(tmp_path): + from types import SimpleNamespace + + return SimpleNamespace( + max_attempts=2, + task_worker_overrides={}, + runner_transport="local", + workers=(), + sandbox=None, + gateway_routing="modulo", + gateway_url="http://gateway", + runner_python=sys.executable, + max_output_tokens=128, + ) + + +def test_runtime_failure_retries_as_a_new_ledger_attempt(tmp_path, monkeypatch): + from harborrl.rollout import runtime as runtime_module + + policy = RetryPolicy(backoff_seconds=(0, 0), node_consecutive_failures=100) + ledger = ReliabilityLedger(tmp_path, policy=policy) + identities = [ + SimpleNamespace(attempt_id=f"attempt-{index}", group_id="group-0", + slot_id="0", task_digest="d" * 64, policy_version="1") + for index in range(2) + ] + slots = RetrySlots(identities) + calls = [] + + async def attempt(identity, **kwargs): + calls.append(identity.attempt_id) + kwargs["root"].mkdir(parents=True, exist_ok=True) + if len(calls) == 1: + raise RuntimeError("synthetic runtime failure") + return {"identity": identity.__dict__} + + monkeypatch.setattr(runtime_module, "run_attempt", attempt) + config = _reliability_runtime_config(tmp_path) + current = SimpleNamespace(rollout_root=tmp_path, semaphore=asyncio.Semaphore(1), + profile={}, registry=None, reliability=ledger, + shards=(SimpleNamespace(url=config.gateway_url, registry=None),)) + result = asyncio.run(_run_slot( + config, current, slots, 0, + {"id": "task", "path": "/task", "task_digest": "d" * 64}, None)) + + assert result == {"identity": identities[1].__dict__} + assert calls == ["attempt-0", "attempt-1"] + assert slots.history == [("0", "invalid"), ("0", "valid")] + summary = summarize_reliability(tmp_path) + assert summary == { + "events": 6, + "attempts": 2, + "completed_attempts": 1, + "failed_attempts": 1, + "verified_absent_attempts": 0, + "terminal_attempts": 2, + "failure_counts": {"runtime-fault": 1}, + "retry_decisions": 1, + "fail_seed_decisions": 0, + "node_cooldown_events": 0, + } + + +def test_runtime_budget_exhaustion_fails_seed_without_next_attempt(tmp_path, monkeypatch): + from harborrl.rollout import runtime as runtime_module + + ledger = ReliabilityLedger(tmp_path, policy=RetryPolicy( + backoff_seconds=(0, 0)), budget=InfraBudget( + attempts=1, create_retries=1, cleanup_reconciliations=1, + storage_faults=1, wall_clock_seconds=3600)) + identities = [SimpleNamespace(attempt_id="attempt-0", group_id="group-0", + slot_id="0", task_digest="d" * 64, policy_version="1")] + slots = RetrySlots(identities) + calls = [] + + async def attempt(identity, **kwargs): + calls.append(identity.attempt_id) + raise RuntimeError("synthetic runtime failure") + + monkeypatch.setattr(runtime_module, "run_attempt", attempt) + config = _reliability_runtime_config(tmp_path) + current = SimpleNamespace(rollout_root=tmp_path, semaphore=asyncio.Semaphore(1), + profile={}, registry=None, reliability=ledger, + shards=(SimpleNamespace(url=config.gateway_url, registry=None),)) + with pytest.raises(InfraBudgetExhausted, match="attempts"): + asyncio.run(_run_slot(config, current, slots, 0, + {"id": "task", "path": "/task", + "task_digest": "d" * 64}, None)) + + assert calls == ["attempt-0"] + summary = summarize_reliability(tmp_path) + assert summary["attempts"] == 1 + assert summary["fail_seed_decisions"] == 1 + assert slots.history == [("0", "invalid"), ("0", "invalid")] + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced budget lock') +def test_restart_preserves_seed_budget_and_rejects_changed_limits(tmp_path): + def budget(attempts=2): + return InfraBudget(attempts=attempts, create_retries=1, cleanup_reconciliations=1, + storage_faults=1, wall_clock_seconds=3600) + first = ReliabilityLedger(tmp_path, budget=budget()) + first.reserve('a0', task_digest='d' * 64, policy_version='1', retry_index=0) + restarted = ReliabilityLedger(tmp_path, budget=budget()) + assert restarted.budget.remaining['attempts'] == 1 + assert abs(restarted.budget.expires_at - first.budget.expires_at) < .1 + restarted.reserve('a1', task_digest='d' * 64, policy_version='1', retry_index=1) + exhausted = ReliabilityLedger(tmp_path, budget=budget()) + with pytest.raises(InfraBudgetExhausted): + exhausted.reserve('a2', task_digest='d' * 64, policy_version='1', retry_index=2) + with pytest.raises(ValueError, match='budget changed'): + ReliabilityLedger(tmp_path, budget=budget(3)) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX fsynced budget lock') +def test_locked_seed_cannot_remove_budget_before_first_reservation(tmp_path): + ReliabilityLedger(tmp_path, budget=InfraBudget( + attempts=2, create_retries=1, cleanup_reconciliations=1, + storage_faults=1, wall_clock_seconds=3600)) + with pytest.raises(ValueError, match='without its infrastructure budget'): + ReliabilityLedger(tmp_path) From 33362e6e64844733755c112e0170a6b1e5eb9d92 Mon Sep 17 00:00:00 2001 From: AltmanD Date: Tue, 24 Nov 2026 15:54:39 +0800 Subject: [PATCH 2/3] ci: keep lint rules consistent across Ruff releases --- pyproject.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index ac4ee37e2..320913fcc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,5 +53,9 @@ exclude = ["runs*", ".venv*", "workspace*", "local*", "docs*", "tests*"] testpaths = ["tests"] pythonpath = ["."] +[tool.ruff.lint] +# Keep the established error checks stable across Ruff default-rule changes. +select = ["E4", "E7", "E9", "F"] + [tool.ruff.lint.per-file-ignores] "tests/test_consistency_torch.py" = ["E402"] From b238501a8a2e407d3431daecf1b1e87b91431e03 Mon Sep 17 00:00:00 2001 From: AltmanD Date: Tue, 24 Nov 2026 15:58:44 +0800 Subject: [PATCH 3/3] test: wait for gateway admission release before retry --- tests/harborrl/test_native_gateway.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/harborrl/test_native_gateway.py b/tests/harborrl/test_native_gateway.py index 90d6c38a8..8d15548a2 100644 --- a/tests/harborrl/test_native_gateway.py +++ b/tests/harborrl/test_native_gateway.py @@ -203,9 +203,19 @@ def test_pool_mismatch_keeps_admission_closed(tmp_path): assert not registry.accepting -def test_http_overload_rejects_before_any_attempt_state(tmp_path): +def test_http_overload_rejects_before_any_attempt_state(tmp_path, monkeypatch): _registry, _ident, token, gateway = setup(tmp_path) started, release = threading.Event(), threading.Event() + released = threading.Event() + permit = threading.BoundedSemaphore(1) + release_permit = permit.release + + def finish_request(): + release_permit() + released.set() + + monkeypatch.setattr(permit, 'release', finish_request) + monkeypatch.setattr('harborrl.gateway.server.threading.BoundedSemaphore', lambda _: permit) class BlockingBackend(Backend): def generate(self, converted, ident, response_id): @@ -244,6 +254,9 @@ def post(): release.set() first.join(10) assert not errors and results and results[0]["role"] == "assistant" + # Receiving the body can precede the server's delivery bookkeeping + # and semaphore release. Retry only after the first handler finishes. + assert released.wait(5), "first request did not release its admission slot" # The rejected request never began a generation, so a retry is safe. post() assert len(results) == 2