Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(tier3): fail fast on rejected credentials (#75)
Christopher Kevin7119e2a226b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a0db4eb9..74aad1f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,16 @@ All notable changes to SkillEvaluator are documented in this file.### Fixed+- Tier 3 now exercises each resolved agent route and the enabled standard-+ grading route against its provider's model catalog before image preparation+ or task staging. Definitive native-provider authentication and deterministic+ Bedrock credential/configuration failures stop immediately with a redacted+ diagnostic. Non-authoritative OpenAI catalog permission/membership results,+ public or compatible catalog success that does not authenticate inference,+ compatible-gateway catalog authentication, transient failures, and native+ Harbor judge selection resolved only at runtime continue as degraded checks.+ Redacted per-route outcomes are retained even when the later agent runtime+ preflight fails ([#71](https://github.com/NVIDIA/SkillEvaluator/issues/71)).- Tier 3 Harbor collection now accepts the `step_results: null` sentinelemitted for successful single-step trials while retaining fail-closedvalidation for malformed non-null multi-step result containers.diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdxindex 927d285a..56782200 100644--- a/docs/agents-and-sandboxes.mdx+++ b/docs/agents-and-sandboxes.mdx@@ -252,8 +252,10 @@ cleaner experiment.## Readiness checks-`doctor` and `health-check` run the same readiness checks and exit `0` only-when every check passes, so either can gate a script or CI job.+`doctor` and `health-check` run the same readiness checks and exit nonzero when+any check fails, so either can gate a script or CI job. Warnings from+`doctor --verify-models` are nonblocking because the catalog result is+inconclusive rather than a definitive rejection.### doctor@@ -274,10 +276,14 @@ skillevaluator doctor --agents codex --env-mode docker`doctor` also accepts `--agent-model AGENT=MODEL` (repeatable), so you cancheck the exact model plan a run would use. Add `--verify-models` to probeeach agent's resolved model live against the provider's catalog — one extra-pass/fail row per agent, catching a bad model selection before a long run.-When a probe fails, browse what your credential can actually see with-`skillevaluator models` (top 10 of the authenticated catalog by default;-`--limit` and `--json` to adjust).+pass, warn, or fail row per agent. A warning means the catalog result is+non-authoritative, such as a public NVIDIA Build listing or an OpenAI catalog+permission failure that does not decide inference access. Browse catalog+membership with `skillevaluator models` (top 10 by default; `--limit` and+`--json` adjust the result), but use the Tier 3 runtime preflight to prove that+the agent can actually invoke the model. A different route used only by the+standard grader is not exercised by that smoke and remains unproven until+grading begins.### health-checkdiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex ffc0ed2f..e745de0b 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -35,7 +35,7 @@ commands referenced below.| [harbor-view](#harbor-view) | Browse retained Harbor job artifacts | A run made with `--harbor-keep-jobs` || [doctor](#doctor) | Live-evaluation readiness check | Nothing || [health-check](#health-check) | Quick CLI + backend readiness check | Nothing |-| [models](#models) | List a filtered view of the selected provider's authenticated catalog | Provider key |+| [models](#models) | List models visible through the selected provider's catalog | Provider configuration/key || [tier3 validate](#tier3-validate) | Validate `evals/` and the optional Harbor contract | Nothing |## Global conventions@@ -432,7 +432,7 @@ skillevaluator doctor --agents codex --env-mode docker| `-a, --agents TEXT` | `codex` | Comma-separated agents to check. || `--env-mode` | `docker` | Backend to check (same 16 values as [tier3 evaluate](#tier3-evaluate)). || `--agent-model TEXT` | unset | Per-agent model override, `AGENT=MODEL` (repeatable) — check readiness with the model each agent will actually run. |-| `--verify-models` | off | Live per-agent model probe: verifies each agent's resolved model against the provider catalog and prints a pass/fail row per agent, so you can catch a bad model selection before a long run. |+| `--verify-models` | off | Live per-agent catalog probe. Prints pass for verified access, warn for an inconclusive or non-authoritative result (success or failure), and fail only for a definitive credential, model, or configuration rejection. |`skillevaluator tier3 doctor` takes the same flags, including `--agent-model` and `--verify-models`.@@ -451,7 +451,7 @@ skillevaluator health-check## models-List a filtered view of the selected provider's authenticated catalog. Uses the same provider and credential resolution as evaluation (see [Providers & Credentials](configuration.mdx)), so it doubles as a quick check that your key works. A model appearing in the catalog is **not** proof it is compatible with the evaluation harness — use [doctor](#doctor) `--verify-models` for that. Top-level only; there is no tier-prefixed twin.+List models visible through the selected provider's catalog. It uses the same provider and credential resolution as evaluation (see [Providers & Credentials](configuration.mdx)), so it checks catalog reachability and model membership. NVIDIA Build and some compatible gateways expose public catalogs, so a listed model does **not** prove that the inference key works or that the model is compatible with the evaluation harness. `doctor --verify-models` reports such successful but non-authoritative checks as warnings. Top-level only; there is no tier-prefixed twin.```bash title="List the provider's models"skillevaluator models --limit 20diff --git a/docs/configuration.mdx b/docs/configuration.mdxindex f6f43985..2ebeb89e 100644--- a/docs/configuration.mdx+++ b/docs/configuration.mdx@@ -20,13 +20,29 @@ Tiers describe evaluation depth; credentials are a separate axis. This is the co| --- | --- || `validate --no-dedup` (all deterministic checks: schema, security scanners including secret detection, PII, license, code-integrity, unicode, quality, lint) | `rubric-eval` — LLM-as-judge scoring (chat LLM) || `quality-check`, `security-scan`, `pii-scan`, `lint-scripts` | `validate --llm` / `security-scan --llm` — deeper LLM security analysis |-| `doctor`, `health-check` (offline readiness probes; missing credentials are reported as not ready) | `--llm-verify` on `validate`, `security-scan`, `pii-scan` — LLM false-positive suppression |+| `doctor`, `health-check` (offline readiness probes by default; missing credentials are reported as not ready) | `--llm-verify` on `validate`, `security-scan`, `pii-scan` — LLM false-positive suppression || | All Tier 2 commands — embeddings API; `context-optimization-check` and `dedup-scan` also use a chat LLM (`similarity-check` is embeddings-only). A local OpenAI-compatible server works too — see [Fully local setup](#fully-local-setup) || Tier 3 scaffolding and inspection: `create-eval-dataset --no-llm`, `init-custom-grader`, `init-harbor-task`, `tier3 validate`, `view`, `harbor-view`, and `compare` | Tier 3 LLM dataset generation needs a provider key; `tier3 evaluate` needs a provider key plus a credential the selected live agent can use — with NVIDIA Build in `--env-mode docker` or `local`, one `NVIDIA_API_KEY` covers both roles |-| | `models` — lists the selected provider's authenticated model catalog |+| | `models` and `doctor --verify-models` — provider-catalog reachability and membership checks; public catalogs do not prove that an inference key works |`validate` without `--no-dedup` stays usable keyless: the Tier 2 dedup pass skips gracefully when no embedding provider is configured.+Before Tier 3 prepares images or stages Harbor tasks, `tier3 evaluate` also+makes a bounded credential-bearing catalog request for each distinct agent route+and for the standard-grading route when that grader's effective model is known.+A definitive native-provider credential rejection or deterministic Bedrock+credential/configuration error fails immediately. Catalog permission and+membership are not authoritative for OpenAI Responses access, and NVIDIA Build+or a compatible gateway may expose a catalog without authenticating inference,+so those checks are reported as degraded and evaluation continues to the real+per-agent runtime preflight. That smoke proves agent routes only: when a+degraded credential route is used solely by the standard grader, inference on+that route remains unproven until grading begins. The same applies when native+Harbor must resolve at runtime whether a task or step verifier declaration+supersedes the configured judge fallback. Redacted per-route outcomes are retained under+`run_config.credential_validation` in `result.json`, including when that later+agent runtime preflight fails.+## Choose an LLM providerSet `SKILL_EVAL_LLM_PROVIDER` to one of `openai`, `anthropic`, `nv_build`, `bedrock`, or `openai-compatible`. The selected provider determines which credential SkillEvaluator reads. All but `openai-compatible` ship a default model that `SKILL_EVAL_LLM_MODEL` overrides.@@ -199,7 +215,7 @@ skillevaluator models --limit 20skillevaluator models --json```-`skillevaluator models` prints a filtered, bounded view of the authenticated provider catalog (`--limit` accepts 1–100, default 10; `--json` emits machine-readable output). It uses the same provider and credential resolution as evaluation, so it doubles as a quick check that your key works. A model appearing in the catalog is not proof a given agent harness supports it — use `doctor --verify-models` for that. Bedrock exposes no HTTP model catalog, so `models` errors on that provider; use `doctor --verify-models` there too.+`skillevaluator models` prints a filtered, bounded view of the provider catalog (`--limit` accepts 1–100, default 10; `--json` emits machine-readable output). It uses the same provider and credential resolution as evaluation, so it checks catalog routing and model discovery where that surface is supported. NVIDIA Build and some compatible gateways can expose a public catalog, so a listed model is not proof that the inference key works or that a given agent harness supports it. Tier 3's real per-agent runtime preflight is the stronger check for agent routes; a separate degraded standard-grader route remains unproven until grading begins. Bedrock exposes no HTTP model catalog, so `models` errors on that provider; use `doctor --verify-models` there instead.### `runtime_env` is for task values, not credentialsdiff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdxindex 8bdd7ce7..951ec1bc 100644--- a/docs/environment-variables.mdx+++ b/docs/environment-variables.mdx@@ -107,7 +107,7 @@ execution environments are covered in| `SKILLEVALUATOR_LOCAL_INHERIT_AGENT_KEYS` | `false` | When true, local-mode trials inherit the host's agent credential variables into their ambient environment. Off by default so a hostile skill command cannot read credentials — agents and verifiers receive credentials per-exec instead. || `SKILLEVALUATOR_RUNTIME_DIR` | `~/.local/share/skillevaluator/runtimes` | Where local mode looks for managed agent CLIs. Must be a dedicated subdirectory — not the home directory or one of its parents. || `SKILL_EVAL_HARBOR_PREBUILD_TASK_ENVS` | unset | Set to exactly `1` to opt in to pre-building Harbor task environment images before trials start (other truthy spellings are not honored). Opt-in because concurrent trial cleanup can remove a shared prebuilt image that sibling trials still need. |-| `SKILL_EVAL_JUDGE_MODEL` | falls back to `SKILL_EVAL_LLM_MODEL` | Operator-controlled model override for the Tier 3 dimension judge in standard grading. `LLM_JUDGE_MODEL` is honored as a higher-precedence spelling; when neither is set, the judge uses `SKILL_EVAL_LLM_MODEL`, then the built-in judge default. Both spellings change only the model used with the configured `SKILL_EVAL_LLM_PROVIDER`; they do not select a separate judge provider, so the model must be supported by that provider. Standard grading makes both spellings resolve to the selected override in Harbor's parent process, then forwards them through its verifier-only job layer, which takes precedence over task and step verifier declarations. Neither name is injected into the evaluated agent's initial environment; attempts to set or reference one from skill-authored `runtime_env` or native `[environment.env]` tables are rejected. Native custom-only graders keep ownership of their verifier configuration. Shared agent/verifier containers are a process boundary, not a confidentiality boundary; use a separate verifier environment when the model name itself must be hidden from untrusted agent processes. `run_config.json` records the configured judge provider, model, source, and `override_applied` separately from agent models; an allowed provider fallback may use a different model for an individual judge call. When `override_applied` is false for a native Harbor task, an authored task or step verifier declaration may supersede that recorded fallback. |+| `SKILL_EVAL_JUDGE_MODEL` | falls back to `SKILL_EVAL_LLM_MODEL` | Operator-controlled model override for the Tier 3 dimension judge in standard grading. `LLM_JUDGE_MODEL` is honored as a higher-precedence spelling; when neither is set, the judge uses `SKILL_EVAL_LLM_MODEL`, then the built-in judge default. Both spellings change only the model used with the configured `SKILL_EVAL_LLM_PROVIDER`; they do not select a separate judge provider, so the model must be supported by that provider. Standard grading makes both spellings resolve to the selected override in Harbor's parent process, then forwards them through its verifier-only job layer, which takes precedence over task and step verifier declarations. Neither name is injected into the evaluated agent's initial environment; attempts to set or reference one from skill-authored `runtime_env` or native `[environment.env]` tables are rejected. Native custom-only graders keep ownership of their verifier configuration. Shared agent/verifier containers are a process boundary, not a confidentiality boundary; use a separate verifier environment when the model name itself must be hidden from untrusted agent processes. `run_config.json` records the configured judge provider, model, source, `override_applied`, and catalog-verification status separately from agent models; an allowed provider fallback may use a different model for an individual judge call. When `override_applied` is false for a native Harbor task, `effective_model_source` is `native_harbor_runtime` and catalog verification is explicitly inconclusive because an authored task or step verifier declaration may supersede the recorded fallback. || `SKILLEVALUATOR_HARBOR_DIAGNOSTIC_ARTIFACT_MAX_BYTES` | `5242880` (5 MiB) | Size cap per diagnostic artifact copied from a Harbor trial into the results directory. Values are bounded to 0–67108864 bytes (64 MiB); `0` skips non-empty artifacts. Oversized artifacts are skipped and recorded in the artifact manifest. |### Tier 3 judge failure semanticsdiff --git a/docs/installation.mdx b/docs/installation.mdxindex d75a6306..e4ed106e 100644--- a/docs/installation.mdx+++ b/docs/installation.mdx@@ -149,7 +149,7 @@ skillevaluator --versionskillevaluator health-check```-`--version` confirms the CLI is on PATH — that is the whole smoke test for a Tier 1-only install. `health-check` goes one step further: a quick readiness check of the CLI and the selected live-eval backend (defaults: the `codex` agent, `docker` environment), useful once you plan to run Tier 3. On an install without the `tier3` extra or a configured provider it lists the missing pieces and exits non-zero — expected for a Tier 1-only setup, not a broken install. For a deeper diagnosis, `doctor` covers the same ground plus model verification — see the [CLI Reference](cli-reference.mdx) for both.+`--version` confirms the CLI is on PATH — that is the whole smoke test for a Tier 1-only install. `health-check` goes one step further: a quick readiness check of the CLI and the selected live-eval backend (defaults: the `codex` agent, `docker` environment), useful once you plan to run Tier 3. On an install without the `tier3` extra or a configured provider it lists the missing pieces and exits non-zero — expected for a Tier 1-only setup, not a broken install. For a deeper diagnosis, `doctor` covers the same ground; add `doctor --verify-models` to make a live credential-bearing catalog request for each resolved agent model. A public or otherwise non-authoritative result is reported as a warning because catalog access alone does not prove inference access. See the [CLI Reference](cli-reference.mdx) for both commands.## Troubleshootingdiff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 1fda4fc5..924ab2d5 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -63,8 +63,11 @@ skillevaluator doctor --agents codex --env-mode docker`doctor` takes seconds and names anything missing: the evaluator provider,the selected backend's prerequisites, and unsupported agent names. Add`--verify-models` to live-probe each agent's model against the provider's-catalog — one pass/fail row per agent — and `--agent-model AGENT=MODEL` to-check an override before committing to a run.+catalog — one pass, warn, or fail row per agent — and `--agent-model AGENT=MODEL`+to check an override before committing to a run. Warnings identify catalog+results that do not authoritatively prove inference access. Tier 3's runtime+preflight is the stronger check for agent routes; it does not invoke a separate+standard-grader-only route before the evaluation reaches grading.`skillevaluator health-check` is the quickerCLI-and-backend variant; [Agents & Sandboxes](agents-and-sandboxes.mdx) coversboth in depth.@@ -199,17 +202,32 @@ wrote and how to interpret it.## How a run works-`tier3 evaluate` reads the accepted dataset (or native task source) and builds-a Harbor task bundle. Before spending the full A/B matrix, a runtime preflight-runs one real, bounded smoke task per agent to confirm each agent runtime-actually works (on by default; disable with `--no-agent-runtime-preflight`). Harbor then-starts the selected environment and runs the agent in both arms; with standard-grading, each transcript is judged against the case's expected output and-assertions using the configured evaluator provider. Finally, SkillEvaluator-collects the artifacts and computes the dimension scores, pass rates, and-Skill Lift. Harbor task and job directories are transient: they are deleted-after collection whether the run succeeds or fails, unless you pass-`--harbor-keep-jobs`.+`tier3 evaluate` reads the accepted dataset (or native task source), resolves+each agent's actual provider route and the enabled standard-grading route, and+makes bounded credential-bearing model-catalog requests before image preparation+or task staging. Definitive native-provider authentication, authoritative model+rejection, and deterministic Bedrock credential/configuration failures stop+immediately. Non-authoritative OpenAI catalog permission or membership results,+compatible-gateway catalog authentication, unsupported catalogs, and transient+failures are reported as degraded rather than blocking the run. A successful+NVIDIA Build or compatible-gateway listing is also inconclusive when that+catalog does not authenticate inference; the real per-agent runtime preflight+is the stronger check for agent routes. A degraded route used only by the+standard grader remains unproven until grading begins. Native Harbor judge selection is likewise inconclusive+until runtime when no host judge override is set. `result.json` retains the+redacted target-by-target outcome under `run_config.credential_validation`,+including when the subsequent agent runtime preflight fails.++SkillEvaluator then builds the Harbor task bundle. Before spending the full+A/B matrix, a runtime preflight runs one real, bounded smoke task per agent to+confirm each agent runtime actually works (on by default; disable with+`--no-agent-runtime-preflight`). Harbor then starts the selected environment+and runs the agent in both arms; with standard grading, each transcript is+judged against the case's expected output and assertions using the configured+evaluator provider. Finally, SkillEvaluator collects the artifacts and+computes the dimension scores, pass rates, and Skill Lift. Harbor task and job+directories are transient: they are deleted after collection whether the run+succeeds or fails, unless you pass `--harbor-keep-jobs`.Two credential roles are involved: the evaluator provider generates datasetsand performs standard grading, while the live agent uses its own nativediff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 768ce205..0ed29141 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -2009,7 +2009,7 @@ def view(skill_path: Path, results_dir: Path | None) -> None:@click.option("--limit", type=click.IntRange(min=1, max=100), default=10, show_default=True)@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON.")def models_command(limit: int, as_json: bool) -> None:- """List a filtered view of the selected provider's authenticated catalog."""+ """Check catalog reachability and list visible provider models."""from skillevaluator.model_commands import run_models_commandraise SystemExit(run_models_command(limit=limit, as_json=as_json))@@ -2025,7 +2025,11 @@ def models_command(limit: int, as_json: bool) -> None:)@click.option("--env-mode", default="docker", show_default=True, type=ENV_MODE_CHOICE)@click.option("--agent-model", multiple=True, help="Per-agent model override, AGENT=MODEL.")[email protected]("--verify-models", is_flag=True, help="Show the configured public provider model.")+ "--verify-models",+ is_flag=True,+ help="Check resolved agent-model catalog reachability with a live credential-bearing request.",+)def doctor(agents: str, env_mode: str, agent_model: tuple[str, ...], verify_models: bool) -> None:"""Check live-evaluation runtime readiness."""from skillevaluator.tier3.commands import doctor as tier3_doctordiff --git a/src/skillevaluator/model_catalog.py b/src/skillevaluator/model_catalog.pyindex b7e64c2d..bc60b774 100644--- a/src/skillevaluator/model_catalog.py+++ b/src/skillevaluator/model_catalog.py@@ -14,13 +14,14 @@ import timeimport unicodedatafrom collections.abc import Iterable, Mappingfrom dataclasses import dataclass+from enum import StrEnumfrom functools import partialfrom http.client import HTTPConnection, HTTPException, HTTPResponse, HTTPSConnectionfrom queue import Empty, Queuefrom threading import BoundedSemaphore, Threadfrom typing import TYPE_CHECKING, Anyfrom urllib.error import HTTPError, URLError-from urllib.parse import urlencode, urlsplit+from urllib.parse import quote, urlencode, urlsplitfrom urllib.request import HTTPHandler, HTTPRedirectHandler, HTTPSHandler, ProxyHandler, Request, build_openerif TYPE_CHECKING:@@ -50,8 +51,48 @@ _NON_CHAT_MARKERS = ()+class ModelCatalogFailureKind(StrEnum):+ """Structured catalog failure categories safe for command-level policy."""++ AUTHENTICATION = "authentication"+ AUTHORIZATION = "authorization"+ UNSUPPORTED = "unsupported"+ UNAVAILABLE = "unavailable"+ INVALID_CONFIGURATION = "invalid_configuration"+ INVALID_RESPONSE = "invalid_response"+ MODEL_NOT_FOUND = "model_not_found"+ OTHER_HTTP = "other_http"+ UNKNOWN = "unknown"++class ModelCatalogError(RuntimeError):- """Safe-to-display catalog error without response or credential content."""+ """Safe-to-display catalog error with non-secret structured metadata."""++ def __init__(+ self,+ message: str,+ *,+ kind: ModelCatalogFailureKind | str = ModelCatalogFailureKind.UNKNOWN,+ http_status: int | None = None,+ ) -> None:+ super().__init__(message)+ try:+ self.kind = ModelCatalogFailureKind(kind)+ except (TypeError, ValueError):+ self.kind = ModelCatalogFailureKind.UNKNOWN+ self.http_status = http_status+++def _http_failure_kind(status: int) -> ModelCatalogFailureKind:+ if status == 401:+ return ModelCatalogFailureKind.AUTHENTICATION+ if status == 403:+ return ModelCatalogFailureKind.AUTHORIZATION+ if status in {404, 405, 501}:+ return ModelCatalogFailureKind.UNSUPPORTED+ if status in {408, 429} or 500 <= status <= 599:+ return ModelCatalogFailureKind.UNAVAILABLE+ return ModelCatalogFailureKind.OTHER_HTTPclass _RejectRedirects(HTTPRedirectHandler):@@ -301,7 +342,7 @@ class CatalogModel:def fetch_model_records(config: ProviderConfig, timeout_seconds: float = 15.0) -> tuple[ModelRecord, ...]:- """Fetch and normalize the selected provider's authenticated ``/models`` catalog."""+ """Fetch and normalize the selected provider's ``/models`` catalog."""_validate_timeout(timeout_seconds)url, headers = _request_settings(config)records: list[ModelRecord] = []@@ -314,7 +355,10 @@ def fetch_model_records(config: ProviderConfig, timeout_seconds: float = 15.0) -for page_number in range(1, _MAX_CATALOG_PAGES + 1):request_timeout = timeout_seconds if page_number == 1 else deadline - time.monotonic()if request_timeout <= 0:- raise ModelCatalogError("model catalog request timed out")+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ )payload, response_bytes = _request_json(next_url,headers=headers,@@ -325,7 +369,10 @@ def fetch_model_records(config: ProviderConfig, timeout_seconds: float = 15.0) -remaining_bytes -= response_bytesdata = payload.get("data") if isinstance(payload, dict) else Noneif not isinstance(data, list):- raise ModelCatalogError("model catalog response has no data list")+ raise ModelCatalogError(+ "model catalog response has no data list",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )for item in data:if not isinstance(item, dict):@@ -342,7 +389,10 @@ def fetch_model_records(config: ProviderConfig, timeout_seconds: float = 15.0) -):continueif len(records) >= _MAX_MODEL_RECORDS:- raise ModelCatalogError("model catalog exceeded the safe record limit")+ raise ModelCatalogError(+ "model catalog exceeded the safe record limit",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )created = item.get("created")normalized_created = (created if isinstance(created, int) and not isinstance(created, bool) and created >= 0 else None@@ -360,19 +410,78 @@ def fetch_model_records(config: ProviderConfig, timeout_seconds: float = 15.0) -or _has_unsafe_control(cursor)or cursor in seen_cursors):- raise ModelCatalogError("model catalog pagination cursor is invalid")+ raise ModelCatalogError(+ "model catalog pagination cursor is invalid",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )if remaining_bytes <= 0:- raise ModelCatalogError("model catalog response exceeded the safe size limit")+ raise ModelCatalogError(+ "model catalog response exceeded the safe size limit",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )seen_cursors.add(cursor)next_url = f"{url}?{urlencode({'after_id': cursor})}"else:- raise ModelCatalogError("model catalog exceeded the safe pagination limit")+ raise ModelCatalogError(+ "model catalog exceeded the safe pagination limit",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )if data and not records:- raise ModelCatalogError("model catalog response did not contain valid model records")+ raise ModelCatalogError(+ "model catalog response did not contain valid model records",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )return tuple(records)+def fetch_anthropic_model_record(+ config: ProviderConfig,+ model_id: str,+ timeout_seconds: float = 15.0,+) -> ModelRecord:+ """Resolve one Anthropic model ID or alias through its native endpoint."""+ _validate_timeout(timeout_seconds)+ if config.provider != "anthropic":+ raise ModelCatalogError(+ "single-model lookup is only supported for Anthropic",+ kind=ModelCatalogFailureKind.UNSUPPORTED,+ )+ if (+ not isinstance(model_id, str)+ or not model_id+ or model_id != model_id.strip()+ or len(model_id) > _MAX_MODEL_ID_LENGTH+ or _has_unsafe_control(model_id)+ ):+ raise ModelCatalogError(+ "model catalog model ID is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )++ catalog_url, headers = _request_settings(config)+ deadline = time.monotonic() + timeout_seconds+ payload, _response_bytes = _request_json(+ f"{catalog_url}/{quote(model_id, safe='')}",+ headers=headers,+ timeout_seconds=timeout_seconds,+ max_response_bytes=_MAX_RESPONSE_BYTES,+ deadline=deadline,+ )+ resolved_id = payload.get("id") if isinstance(payload, dict) else None+ if (+ not isinstance(resolved_id, str)+ or not resolved_id.strip()+ or len(resolved_id) > _MAX_MODEL_ID_LENGTH+ or _has_unsafe_control(resolved_id)+ ):+ raise ModelCatalogError(+ "model catalog response did not contain a valid model record",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )+ return ModelRecord(id=resolved_id.strip())++def select_catalog_models(config: ProviderConfig,records: Iterable[ModelRecord],@@ -401,17 +510,29 @@ def select_catalog_models(def _request_settings(config: ProviderConfig) -> tuple[str, dict[str, str]]:if config.provider == "bedrock":- raise ModelCatalogError("bedrock does not expose this HTTP catalog; use skillevaluator doctor --verify-models")+ raise ModelCatalogError(+ "bedrock does not expose this HTTP catalog; use skillevaluator doctor --verify-models",+ kind=ModelCatalogFailureKind.UNSUPPORTED,+ )if config.provider not in {"nv_build", "openai", "openai-compatible", "anthropic"}:- raise ModelCatalogError(f"{config.provider} does not expose a supported HTTP model catalog")+ raise ModelCatalogError(+ f"{config.provider} does not expose a supported HTTP model catalog",+ kind=ModelCatalogFailureKind.UNSUPPORTED,+ )api_key = config.api_keyif not isinstance(api_key, str) or not api_key.strip():credential = config.credential_env or "provider API key"- raise ModelCatalogError(f"{credential} is required for authenticated model discovery")+ raise ModelCatalogError(+ f"{credential} is required for authenticated model discovery",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if _has_unsafe_control(api_key):credential = config.credential_env or "provider API key"- raise ModelCatalogError(f"{credential} contains invalid control characters")+ raise ModelCatalogError(+ f"{credential} contains invalid control characters",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if config.provider == "anthropic":base_url = config.base_url or _ANTHROPIC_BASE_URL@@ -421,25 +542,40 @@ def _request_settings(config: ProviderConfig) -> tuple[str, dict[str, str]]:}if not config.base_url:- raise ModelCatalogError(f"{config.provider} does not expose an HTTP model catalog")+ raise ModelCatalogError(+ f"{config.provider} does not expose an HTTP model catalog",+ kind=ModelCatalogFailureKind.UNSUPPORTED,+ )return _provider_url(config.base_url), {"Authorization": f"Bearer {api_key}"}def _provider_url(base_url: str, *, ensure_v1: bool = False) -> str:if not isinstance(base_url, str) or not base_url or base_url != base_url.strip():- raise ModelCatalogError("model catalog base URL is invalid")+ raise ModelCatalogError(+ "model catalog base URL is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if _has_unsafe_control(base_url) or "\\" in base_url:- raise ModelCatalogError("model catalog base URL is invalid")+ raise ModelCatalogError(+ "model catalog base URL is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )try:parsed = urlsplit(base_url)port = parsed.portexcept ValueError:- raise ModelCatalogError("model catalog base URL is invalid") from None+ raise ModelCatalogError(+ "model catalog base URL is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ ) from Nonescheme = parsed.scheme.casefold()hostname = parsed.hostnameif scheme not in {"http", "https"} or not parsed.netloc or not hostname:- raise ModelCatalogError("model catalog base URL must be absolute HTTP or HTTPS")+ raise ModelCatalogError(+ "model catalog base URL must be absolute HTTP or HTTPS",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if (parsed.username is not Noneor parsed.password is not None@@ -447,11 +583,20 @@ def _provider_url(base_url: str, *, ensure_v1: bool = False) -> str:or "#" in base_urlor parsed.netloc.endswith(":")):- raise ModelCatalogError("model catalog base URL must not contain credentials, query, or fragment")+ raise ModelCatalogError(+ "model catalog base URL must not contain credentials, query, or fragment",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if ";" in parsed.path:- raise ModelCatalogError("model catalog base URL path is invalid")+ raise ModelCatalogError(+ "model catalog base URL path is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )if scheme == "http" and not _is_loopback_host(hostname):- raise ModelCatalogError("model catalog base URL must use HTTPS unless it targets loopback")+ raise ModelCatalogError(+ "model catalog base URL must use HTTPS unless it targets loopback",+ kind=ModelCatalogFailureKind.UNSUPPORTED,+ )host = f"[{hostname}]" if ":" in hostname else hostnameauthority = f"{host}:{port}" if port is not None else host@@ -480,24 +625,49 @@ def _request_json(with urlopen(request, timeout=timeout_seconds) as response: # nosec B310 - validated aboveraw = _read_response_body(response, max_response_bytes=max_response_bytes, deadline=deadline)except HTTPError as exc:- raise ModelCatalogError(f"model catalog returned HTTP {exc.code}") from None+ raise ModelCatalogError(+ f"model catalog returned HTTP {exc.code}",+ kind=_http_failure_kind(exc.code),+ http_status=exc.code,+ ) from Noneexcept TimeoutError:- raise ModelCatalogError("model catalog request timed out") from None+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ ) from Noneexcept URLError as exc:if isinstance(exc.reason, TimeoutError):- raise ModelCatalogError("model catalog request timed out") from None- raise ModelCatalogError(f"model catalog request failed: {type(exc).__name__}") from None+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ ) from None+ raise ModelCatalogError(+ f"model catalog request failed: {type(exc).__name__}",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ ) from Noneexcept (HTTPException, OSError) as exc:- raise ModelCatalogError(f"model catalog request failed: {type(exc).__name__}") from None+ raise ModelCatalogError(+ f"model catalog request failed: {type(exc).__name__}",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ ) from Noneexcept (TypeError, ValueError):- raise ModelCatalogError("model catalog request configuration is invalid") from None+ raise ModelCatalogError(+ "model catalog request configuration is invalid",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ ) from Noneif len(raw) > max_response_bytes:- raise ModelCatalogError("model catalog response exceeded the safe size limit")+ raise ModelCatalogError(+ "model catalog response exceeded the safe size limit",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ )try:return json.loads(raw), len(raw)except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):- raise ModelCatalogError("model catalog returned invalid JSON") from None+ raise ModelCatalogError(+ "model catalog returned invalid JSON",+ kind=ModelCatalogFailureKind.INVALID_RESPONSE,+ ) from Nonedef _read_response_body(response: Any, *, max_response_bytes: int, deadline: float) -> bytes:@@ -517,7 +687,10 @@ def _read_response_body(response: Any, *, max_response_bytes: int, deadline: floif not callable(read_once):raw = response.read(max_response_bytes + 1)if time.monotonic() >= deadline:- raise ModelCatalogError("model catalog request timed out")+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ )return rawchunks: list[bytes] = []@@ -525,11 +698,17 @@ def _read_response_body(response: Any, *, max_response_bytes: int, deadline: flowhile total <= max_response_bytes:remaining = deadline - time.monotonic()if remaining <= 0:- raise ModelCatalogError("model catalog request timed out")+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ )_set_response_socket_timeout(response, remaining)chunk = read_once(min(_RESPONSE_READ_CHUNK_BYTES, max_response_bytes + 1 - total))if time.monotonic() >= deadline:- raise ModelCatalogError("model catalog request timed out")+ raise ModelCatalogError(+ "model catalog request timed out",+ kind=ModelCatalogFailureKind.UNAVAILABLE,+ )if not chunk:breakchunks.append(chunk)@@ -559,7 +738,10 @@ def _validate_timeout(timeout_seconds: float) -> None:or not math.isfinite(timeout_seconds)or timeout_seconds <= 0):- raise ModelCatalogError("model catalog timeout must be a positive number")+ raise ModelCatalogError(+ "model catalog timeout must be a positive number",+ kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )def _has_unsafe_control(value: str) -> bool:diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 54f5ac41..217dfe46 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -786,21 +786,39 @@ def doctor(if provider is None or not runtime_plans:rows.append(("provider model", "fail", "provider model resolution was unavailable"))else:- from skillevaluator.tier3.harbor.runtime_preflight import probe_model+ from skillevaluator.tier3.harbor.runtime_preflight import (+ CredentialProbeDisposition,+ credential_probe_disposition,+ probe_model,+ )for agent in agent_list:- probe = probe_model(runtime_plans[agent].provider)- rows.append((f"{agent} model", "pass" if probe.ok else "fail", probe.detail))+ selected_provider = runtime_plans[agent].provider+ probe = probe_model(selected_provider)+ disposition = credential_probe_disposition(selected_provider, probe)+ if disposition == CredentialProbeDisposition.FATAL:+ status = "fail"+ detail = probe.detail+ elif disposition == CredentialProbeDisposition.DEGRADED:+ status = "warn"+ detail = probe.detail+ if probe.ok:+ detail = f"{detail}; catalog access does not verify runtime credentials for this endpoint"+ else:+ status = "pass"+ detail = probe.detail+ rows.append((f"{agent} model", status, detail))table = Table(title="SkillEvaluator Doctor", box=SIMPLE, show_edge=False)table.add_column("Check", style="bold")table.add_column("Status")table.add_column("Details")+ status_styles = {"pass": "green", "warn": "yellow", "fail": "red"}for name, status, detail in rows:- style = "green" if status == "pass" else "red"+ style = status_styles[status]table.add_row(name, f"[{style}]{status}[/{style}]", detail)console.print(table)- return 0 if all(row[1] == "pass" for row in rows) else 1+ return 1 if any(row[1] == "fail" for row in rows) else 0def validate_evals(skill_path: Path, *, as_json: bool, strict: bool, harbor_contract: bool) -> int:diff --git a/src/skillevaluator/tier3/harbor/local_agents.py b/src/skillevaluator/tier3/harbor/local_agents.pyindex 6304a9fc..605ecc34 100644--- a/src/skillevaluator/tier3/harbor/local_agents.py+++ b/src/skillevaluator/tier3/harbor/local_agents.py@@ -14,12 +14,13 @@ import secretsimport shleximport tempfileimport uuid-from collections.abc import Callable+from collections.abc import Awaitable, Callablefrom contextlib import suppressfrom pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Anyfrom urllib.parse import urlsplit+from harbor.agents.installed.base import NonZeroAgentExitCodeErrorfrom harbor.agents.installed.claude_code import ClaudeCodefrom harbor.agents.installed.codex import Codexfrom harbor.agents.installed.opencode import OpenCode@@ -30,6 +31,10 @@ from skillevaluator.tier3.harbor.nvidia_build_bridge import (RunningBridge,start_in_process_bridge,)+from skillevaluator.tier3.harbor.sensitive_stdin import (+ NVIDIA_BUILD_STDIN_SENTINEL,+ read_nvidia_build_key_from_stdin,+)if TYPE_CHECKING:from harbor.environments.base import BaseEnvironment@@ -39,6 +44,8 @@ _CODEX_MODEL_ARG_RE = re.compile(r"(?P<prefix>(?:^|\s)--model(?:=|\s+))(?P<model_DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1"_NVIDIA_BUILD_BRIDGE_BASE_URL = "https://integrate.api.nvidia.com/v1"_NVIDIA_BUILD_BRIDGE_HOST = "127.0.0.1"+_NVIDIA_BUILD_BRIDGE_API_KEY_ENV = "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY"+_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV = "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN"_NVIDIA_BUILD_FILE_BACKED_SENTINEL_KEY = "skillevaluator-file-backed-nvidia-key"_NVIDIA_BUILD_HOST_KEY_FILE_ENV = "SKILLEVALUATOR_NVIDIA_API_KEY_FILE"@@ -343,6 +350,14 @@ class _NvidiaBuildBridgeAgent:def _rewrite_bridge_client_command(self, command: str) -> str:return command+ @staticmethod+ def _sensitive_exec(environment: BaseEnvironment) -> Callable[..., Awaitable[Any]]:+ """Require a transport that keeps sensitive values out of host argv and logs."""+ sensitive_exec = getattr(environment, "exec_with_sensitive_env", None)+ if not callable(sensitive_exec):+ raise RuntimeError("NVIDIA Build bridge requires an environment with protected sensitive-value transport")+ return sensitive_exec+async def _prepare_bridge_client(self, environment: BaseEnvironment) -> None:"""Perform optional agent-specific setup after the bridge is healthy."""@@ -364,6 +379,9 @@ class _NvidiaBuildBridgeAgent:@staticmethoddef _resolve_bridge_api_key() -> str:+ api_key = os.environ.get("NVIDIA_API_KEY", "").strip()+ if api_key == NVIDIA_BUILD_STDIN_SENTINEL:+ return read_nvidia_build_key_from_stdin()host_key_file = os.environ.get(_NVIDIA_BUILD_HOST_KEY_FILE_ENV, "").strip()if host_key_file:try:@@ -373,7 +391,6 @@ class _NvidiaBuildBridgeAgent:if not api_key:raise RuntimeError("NVIDIA Build bridge key handoff file is empty")return api_key- api_key = os.environ.get("NVIDIA_API_KEY", "").strip()if api_key == _NVIDIA_BUILD_FILE_BACKED_SENTINEL_KEY:raise RuntimeError(f"NVIDIA Build bridge requires {_NVIDIA_BUILD_HOST_KEY_FILE_ENV} for file-backed credentials"@@ -428,6 +445,7 @@ class _NvidiaBuildBridgeAgent:return str(client_token)async def _start_bridge(self, environment: BaseEnvironment) -> None:+ sensitive_exec = self._sensitive_exec(environment)api_key = self._resolve_bridge_api_key()model_name = str(self.model_name or "").strip()if not model_name:@@ -447,23 +465,28 @@ class _NvidiaBuildBridgeAgent:Path(__file__).with_name("nvidia_build_bridge.py"), self._BRIDGE_SCRIPT.as_posix())- # Harbor's Docker executor renders values supplied through- # ``env=`` in the host-side ``docker compose exec`` argv. Hand the- # credential over as a mode-0600 file in container-only /tmp- # instead, then let the bridge consume and unlink it before- # accepting requests.- with tempfile.TemporaryDirectory(prefix="skillevaluator-nvidia-build-") as temp_dir:- key_fd, key_path = tempfile.mkstemp(prefix="nvidia-api-key-", dir=temp_dir, text=True)- with os.fdopen(key_fd, "w", encoding="utf-8") as host_key_stream:- host_key_stream.write(api_key)- host_key_file = Path(key_path)-- token_fd, token_path = tempfile.mkstemp(prefix="nvidia-client-token-", dir=temp_dir, text=True)- with os.fdopen(token_fd, "w", encoding="utf-8") as host_token_stream:- host_token_stream.write(client_token)- host_client_token_file = Path(token_path)- await environment.upload_file(host_key_file, key_file.as_posix())- await environment.upload_file(host_client_token_file, client_token_file.as_posix())+ # The selected secure Docker environment streams ``env=`` values+ # over Compose stdin. Materialize both secrets only inside the+ # not-yet-exposed task container, then discard the transient names.+ # Do not route this through BaseInstalledAgent._exec: Harbor 0.13.2+ # attaches that helper's raw ``env`` mapping to DEBUG LogRecords,+ # which structured/custom handlers may serialize.+ handoff_result = await sensitive_exec(+ command=(+ "set -eu; umask 077; "+ f"printf '%s' \"${{{_NVIDIA_BUILD_BRIDGE_API_KEY_ENV}}}\" > "+ f"{shlex.quote(key_file.as_posix())}; "+ f"printf '%s' \"${{{_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV}}}\" > "+ f"{shlex.quote(client_token_file.as_posix())}; "+ f"unset {_NVIDIA_BUILD_BRIDGE_API_KEY_ENV} {_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV}"+ ),+ env={+ _NVIDIA_BUILD_BRIDGE_API_KEY_ENV: api_key,+ _NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV: client_token,+ },+ user="root",+ )+ self._require_success(handoff_result, "secret handoff")start_result = await self._bridge_raw_exec(environment,@@ -565,17 +588,27 @@ class _NvidiaBuildBridgeAgent:client_env = getattr(self, "_nvidia_build_bridge_client_env", None)if client_env is None:return await super().exec_as_agent(environment, command=command, env=env, cwd=cwd, timeout_sec=timeout_sec)+ sensitive_exec = self._sensitive_exec(environment)routed_env = dict(env or {})+ routed_env.update(getattr(self, "_extra_env", {}) or {})routed_env.update(client_env)routed_env.pop("NVIDIA_API_KEY", None)routed_command = self._rewrite_bridge_client_command(command)- return await super().exec_as_agent(- environment,- command=f"env -u NVIDIA_API_KEY bash -c {shlex.quote(routed_command)}",+ # Harbor 0.13.2 attaches BaseInstalledAgent._exec's merged env to DEBUG+ # LogRecords, which structured/custom handlers may serialize.+ # Call the selected secure environment directly so its stdin transport+ # can protect the per-trial bridge capability as well.+ result = await sensitive_exec(+ command=(f"env -u NVIDIA_API_KEY bash -o pipefail -c {shlex.quote(routed_command)}"),env=routed_env,cwd=cwd,timeout_sec=timeout_sec,)+ if result.return_code != 0:+ raise NonZeroAgentExitCodeError(+ f"NVIDIA Build bridge client command failed with exit code {result.return_code}"+ )+ return resultasync def run(self, instruction, environment: BaseEnvironment, context) -> None: # type: ignore[no-untyped-def]self._nvidia_build_bridge_started = Falsediff --git a/src/skillevaluator/tier3/harbor/local_environment.py b/src/skillevaluator/tier3/harbor/local_environment.pyindex d82a5c1c..9be41907 100644--- a/src/skillevaluator/tier3/harbor/local_environment.py+++ b/src/skillevaluator/tier3/harbor/local_environment.py@@ -589,6 +589,23 @@ class SkillEvaluatorLocalEnvironment(BaseEnvironment):finally:self._active_processes.pop(proc, None)+ async def exec_with_sensitive_env(+ self,+ command: str,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ timeout_sec: int | None = None,+ user: str | int | None = None,+ ) -> ExecResult:+ """Execute with values delivered through the existing stdin-only bootstrap."""+ return await self.exec(+ command=command,+ cwd=cwd,+ env=env,+ timeout_sec=timeout_sec,+ user=user,+ )+@staticmethodasync def _terminate_process_tree(proc: asyncio.subprocess.Process,diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 6d5cf363..c647b390 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -16,10 +16,10 @@ import subprocessimport tempfileimport timeimport tomllib-from collections.abc import Iterator, Mapping+from collections.abc import Mappingfrom concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait-from contextlib import ExitStack, contextmanager-from dataclasses import dataclass+from contextlib import ExitStack+from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom functools import wrapsfrom pathlib import Path@@ -70,6 +70,12 @@ from skillevaluator.tier3.harbor.report_data import ()from skillevaluator.tier3.harbor.secure_copy import copytree_securefrom skillevaluator.tier3.harbor.secure_docker_environment import SECURE_DOCKER_ENV_IMPORT_PATH+from skillevaluator.tier3.harbor.sensitive_stdin import (+ NVIDIA_BUILD_KEY_STDIN_ENV as _NVIDIA_BUILD_KEY_STDIN_ENV,+)+from skillevaluator.tier3.harbor.sensitive_stdin import (+ NVIDIA_BUILD_STDIN_SENTINEL as _NVIDIA_BUILD_STDIN_SENTINEL,+)from skillevaluator.tier3.output_provenance import (mark_generated_output_root,remove_generated_output_root_if_owned,@@ -327,33 +333,34 @@ def format_harbor_view_command(jobs_dir: Path | str, *, multiline: bool = False)return f"{command} {path}" if not multiline else f"{command} \\\n {path}"-@contextmanager+@dataclass(frozen=True)+class _NvidiaBuildKeyHandoff:+ """Sanitized child environment plus an optional stdin credential payload."""++ subprocess_env: dict[str, str] = field(repr=False)+ stdin_text: str | None = field(default=None, repr=False, compare=False)++def _nvidia_build_key_handoff(run_env: Mapping[str, str],*,env_mode: str,-) -> Iterator[dict[str, str]]:- """Replace the host Build key with a temporary file-backed sentinel."""+) -> _NvidiaBuildKeyHandoff:+ """Replace the host Build key with a stdin-backed sentinel."""subprocess_env = dict(run_env)- key_handoff: tempfile.TemporaryDirectory[str] | None = None+ subprocess_env.pop(_NVIDIA_BUILD_KEY_FILE_ENV, None)+ subprocess_env.pop(_NVIDIA_BUILD_KEY_STDIN_ENV, None)api_key = subprocess_env.get("NVIDIA_API_KEY", "")if (env_mode == "docker"and subprocess_env.get("SKILL_EVAL_LLM_PROVIDER") == "nv_build"and api_key- and api_key != _NVIDIA_BUILD_FILE_SENTINEL+ and api_key not in {_NVIDIA_BUILD_FILE_SENTINEL, _NVIDIA_BUILD_STDIN_SENTINEL}):- key_handoff = tempfile.TemporaryDirectory(prefix="skillevaluator-nvidia-build-host-")- key_file = Path(key_handoff.name) / "nvidia-api-key"- key_file.write_text(api_key, encoding="utf-8")- key_file.chmod(0o600)- subprocess_env["NVIDIA_API_KEY"] = _NVIDIA_BUILD_FILE_SENTINEL- subprocess_env[_NVIDIA_BUILD_KEY_FILE_ENV] = str(key_file)- try:- yield subprocess_env- finally:- if key_handoff is not None:- key_handoff.cleanup()+ subprocess_env["NVIDIA_API_KEY"] = _NVIDIA_BUILD_STDIN_SENTINEL+ subprocess_env[_NVIDIA_BUILD_KEY_STDIN_ENV] = "1"+ return _NvidiaBuildKeyHandoff(subprocess_env, api_key)+ return _NvidiaBuildKeyHandoff(subprocess_env)def build_harbor_run_command(@@ -1259,15 +1266,16 @@ def _run_harbor(verifier_env=verifier_env,)try:- with _nvidia_build_key_handoff(run_env, env_mode=env_mode) as subprocess_env:- result = subprocess.run(- command,- capture_output=True,- text=True,- env=subprocess_env,- timeout=7200,- check=False,- )+ handoff = _nvidia_build_key_handoff(run_env, env_mode=env_mode)+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ input=handoff.stdin_text,+ env=handoff.subprocess_env,+ timeout=7200,+ check=False,+ )except (OSError, subprocess.TimeoutExpired) as exc:return False, str(exc)if result.returncode == 0:@@ -1928,6 +1936,23 @@ def _run_harbor_eval_impl(return {"error": prereq_errors}reporter.emit(ProgressEvent(stage="environment-preflight", state="complete", detail=env_mode))+ # Resolve the effective source before constructing credential-probe targets.+ # Native Harbor tasks can select the standard-grader judge model at task or+ # step scope, so the provider fallback is not necessarily the runtime model.+ evals_exists = find_evals_file(evaluator_skill_path) is not None+ native_exists = (evaluator_skill_path / "evals" / "harbor").exists()+ if task_source == "auto":+ task_source = "evals_json" if evals_exists else "native_harbor" if native_exists else ""+ if task_source == "evals_json" and not evals_exists:+ reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="evaluation dataset missing"))+ return {"error": ["No evals/evals.json found. Run create-eval-dataset or add a dataset."]}+ if task_source == "native_harbor" and not native_exists:+ reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="native Harbor tasks missing"))+ return {"error": ["No native Harbor task source found at evals/harbor."]}+ if task_source not in {"evals_json", "native_harbor"}:+ reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="invalid task source"))+ return {"error": ["harbor.task_source must be auto, evals_json, or native_harbor"]}+reporter.emit(ProgressEvent(stage="credential-validation", state="running"))if runtime_errors:reporter.emit(ProgressEvent(stage="credential-validation", state="failed", detail="; ".join(runtime_errors)))@@ -1949,10 +1974,182 @@ def _run_harbor_eval_impl(for agent in agentsif (import_path := _nvidia_build_agent_import_path(provider, agent, env_mode)) is not None}- reporter.set_secret_values(- set().union(*(secret_values_from_environment(plan.subprocess_env) for plan in runtime_plans.values()))+ runtime_secret_values = set().union(+ *(secret_values_from_environment(plan.subprocess_env) for plan in runtime_plans.values())+ )++ # Probe each exact agent route before reserving output space, building images,+ # or staging tasks. The runtime-preflight module imports runner helpers, so+ # this import must remain lazy to avoid a module cycle.+ from skillevaluator.tier3.harbor.runtime_preflight import (+ CredentialProbeDisposition,+ credential_probe_disposition,+ probe_model,)- reporter.emit(ProgressEvent(stage="credential-validation", state="complete", detail="credentials validated"))++ probe_targets: dict[+ tuple[str, str, str | None, str | None, str | None],+ tuple[ProviderConfig, list[str]],+ ] = {}+ probe_degraded: list[str] = []+ credential_validation_targets: list[dict[str, Any]] = []+ judge_config = _judge_model_config(provider, provider_env, grading_mode)++ def add_probe_target(label: str, selected_provider: ProviderConfig) -> None:+ route_key = (+ selected_provider.provider,+ selected_provider.model,+ selected_provider.api_key,+ selected_provider.base_url,+ selected_provider.region,+ )+ target = probe_targets.get(route_key)+ if target is None:+ probe_targets[route_key] = (selected_provider, [label])+ else:+ target[1].append(label)++ for agent in agents:+ add_probe_target(agent, runtime_plans[agent].provider)++ if grading_mode != "custom_only":+ if task_source == "native_harbor" and not bool(judge_config["override_applied"]):+ detail = (+ "native Harbor resolves the effective judge model at runtime; "+ "task or step verifier env may supersede the configured fallback"+ )+ probe_degraded.append(f"standard grader: {detail}")+ judge_config["catalog_verification"] = "inconclusive"+ judge_config["effective_model_source"] = "native_harbor_runtime"+ credential_validation_targets.append(+ {+ "labels": ["standard grader"],+ "provider": provider.provider,+ "model": None,+ "fallback_model": provider.model,+ "status": "inconclusive",+ "detail": detail,+ }+ )+ else:+ judge_model = str(judge_config["model"])+ litellm_model = str(getattr(provider, "litellm_model", f"{provider.provider}/{provider.model}"))+ litellm_prefix = litellm_model.partition("/")[0] or provider.provider+ add_probe_target(+ "standard grader",+ ProviderConfig(+ provider=provider.provider,+ model=judge_model,+ api_key=provider.api_key,+ base_url=provider.base_url,+ litellm_model=f"{litellm_prefix}/{judge_model}",+ region=getattr(provider, "region", None),+ credential_env=getattr(provider, "credential_env", None),+ base_url_env=getattr(provider, "base_url_env", None),+ ),+ )++ runtime_secret_values.update(+ selected_provider.api_key for selected_provider, _labels in probe_targets.values() if selected_provider.api_key+ )+ reporter.set_secret_values(runtime_secret_values)++ with ThreadPoolExecutor(max_workers=min(len(probe_targets), 4)) as probe_pool:+ probe_futures = {+ route_key: probe_pool.submit(probe_model, selected_provider)+ for route_key, (selected_provider, _labels) in probe_targets.items()+ }++ probe_errors: list[str] = []+ for route_key, (selected_provider, selected_labels) in probe_targets.items():+ label = ", ".join(selected_labels)+ try:+ probe = probe_futures[route_key].result()+ except Exception as exc:+ safe_detail = f"model catalog probe failed: {type(exc).__name__}"+ probe_degraded.append(f"{label}: {safe_detail}")+ credential_validation_targets.append(+ {+ "labels": list(selected_labels),+ "provider": selected_provider.provider,+ "model": selected_provider.model,+ "status": "degraded",+ "detail": safe_detail,+ }+ )+ if "standard grader" in selected_labels:+ judge_config["catalog_verification"] = "degraded"+ continue++ safe_detail = redact_progress_detail(probe.detail, secret_values=runtime_secret_values)+ disposition = credential_probe_disposition(selected_provider, probe)+ if probe.ok and disposition == CredentialProbeDisposition.DEGRADED:+ safe_detail = "model catalog access does not verify runtime credentials for this endpoint"+ credential_validation_targets.append(+ {+ "labels": list(selected_labels),+ "provider": selected_provider.provider,+ "model": selected_provider.model,+ "status": disposition.value,+ "detail": safe_detail,+ }+ )+ if "standard grader" in selected_labels:+ judge_config["catalog_verification"] = disposition.value+ if disposition == CredentialProbeDisposition.FATAL:+ probe_errors.append(f"{label} provider verification failed: {safe_detail}")+ elif disposition == CredentialProbeDisposition.DEGRADED:+ probe_degraded.append(f"{label}: {safe_detail}")++ if probe_errors:+ reporter.emit(+ ProgressEvent(+ stage="credential-validation",+ state="failed",+ detail="; ".join(probe_errors),+ )+ )+ return {"error": probe_errors}+ if probe_degraded:+ reporter.emit(+ ProgressEvent(+ stage="credential-validation",+ state="degraded",+ detail=(+ "credential configuration resolved; live catalog verification inconclusive: "+ f"{'; '.join(probe_degraded)}; continuing to evaluation"+ ),+ )+ )+ else:+ reporter.emit(+ ProgressEvent(+ stage="credential-validation",+ state="complete",+ detail="credentials and selected models verified",+ )+ )+ run_config = {+ "config_file": str(config_path.relative_to(evaluator_skill_path)) if config_path else "none",+ "harbor": {+ "environment": {"value": env_mode, "source": env_mode_source},+ "n_attempts": n_attempts,+ "stop_on_pass": bool(stop_on_pass),+ "n_concurrent": n_concurrent,+ "timeout_multiplier": timeout_multiplier,+ "base_image_mode": base_image_mode,+ "jobs_retained": keep_harbor_jobs,+ },+ "provider": {"name": provider.provider, "model": provider.model},+ "judge": judge_config,+ "credential_validation": {+ "status": "degraded" if probe_degraded else "verified",+ "targets": credential_validation_targets,+ },+ "task_source": task_source,+ "grading": {"mode": grading_mode},+ "agents": model_resolution,+ }verifier_env = {**configured_runtime_env, **provider_env}staged_verifier_env = {name: f"${{{name}}}" for name in verifier_env if name not in _VERIFIER_JUDGE_MODEL_ENV_VARS}job_judge_verifier_env = _job_judge_verifier_env(provider_env, grading_mode)@@ -1968,20 +2165,6 @@ def _run_harbor_eval_impl(reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail=str(exc)))return {"error": [str(exc)]}- evals_exists = find_evals_file(evaluator_skill_path) is not None- native_exists = (evaluator_skill_path / "evals" / "harbor").exists()- if task_source == "auto":- task_source = "evals_json" if evals_exists else "native_harbor" if native_exists else ""- if task_source == "evals_json" and not evals_exists:- reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="evaluation dataset missing"))- return {"error": ["No evals/evals.json found. Run create-eval-dataset or add a dataset."]}- if task_source == "native_harbor" and not native_exists:- reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="native Harbor tasks missing"))- return {"error": ["No native Harbor task source found at evals/harbor."]}- if task_source not in {"evals_json", "native_harbor"}:- reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="invalid task source"))- return {"error": ["harbor.task_source must be auto, evals_json, or native_harbor"]}-root = Path(output_dir) if output_dir is not None else skill_path / "evals" / "results"try:validate_output_provenance_key_location(@@ -2027,6 +2210,29 @@ def _run_harbor_eval_impl())+ def _persist_pre_execution_failure(errors: list[str]) -> dict[str, Any]:+ """Retain redacted probe provenance for failures after run reservation."""+ failed_result: dict[str, Any] = {+ "skill_name": skill_path.name,+ "execution_status": "failed",+ "execution_errors": errors,+ "error": errors,+ "run_id": run_id,+ "run_dir": str(run_dir),+ "harbor_jobs_dir": str(jobs_dir),+ "harbor_jobs_retained": jobs_dir.is_dir(),+ "duration_seconds": round(time.monotonic() - started_at, 3),+ "result_path": str(result_path),+ "agents": {},+ "run_config": run_config,+ }+ write_output_file_atomically(+ run_dir / "run_config.json",+ json.dumps(run_config, indent=2).encode("utf-8"),+ )+ write_output_file_atomically(result_path, json.dumps(failed_result, indent=2).encode("utf-8"))+ return failed_result+reservation_identity: tuple[int, int] | None = Nonetry:reservation_metadata = run_dir.lstat()@@ -2152,7 +2358,7 @@ def _run_harbor_eval_impl(reporter.emit(ProgressEvent(stage="baseline-tasks", state="skipped", detail="baseline disabled"))except (OSError, ValueError) as exc:reporter.emit(ProgressEvent(stage=staging_failure_stage, state="failed", detail=str(exc)))- return {"error": [str(exc)], "run_dir": str(run_dir)}+ return _persist_pre_execution_failure([str(exc)])task_names = expected_task_names or []expected_trials = len(task_names) * n_attempts@@ -2220,20 +2426,7 @@ def _run_harbor_eval_impl(if preflight_errors:detail = "; ".join(preflight_errors)reporter.emit(ProgressEvent(stage="agent-runtime-preflight", state="failed", detail=detail))- failed_result: dict[str, Any] = {- "skill_name": skill_path.name,- "execution_status": "failed",- "execution_errors": preflight_errors,- "error": preflight_errors,- "run_id": run_id,- "run_dir": str(run_dir),- "harbor_jobs_dir": str(jobs_dir),- "harbor_jobs_retained": True,- "duration_seconds": round(time.monotonic() - started_at, 3),- "result_path": str(result_path),- "agents": {},- }- write_output_file_atomically(result_path, json.dumps(failed_result, indent=2).encode("utf-8"))+ failed_result = _persist_pre_execution_failure(preflight_errors)_emit_run_finished("failed", "agent runtime preflight failed")return failed_resultreporter.emit(@@ -2351,23 +2544,6 @@ def _run_harbor_eval_impl(_emit_run_finished("failed", "result collection failed")raisereporter.emit(ProgressEvent(stage="collection", state="complete", detail="Harbor results collected"))- run_config = {- "config_file": str(config_path.relative_to(evaluator_skill_path)) if config_path else "none",- "harbor": {- "environment": {"value": env_mode, "source": env_mode_source},- "n_attempts": n_attempts,- "stop_on_pass": bool(stop_on_pass),- "n_concurrent": n_concurrent,- "timeout_multiplier": timeout_multiplier,- "base_image_mode": base_image_mode,- "jobs_retained": keep_harbor_jobs,- },- "provider": {"name": provider.provider, "model": provider.model},- "judge": _judge_model_config(provider, provider_env, grading_mode),- "task_source": task_source,- "grading": {"mode": grading_mode},- "agents": model_resolution,- }dataset_truth = _persist_dataset_truth(run_dir, fallback_task_ids=task_names)results.update({diff --git a/src/skillevaluator/tier3/harbor/runtime_preflight.py b/src/skillevaluator/tier3/harbor/runtime_preflight.pyindex d4f6930b..d7ce0d55 100644--- a/src/skillevaluator/tier3/harbor/runtime_preflight.py+++ b/src/skillevaluator/tier3/harbor/runtime_preflight.py@@ -5,17 +5,72 @@from __future__ import annotations+import errnoimport json+import math+import os+import shlex+import sslimport subprocessfrom collections.abc import Mappingfrom dataclasses import dataclass+from enum import StrEnumfrom pathlib import Path+from queue import Empty, Queue+from threading import BoundedSemaphore, Thread+from time import monotonicfrom typing import TYPE_CHECKING+from urllib.parse import urlsplit+from urllib.request import getproxiesimport boto3-from botocore.exceptions import BotoCoreError, ClientError+from botocore import exceptions as botocore_exceptions+from botocore.config import Config as BotoConfig+from botocore.exceptions import (+ ApiVersionNotFoundError,+ BaseEndpointResolverError,+ BotoCoreError,+ ClientError,+ ConfigNotFound,+ ConfigParseError,+ CredentialRetrievalError,+ DataNotFoundError,+ EndpointProviderError,+ HTTPClientError,+ InvalidConfigError,+ InvalidDefaultsMode,+ InvalidIMDSEndpointError,+ InvalidIMDSEndpointModeError,+ InvalidMaxRetryAttemptsError,+ InvalidProxiesConfigError,+ InvalidRegionError,+ InvalidRetryConfigurationError,+ InvalidSTSRegionalEndpointsConfigError,+ MissingDependencyException,+ NoAuthTokenError,+ NoCredentialsError,+ ParamValidationError,+ PartialCredentialsError,+ ProfileNotFound,+ RefreshWithMFAUnsupportedError,+ ServiceNotInRegionError,+ SSOTokenLoadError,+ UnauthorizedSSOTokenError,+ UnknownCredentialError,+ UnknownRegionError,+ UnknownSignatureVersionError,+ UnsupportedSignatureVersionError,+)+from botocore.exceptions import (+ SSLError as BotocoreSSLError,+)-from skillevaluator.model_catalog import ModelCatalogError, fetch_model_records+from skillevaluator.model_catalog import (+ ModelCatalogError,+ ModelCatalogFailureKind,+ fetch_anthropic_model_record,+ fetch_model_records,+)from skillevaluator.tier3.harbor.progress import redact_progress_detailfrom skillevaluator.tier3.harbor.runner import _nvidia_build_key_handoff, build_harbor_run_command@@ -44,6 +99,698 @@ class ModelProbeResult:provider: strmodel: strdetail: str+ failure_kind: ModelCatalogFailureKind | None = None+ http_status: int | None = None+ catalog_authoritative: bool = True+++class CredentialProbeDisposition(StrEnum):+ """How Tier 3 should act on a model-catalog credential probe."""++ VERIFIED = "verified"+ FATAL = "fatal"+ DEGRADED = "degraded"+++_BEDROCK_PROBE_SLOT = BoundedSemaphore(4)+_BEDROCK_AUTHENTICATION_ERRORS: tuple[type[BaseException], ...] = (+ NoAuthTokenError,+ NoCredentialsError,+ RefreshWithMFAUnsupportedError,+ SSOTokenLoadError,+ UnauthorizedSSOTokenError,+)+_BEDROCK_INVALID_CONFIGURATION_ERRORS: tuple[type[BaseException], ...] = (+ ApiVersionNotFoundError,+ BaseEndpointResolverError,+ ConfigNotFound,+ ConfigParseError,+ DataNotFoundError,+ EndpointProviderError,+ InvalidConfigError,+ InvalidDefaultsMode,+ InvalidIMDSEndpointError,+ InvalidIMDSEndpointModeError,+ InvalidProxiesConfigError,+ InvalidRegionError,+ InvalidRetryConfigurationError,+ InvalidSTSRegionalEndpointsConfigError,+ MissingDependencyException,+ ParamValidationError,+ PartialCredentialsError,+ ProfileNotFound,+ ServiceNotInRegionError,+ UnknownCredentialError,+ UnknownRegionError,+ UnknownSignatureVersionError,+ UnsupportedSignatureVersionError,+)+for _error_name, _target in (+ ("LoginError", "authentication"),+ ("InvalidChecksumConfigError", "configuration"),+ ("UnknownTokenProviderError", "configuration"),+ ("UnsupportedServiceProtocolsError", "configuration"),+):+ _error_type = getattr(botocore_exceptions, _error_name, None)+ if not isinstance(_error_type, type) or not issubclass(_error_type, BotoCoreError):+ continue+ if _target == "authentication":+ _BEDROCK_AUTHENTICATION_ERRORS += (_error_type,)+ else:+ _BEDROCK_INVALID_CONFIGURATION_ERRORS += (_error_type,)++_BEDROCK_CREDENTIAL_BOOTSTRAP_TRANSIENT_CODES = frozenset(+ {+ "IDPCommunicationError",+ "IDPCommunicationErrorException",+ "InternalFailure",+ "InternalServerError",+ "InternalServerException",+ "RequestTimeout",+ "RequestTimeoutException",+ "ServiceUnavailable",+ "ServiceUnavailableException",+ "Throttling",+ "ThrottlingException",+ "TooManyRequestsError",+ "TooManyRequestsException",+ }+)++_BEDROCK_INTEGER_ENVIRONMENT_VARIABLES = (+ "AWS_MAX_ATTEMPTS",+ "AWS_METADATA_SERVICE_NUM_ATTEMPTS",+ "AWS_METADATA_SERVICE_TIMEOUT",+)+_BEDROCK_ENDPOINT_ENVIRONMENT_VARIABLES = (+ "AWS_ENDPOINT_URL",+ "AWS_ENDPOINT_URL_BEDROCK",+ "AWS_ENDPOINT_URL_BEDROCK_RUNTIME",+ "AWS_ENDPOINT_URL_STS",+)+_BEDROCK_RUNTIME_SERVICE_MODELS = ("bedrock", "bedrock-runtime")+_BEDROCK_CREDENTIAL_PROCESS_TRANSIENT_ERRNOS = frozenset(+ {errno.EAGAIN, errno.EINTR, errno.EMFILE, errno.ENFILE, errno.ENOMEM, errno.ETIMEDOUT}+)+++def _bedrock_scoped_config(session: object | None) -> Mapping[str, object]:+ botocore_session = getattr(session, "_session", None)+ get_scoped_config = getattr(botocore_session, "get_scoped_config", None)+ if not callable(get_scoped_config):+ return {}+ try:+ scoped_config = get_scoped_config()+ except Exception:+ return {}+ if not isinstance(scoped_config, Mapping):+ return {}+ return scoped_config+++def _bedrock_credential_process(session: object | None) -> str | None:+ credential_process = _bedrock_scoped_config(session).get("credential_process")+ return credential_process if isinstance(credential_process, str) else None+++def _bedrock_active_credential_service_models(session: object | None) -> tuple[str, ...]:+ profile_configs = [_bedrock_scoped_config(session)]+ botocore_session = getattr(session, "_session", None)+ full_config = getattr(botocore_session, "full_config", None)+ profiles = full_config.get("profiles") if isinstance(full_config, Mapping) else None+ visited_profiles: set[str] = set()+ source_profile = profile_configs[0].get("source_profile")+ while isinstance(source_profile, str) and isinstance(profiles, Mapping) and source_profile not in visited_profiles:+ visited_profiles.add(source_profile)+ source_config = profiles.get(source_profile)+ if not isinstance(source_config, Mapping):+ break+ profile_configs.append(source_config)+ source_profile = source_config.get("source_profile")++ services: list[str] = []+ if any("role_arn" in config for config in profile_configs) or (+ "AWS_ROLE_ARN" in os.environ and "AWS_WEB_IDENTITY_TOKEN_FILE" in os.environ+ ):+ services.append("sts")+ if any(any(variable in config for variable in ("sso_start_url", "sso_session")) for config in profile_configs):+ services.extend(("sso", "sso-oidc"))+ if any("login_session" in config for config in profile_configs):+ services.append("signin")+ return tuple(services)+++def _is_unusable_imds_credential_response(request: object, response: object) -> bool:+ if getattr(request, "method", None) != "GET" or getattr(response, "status_code", None) != 200:+ return False+ request_url = getattr(request, "url", None)+ if not isinstance(request_url, str):+ return False+ try:+ path = urlsplit(request_url).path+ except ValueError:+ return False+ credential_path = "/latest/meta-data/iam/security-credentials/"+ if not path.startswith(credential_path):+ return False+ try:+ body = response.text+ except Exception:+ return True+ if path.rstrip("/") == credential_path.rstrip("/"):+ allowed_role_characters = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")+ return not (1 <= len(body) <= 64 and all(character in allowed_role_characters for character in body))+ if not body.strip():+ return True+ try:+ payload = json.loads(body)+ except (TypeError, ValueError):+ return True+ required_fields = {"AccessKeyId", "SecretAccessKey", "Token", "Expiration"}+ return not isinstance(payload, Mapping) or not required_fields.issubset(payload)+++def _monitor_bedrock_metadata_unavailability(session: object) -> list[bool]:+ """Retain transient metadata failures that Botocore may collapse to no credentials."""+ unavailable = [False]+ botocore_session = getattr(session, "_session", None)+ get_component = getattr(botocore_session, "get_component", None)+ if not callable(get_component):+ return unavailable+ try:+ resolver = get_component("credential_provider")+ get_provider = resolver.get_provider+ except Exception:+ return unavailable++ transports: list[object] = []+ for provider_name, fetcher_name in (("container-role", "_fetcher"), ("iam-role", "_role_fetcher")):+ try:+ provider = get_provider(provider_name)+ fetcher = getattr(provider, fetcher_name)+ transport = fetcher._session+ if callable(getattr(transport, "send", None)):+ transports.append(transport)+ except Exception:+ continue++ for transport in transports:+ original_send = transport.send++ def tracked_send(request, *args, _send=original_send, **kwargs):+ try:+ response = _send(request, *args, **kwargs)+ except Exception:+ unavailable[0] = True+ raise+ status_code = getattr(response, "status_code", None)+ if (+ isinstance(status_code, int)+ and not isinstance(status_code, bool)+ and (status_code in {408, 429} or status_code >= 500)+ ) or _is_unusable_imds_credential_response(request, response):+ unavailable[0] = True+ return response++ try:+ transport.send = tracked_send+ except Exception:+ continue+ return unavailable+++def _validate_bedrock_local_sdk_configuration(session: object) -> None:+ """Force local values that the probe's bounded overrides could mask."""+ botocore_session = getattr(session, "_session", None)+ get_config_variable = getattr(botocore_session, "get_config_variable", None)+ if callable(get_config_variable):+ max_attempts = get_config_variable("max_attempts")+ if max_attempts is not None and max_attempts < 1:+ raise InvalidMaxRetryAttemptsError(provided_max_attempts=max_attempts, min_value=1)+ get_config_variable("metadata_service_num_attempts")+ metadata_service_timeout = get_config_variable("metadata_service_timeout")+ if metadata_service_timeout is not None and metadata_service_timeout <= 0:+ raise InvalidConfigError(error_msg="metadata service timeout must be greater than zero")+ if get_config_variable("csm_enabled"):+ get_config_variable("csm_port")+ get_service_model = getattr(botocore_session, "get_service_model", None)+ if callable(get_service_model):+ for service_name in _BEDROCK_RUNTIME_SERVICE_MODELS:+ get_service_model(service_name)+++def _is_invalid_bedrock_ca_bundle(session: object | None) -> bool:+ botocore_session = getattr(session, "_session", None)+ get_config_variable = getattr(botocore_session, "get_config_variable", None)+ try:+ value = get_config_variable("ca_bundle") if callable(get_config_variable) else os.environ.get("AWS_CA_BUNDLE")+ except Exception:+ value = os.environ.get("AWS_CA_BUNDLE")+ if not isinstance(value, str) or not value:+ return False+ try:+ ssl.create_default_context(cafile=value)+ except OSError:+ return True+ return False+++def _bedrock_client_uses_tls(client: object) -> bool:+ endpoint_url = getattr(getattr(client, "meta", None), "endpoint_url", None)+ return isinstance(endpoint_url, str) and urlsplit(endpoint_url).scheme.casefold() == "https"+++def _is_builtin_botocore_data_path(loader: object, loaded_path: object) -> bool:+ builtin_data_path = getattr(loader, "BUILTIN_DATA_PATH", None)+ if not isinstance(builtin_data_path, str) or not isinstance(loaded_path, str):+ return False+ try:+ builtin_root = Path(builtin_data_path).expanduser().resolve()+ loaded_base = Path(loaded_path).expanduser()+ except OSError:+ return False+ found_data_file = False+ for suffix in (".json", ".json.gz"):+ candidate = Path(f"{loaded_base}{suffix}")+ try:+ if not candidate.is_file():+ continue+ found_data_file = True+ resolved_path = candidate.resolve()+ except OSError:+ return False+ if resolved_path != builtin_root and builtin_root not in resolved_path.parents:+ return False+ return found_data_file+++def _bedrock_endpoint_metadata_is_builtin(+ session: object,+ client: object,+ *,+ service_name: str,+) -> bool:+ """Require endpoint authority to come from Botocore's packaged data."""+ botocore_session = getattr(session, "_session", None)+ get_component = getattr(botocore_session, "get_component", None)+ if not callable(get_component):+ return False+ try:+ loader = get_component("data_loader")+ load_data_with_path = loader.load_data_with_path+ for data_name in ("endpoints", "partitions"):+ _data, loaded_path = load_data_with_path(data_name)+ if not _is_builtin_botocore_data_path(loader, loaded_path):+ return False++ service_model = getattr(getattr(client, "meta", None), "service_model", None)+ api_version = getattr(service_model, "api_version", None)+ if not isinstance(api_version, str) or not api_version:+ api_version = loader.determine_latest_version(service_name, "endpoint-rule-set-1")+ _rules, rules_path = load_data_with_path(f"{service_name}/{api_version}/endpoint-rule-set-1")+ return _is_builtin_botocore_data_path(loader, rules_path)+ except Exception:+ return False+++def _is_native_bedrock_endpoint(+ session: object,+ client: object,+ *,+ service_name: str,+ region_name: str,+) -> bool:+ endpoint_url = getattr(getattr(client, "meta", None), "endpoint_url", None)+ if endpoint_url is None:+ # Lightweight test doubles predate endpoint-authority evidence.+ return True+ if not isinstance(endpoint_url, str):+ return False+ try:+ endpoint = urlsplit(endpoint_url)+ port = endpoint.port+ except ValueError:+ return False+ if (+ endpoint.scheme.casefold() != "https"+ or endpoint.hostname is None+ or endpoint.username is not None+ or endpoint.password is not None+ or port not in {None, 443}+ or endpoint.path not in {"", "/"}+ or endpoint.query+ or endpoint.fragment+ ):+ return False+ if not _bedrock_endpoint_metadata_is_builtin(session, client, service_name=service_name):+ return False++ botocore_session = getattr(session, "_session", None)+ get_internal_component = getattr(botocore_session, "_get_internal_component", None)+ if not callable(get_internal_component):+ return False+ try:+ resolved = get_internal_component("endpoint_resolver").construct_endpoint(service_name, region_name)+ except Exception:+ return False+ if not isinstance(resolved, Mapping):+ return False+ allowed_hosts = {str(resolved.get("hostname") or "").casefold()}+ variants = resolved.get("variants")+ if isinstance(variants, list):+ for variant in variants:+ if not isinstance(variant, Mapping):+ continue+ hostname = variant.get("hostname")+ if not isinstance(hostname, str):+ continue+ try:+ allowed_hosts.add(+ hostname.format(+ service=service_name,+ region=region_name,+ dnsSuffix=variant.get("dnsSuffix", resolved.get("dnsSuffix", "")),+ ).casefold()+ )+ except (KeyError, ValueError):+ continue+ return endpoint.hostname.casefold() in allowed_hosts+++def _is_bedrock_local_cached_token_error(exc: Exception) -> bool:+ """Identify date parsing failures sourced from local SSO/login caches."""+ error_type = type(exc)+ parser_error = error_type.__name__ == "ParserError" and error_type.__module__.startswith("dateutil.parser")+ if not parser_error and not isinstance(exc, TypeError):+ return False+ traceback = exc.__traceback__+ saw_dateutil_parser = parser_error+ saw_local_cache_owner = False+ while traceback is not None:+ frame = traceback.tb_frame+ module_name = frame.f_globals.get("__name__")+ owner = frame.f_locals.get("self")+ owner_name = type(owner).__name__ if owner is not None else ""+ if isinstance(module_name, str) and module_name.startswith("dateutil.parser"):+ saw_dateutil_parser = True+ if module_name == "botocore.credentials" and owner_name in {"LoginProvider", "SSOCredentialFetcher"}:+ saw_local_cache_owner = True+ if module_name == "botocore.tokens" and owner_name == "SSOTokenProvider":+ saw_local_cache_owner = True+ traceback = traceback.tb_next+ return saw_dateutil_parser and saw_local_cache_owner+++def _is_bedrock_local_sdk_data_error(exc: Exception) -> bool:+ """Identify failures raised while Botocore reads local model files."""+ traceback = exc.__traceback__+ while traceback is not None:+ frame = traceback.tb_frame+ module_name = frame.f_globals.get("__name__")+ if module_name == "botocore.loaders" and frame.f_code.co_name == "_load_file":+ return True+ traceback = traceback.tb_next+ return False+++def _is_bedrock_local_credential_file_error(exc: Exception) -> bool:+ """Identify text-decoding failures from configured local credential files."""+ if not isinstance(exc, UnicodeError):+ return False+ traceback = exc.__traceback__+ while traceback is not None:+ frame = traceback.tb_frame+ module_name = frame.f_globals.get("__name__")+ owner = frame.f_locals.get("self")+ owner_name = type(owner).__name__ if owner is not None else ""+ if (+ module_name == "botocore.utils"+ and frame.f_code.co_name == "__call__"+ and owner_name == "FileWebIdentityTokenLoader"+ ):+ return True+ if (+ module_name == "botocore.credentials"+ and frame.f_code.co_name == "_build_headers"+ and owner_name == "ContainerProvider"+ ):+ return True+ traceback = traceback.tb_next+ return False+++def _is_bedrock_local_credential_process_output_error(exc: Exception) -> bool:+ """Identify malformed output decoded by a configured credential_process."""+ traceback = exc.__traceback__+ saw_process_provider_load = False+ saw_date_parser = False+ while traceback is not None:+ frame = traceback.tb_frame+ module_name = frame.f_globals.get("__name__")+ owner = frame.f_locals.get("self")+ if module_name == "botocore.credentials" and type(owner).__name__ == "ProcessProvider":+ if frame.f_code.co_name == "_retrieve_credentials_using":+ process = frame.f_locals.get("p")+ return_code = getattr(process, "returncode", None)+ return (+ isinstance(return_code, int)+ and return_code == 0+ and isinstance(+ exc,+ (json.JSONDecodeError, UnicodeError, AttributeError, TypeError, CredentialRetrievalError),+ )+ )+ if frame.f_code.co_name == "load":+ saw_process_provider_load = True+ if isinstance(module_name, str) and module_name.startswith("dateutil.parser"):+ saw_date_parser = True+ traceback = traceback.tb_next+ return saw_process_provider_load and saw_date_parser and isinstance(exc, (TypeError, ValueError))+++def _is_bedrock_local_proxy_configuration_error(exc: Exception) -> bool:+ """Match a proxy parser failure to a locally configured proxy value."""+ if not isinstance(exc, HTTPClientError):+ return False+ underlying = exc.kwargs.get("error") if isinstance(exc.kwargs, Mapping) else None+ urllib3_parse_error = type(underlying).__name__ == "LocationParseError" and type(underlying).__module__.startswith(+ "urllib3.exceptions"+ )+ if not isinstance(underlying, ValueError) and not urllib3_parse_error:+ return False+ for proxy_kind, configured_proxy in getproxies().items():+ if proxy_kind == "no" or not isinstance(configured_proxy, str) or not configured_proxy:+ continue+ if configured_proxy.startswith(("http:", "https:")):+ normalized_proxy = configured_proxy+ elif configured_proxy.startswith("//"):+ normalized_proxy = f"http:{configured_proxy}"+ else:+ normalized_proxy = f"http://{configured_proxy}"+ try:+ parsed_proxy = urlsplit(normalized_proxy)+ _ = parsed_proxy.port+ except ValueError as expected:+ if urllib3_parse_error or underlying.args == expected.args:+ return True+ return False+++def _is_bedrock_local_configuration_value_error(exc: ValueError, *, session: object | None) -> bool:+ """Recognize ValueErrors proven to come from local AWS configuration."""+ integer_variables = list(_BEDROCK_INTEGER_ENVIRONMENT_VARIABLES)+ if os.environ.get("AWS_CSM_ENABLED", "").casefold() == "true":+ integer_variables.append("AWS_CSM_PORT")+ for variable in integer_variables:+ value = os.environ.get(variable)+ if value is None:+ continue+ try:+ int(value)+ except ValueError as expected:+ if exc.args == expected.args:+ return True++ botocore_session = getattr(session, "_session", None)+ get_config_variable = getattr(botocore_session, "get_config_variable", None)+ if callable(get_config_variable):+ config_variables = [+ "max_attempts",+ "metadata_service_num_attempts",+ "metadata_service_timeout",+ ]+ try:+ if get_config_variable("csm_enabled"):+ config_variables.append("csm_port")+ except Exception:+ pass+ for variable in config_variables:+ try:+ get_config_variable(variable)+ except ValueError as expected:+ if exc.args == expected.args:+ return True+ except Exception:+ pass+ credential_process = _bedrock_credential_process(session)+ if credential_process is not None:+ try:+ shlex.split(credential_process)+ except ValueError as expected:+ if exc.args == expected.args:+ return True++ if isinstance(exc, json.JSONDecodeError):+ get_service_model = getattr(botocore_session, "get_service_model", None)+ if callable(get_service_model):+ for service_name in (*_BEDROCK_RUNTIME_SERVICE_MODELS, *_bedrock_active_credential_service_models(session)):+ try:+ get_service_model(service_name)+ except json.JSONDecodeError as expected:+ if exc.args == expected.args:+ return True+ except Exception:+ pass++ for variable in _BEDROCK_ENDPOINT_ENVIRONMENT_VARIABLES:+ value = os.environ.get(variable)+ if value is None:+ continue+ if exc.args == (f"Invalid endpoint: {value}",):+ return True+ try:+ _ = urlsplit(value).port+ except ValueError as expected:+ if exc.args == expected.args:+ return True++ container_uri = os.environ.get("AWS_CONTAINER_CREDENTIALS_FULL_URI")+ if container_uri is not None:+ try:+ container_host = urlsplit(container_uri).hostname+ except ValueError:+ container_host = None+ if isinstance(container_host, str) and str(exc).startswith(f"Unsupported host '{container_host}'"):+ return True++ relative_uri = os.environ.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")+ if relative_uri is not None and exc.args == (f"Invalid endpoint: http://169.254.170.2{relative_uri}",):+ return True++ if exc.args == ("Auth token value is not a legal header value",) and (+ "AWS_CONTAINER_AUTHORIZATION_TOKEN" in os.environ or "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE" in os.environ+ ):+ return True+ message = str(exc)+ return (+ message.startswith("Invalid endpoint: ")+ or message.startswith("Port could not be cast to integer value as ")+ or message.startswith("Unsupported host '")+ or message == "Auth token value is not a legal header value"+ )+++def _is_native_catalog_endpoint(provider: ProviderConfig) -> bool:+ """Return whether catalog HTTP status has the provider's native meaning."""+ provider_name = provider.provider.casefold()+ if provider_name == "anthropic" and not provider.base_url:+ return True+ if not isinstance(provider.base_url, str) or provider.base_url != provider.base_url.strip():+ return False+ if "\\" in provider.base_url or any(character in provider.base_url for character in ("?", "#", ";")):+ return False+ try:+ endpoint = urlsplit(provider.base_url)+ port = endpoint.port+ except (TypeError, ValueError):+ return False+ if (+ endpoint.scheme.casefold() != "https"+ or endpoint.hostname is None+ or endpoint.username is not None+ or endpoint.password is not None+ or port not in {None, 443}+ ):+ return False++ if provider_name in {"openai", "openai-compatible"}:+ return endpoint.hostname.casefold() == "api.openai.com" and endpoint.path in {"/v1", "/v1/"}+ if provider_name == "nv_build":+ return endpoint.hostname.casefold() == "integrate.api.nvidia.com" and endpoint.path in {"/v1", "/v1/"}+ if provider_name == "anthropic":+ return endpoint.hostname.casefold() == "api.anthropic.com" and endpoint.path in {"", "/", "/v1", "/v1/"}+ return False+++def _catalog_listing_is_authoritative(provider: ProviderConfig) -> bool:+ """Return whether absence from the listing proves the model is unusable."""+ # Anthropic aliases resolve through its single-model endpoint but are not+ # guaranteed to appear in the unique-ID listing. Bedrock's foundation-model+ # listing excludes other valid InvokeModel resources such as inference profiles.+ # OpenAI provisioned models can likewise be usable through Responses without+ # appearing in /models, so only NVIDIA Build's native listing is authoritative.+ return provider.provider.casefold() == "nv_build" and _is_native_catalog_endpoint(provider)+++def credential_probe_disposition(+ provider: ProviderConfig,+ probe: ModelProbeResult,+) -> CredentialProbeDisposition:+ """Classify a live catalog probe without rejecting compatible custom gateways."""+ if probe.ok:+ provider_name = provider.provider.casefold()+ if provider_name == "bedrock":+ # Only native catalog + runtime endpoints prove AWS credentials.+ return (+ CredentialProbeDisposition.VERIFIED+ if getattr(probe, "catalog_authoritative", True)+ else CredentialProbeDisposition.DEGRADED+ )+ if provider_name == "nv_build" or not _is_native_catalog_endpoint(provider):+ # NVIDIA Build and compatible gateways may expose a public catalog,+ # so listing a model does not prove that inference credentials work.+ return CredentialProbeDisposition.DEGRADED+ return CredentialProbeDisposition.VERIFIED++ raw_kind = getattr(probe, "failure_kind", None)+ try:+ failure_kind = ModelCatalogFailureKind(raw_kind) if raw_kind is not None else None+ except (TypeError, ValueError):+ failure_kind = ModelCatalogFailureKind.UNKNOWN++ if failure_kind == ModelCatalogFailureKind.AUTHENTICATION:+ return (+ CredentialProbeDisposition.FATAL+ if provider.provider.casefold() == "bedrock" or _is_native_catalog_endpoint(provider)+ else CredentialProbeDisposition.DEGRADED+ )+ if failure_kind == ModelCatalogFailureKind.INVALID_CONFIGURATION:+ return CredentialProbeDisposition.FATAL+ if failure_kind == ModelCatalogFailureKind.MODEL_NOT_FOUND:+ return (+ CredentialProbeDisposition.FATAL+ if provider.provider.casefold() not in {"openai", "openai-compatible"}+ and _is_native_catalog_endpoint(provider)+ else CredentialProbeDisposition.DEGRADED+ )+ if failure_kind == ModelCatalogFailureKind.AUTHORIZATION:+ if provider.provider == "bedrock" or provider.provider.casefold() in {"openai", "openai-compatible"}:+ # ListFoundationModels permission is distinct from InvokeModel. OpenAI+ # restricted keys can likewise allow Responses while denying Models.+ return CredentialProbeDisposition.DEGRADED+ return (+ CredentialProbeDisposition.FATAL+ if _is_native_catalog_endpoint(provider)+ else CredentialProbeDisposition.DEGRADED+ )+ if failure_kind is None:+ # ``probe_model`` reached the catalog but did not find the selected model.+ return (+ CredentialProbeDisposition.FATAL+ if _catalog_listing_is_authoritative(provider)+ else CredentialProbeDisposition.DEGRADED+ )+ return CredentialProbeDisposition.DEGRADEDdef _first_task_name(dataset: Path) -> str | None:@@ -234,38 +981,366 @@ def validate_harbor_agent_only_job_result(return True, ""+def _bedrock_client_error_kind(exc: ClientError) -> tuple[ModelCatalogFailureKind, int | None]:+ """Classify a sanitized AWS service error, including credential providers."""+ response = exc.response if isinstance(exc.response, dict) else {}+ error = response.get("Error") if isinstance(response.get("Error"), dict) else {}+ metadata = response.get("ResponseMetadata") if isinstance(response.get("ResponseMetadata"), dict) else {}+ error_code = str(error.get("Code") or "")+ http_status = metadata.get("HTTPStatusCode")+ if not isinstance(http_status, int) or isinstance(http_status, bool):+ http_status = None++ credential_bootstrap = getattr(exc, "operation_name", "") != "ListFoundationModels"+ if credential_bootstrap and (+ error_code in _BEDROCK_CREDENTIAL_BOOTSTRAP_TRANSIENT_CODES+ or http_status in {408, 429}+ or (isinstance(http_status, int) and http_status >= 500)+ ):+ return ModelCatalogFailureKind.UNAVAILABLE, http_status+ if credential_bootstrap:+ # A permanent upstream credential operation failure means InvokeModel+ # cannot be signed. It is distinct from catalog-only authorization.+ return ModelCatalogFailureKind.AUTHENTICATION, http_status+ if http_status == 401 or error_code in {+ "ExpiredTokenException",+ "ExpiredToken",+ "IncompleteSignature",+ "InvalidAccessKeyId",+ "InvalidClientTokenId",+ "InvalidSignatureException",+ "MissingAuthenticationToken",+ "SignatureDoesNotMatch",+ "UnrecognizedClientException",+ }:+ return ModelCatalogFailureKind.AUTHENTICATION, http_status+ if error_code == "RequestExpired":+ return ModelCatalogFailureKind.INVALID_CONFIGURATION, http_status+ if error_code in {"AccessDenied", "AccessDeniedException"}:+ return ModelCatalogFailureKind.AUTHORIZATION, http_status+ if error_code in {"ServiceUnavailable", "ServiceUnavailableException", "ThrottlingException"} or (+ isinstance(http_status, int) and (http_status == 429 or http_status >= 500)+ ):+ return ModelCatalogFailureKind.UNAVAILABLE, http_status+ return ModelCatalogFailureKind.UNKNOWN, http_status+++def _bedrock_exception_result(+ provider: ProviderConfig,+ exc: Exception,+ *,+ catalog_request: bool,+ session: object | None,+) -> ModelProbeResult:+ """Convert a Bedrock SDK failure to a redacted, policy-safe result."""+ http_status = None+ if isinstance(exc, ClientError):+ failure_kind, http_status = _bedrock_client_error_kind(exc)+ elif (+ _is_bedrock_local_sdk_data_error(exc)+ or _is_bedrock_local_credential_file_error(exc)+ or _is_bedrock_local_credential_process_output_error(exc)+ or _is_bedrock_local_proxy_configuration_error(exc)+ ):+ failure_kind = ModelCatalogFailureKind.INVALID_CONFIGURATION+ elif isinstance(exc, _BEDROCK_AUTHENTICATION_ERRORS):+ failure_kind = ModelCatalogFailureKind.AUTHENTICATION+ elif isinstance(+ exc,+ (+ *_BEDROCK_INVALID_CONFIGURATION_ERRORS,+ FileNotFoundError,+ IsADirectoryError,+ NotADirectoryError,+ PermissionError,+ ),+ ) or (isinstance(exc, OSError) and exc.errno == errno.ENOEXEC and _bedrock_credential_process(session) is not None):+ failure_kind = ModelCatalogFailureKind.INVALID_CONFIGURATION+ elif (+ isinstance(exc, OSError)+ and exc.errno in _BEDROCK_CREDENTIAL_PROCESS_TRANSIENT_ERRNOS+ and _bedrock_credential_process(session) is not None+ ):+ failure_kind = ModelCatalogFailureKind.UNAVAILABLE+ elif _is_bedrock_local_cached_token_error(exc):+ failure_kind = ModelCatalogFailureKind.AUTHENTICATION+ elif isinstance(exc, ValueError):+ if _is_bedrock_local_configuration_value_error(exc, session=session):+ failure_kind = ModelCatalogFailureKind.INVALID_CONFIGURATION+ elif catalog_request:+ # Response parsers can raise ValueError for malformed timestamps or+ # other service/proxy data. That is not proof of bad local config.+ failure_kind = ModelCatalogFailureKind.INVALID_RESPONSE+ else:+ # Credential providers can likewise surface malformed remote data+ # while the client is being constructed. Preserve a degraded probe.+ failure_kind = ModelCatalogFailureKind.UNKNOWN+ elif isinstance(exc, BotocoreSSLError) and _is_invalid_bedrock_ca_bundle(session):+ failure_kind = ModelCatalogFailureKind.INVALID_CONFIGURATION+ elif isinstance(exc, BotoCoreError):+ failure_kind = ModelCatalogFailureKind.UNAVAILABLE+ else:+ failure_kind = ModelCatalogFailureKind.UNKNOWN+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ f"Bedrock model catalog request failed: {type(exc).__name__}",+ failure_kind=failure_kind,+ http_status=http_status,+ )+++def _probe_bedrock_model(provider: ProviderConfig, *, timeout_seconds: float) -> ModelProbeResult:+ """Run one Bedrock catalog request inside the outer deadline worker."""+ session = None+ try:+ request_config = BotoConfig(+ connect_timeout=timeout_seconds,+ read_timeout=timeout_seconds,+ retries={"max_attempts": 0},+ )+ session = boto3.session.Session()+ _validate_bedrock_local_sdk_configuration(session)+ bearer_token = os.environ.get("AWS_BEARER_TOKEN_BEDROCK")+ if (+ isinstance(bearer_token, str)+ and bearer_token.strip()+ and any(not 0x21 <= ord(character) <= 0x7E for character in bearer_token)+ ):+ raise InvalidConfigError(error_msg="Bedrock bearer token contains invalid characters")+ if not isinstance(bearer_token, str) or not bearer_token.strip():+ metadata_unavailable = _monitor_bedrock_metadata_unavailability(session)+ get_credentials = getattr(session, "get_credentials", None)+ if callable(get_credentials):+ credentials = get_credentials()+ if credentials is None:+ if metadata_unavailable[0]:+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "Bedrock credential metadata service was unavailable",+ failure_kind=ModelCatalogFailureKind.UNAVAILABLE,+ )+ raise NoCredentialsError+ credentials.get_frozen_credentials()+ bedrock = session.client(+ "bedrock",+ region_name=provider.region or "us-west-2",+ config=request_config,+ )+ bedrock_runtime = session.client(+ "bedrock-runtime",+ region_name=provider.region or "us-west-2",+ config=request_config,+ )+ if (_bedrock_client_uses_tls(bedrock) or _bedrock_client_uses_tls(bedrock_runtime)) and (+ _is_invalid_bedrock_ca_bundle(session)+ ):+ raise InvalidConfigError(error_msg="configured AWS CA bundle cannot be loaded")+ region_name = provider.region or "us-west-2"+ catalog_authoritative = _is_native_bedrock_endpoint(+ session,+ bedrock,+ service_name="bedrock",+ region_name=region_name,+ ) and _is_native_bedrock_endpoint(+ session,+ bedrock_runtime,+ service_name="bedrock-runtime",+ region_name=region_name,+ )+ except Exception as exc:+ return _bedrock_exception_result(provider, exc, catalog_request=False, session=session)++ try:+ response = bedrock.list_foundation_models()+ except Exception as exc:+ return _bedrock_exception_result(provider, exc, catalog_request=True, session=session)+ summaries = response.get("modelSummaries") if isinstance(response, dict) else None+ available = {+ str(item["modelId"])+ for item in summaries or []+ if isinstance(item, dict) and isinstance(item.get("modelId"), str)+ }+ aliases = {provider.model}+ prefix, separator, unprefixed = provider.model.partition(".")+ if separator and prefix in {"apac", "eu", "global", "us"}:+ aliases.add(unprefixed)+ if aliases.isdisjoint(available):+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ f"model {provider.model} is not listed",+ catalog_authoritative=catalog_authoritative,+ )+ return ModelProbeResult(+ True,+ provider.provider,+ provider.model,+ f"model {provider.model} is available",+ catalog_authoritative=catalog_authoritative,+ )+++def _probe_bedrock_model_with_deadline(+ provider: ProviderConfig,+ *,+ timeout_seconds: float,+) -> ModelProbeResult:+ """Bound session creation, credential providers, retries, and request I/O."""+ if (+ not isinstance(timeout_seconds, (int, float))+ or isinstance(timeout_seconds, bool)+ or not math.isfinite(timeout_seconds)+ or timeout_seconds <= 0+ ):+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "model catalog timeout must be a positive number",+ failure_kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )++ result_queue: Queue[ModelProbeResult] = Queue(maxsize=1)+ deadline = monotonic() + timeout_seconds+ if not _BEDROCK_PROBE_SLOT.acquire(timeout=timeout_seconds):+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "Bedrock model catalog request timed out",+ failure_kind=ModelCatalogFailureKind.UNAVAILABLE,+ )++ def run_probe() -> None:+ try:+ try:+ result = _probe_bedrock_model(provider, timeout_seconds=remaining)+ except Exception as exc:+ result = ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ f"Bedrock model catalog request failed: {type(exc).__name__}",+ failure_kind=ModelCatalogFailureKind.UNKNOWN,+ )+ result_queue.put_nowait(result)+ finally:+ _BEDROCK_PROBE_SLOT.release()++ remaining = deadline - monotonic()+ if remaining <= 0:+ _BEDROCK_PROBE_SLOT.release()+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "Bedrock model catalog request timed out",+ failure_kind=ModelCatalogFailureKind.UNAVAILABLE,+ )++ try:+ worker = Thread(target=run_probe, name="bedrock-model-catalog-probe", daemon=True)+ worker.start()+ except BaseException as exc:+ _BEDROCK_PROBE_SLOT.release()+ if not isinstance(exc, Exception):+ raise+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ f"Bedrock model catalog request failed: {type(exc).__name__}",+ failure_kind=ModelCatalogFailureKind.UNKNOWN,+ )+ try:+ return result_queue.get(timeout=remaining)+ except Empty:+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "Bedrock model catalog request timed out",+ failure_kind=ModelCatalogFailureKind.UNAVAILABLE,+ )++def probe_model(provider: ProviderConfig, *, timeout_seconds: float = 15.0) -> ModelProbeResult:- """Verify that the selected provider catalog lists the requested model."""+ """Check the selected model against the provider catalog within one deadline."""if provider.provider == "bedrock":- try:- response = boto3.client("bedrock", region_name=provider.region or "us-west-2").list_foundation_models()- except (BotoCoreError, ClientError) as exc:- return ModelProbeResult(- False,- provider.provider,- provider.model,- f"Bedrock model catalog request failed: {type(exc).__name__}",- )- summaries = response.get("modelSummaries") if isinstance(response, dict) else None- available = {- str(item["modelId"])- for item in summaries or []- if isinstance(item, dict) and isinstance(item.get("modelId"), str)- }- aliases = {provider.model}- prefix, separator, unprefixed = provider.model.partition(".")- if separator and prefix in {"apac", "eu", "global", "us"}:- aliases.add(unprefixed)- if aliases.isdisjoint(available):- return ModelProbeResult(False, provider.provider, provider.model, f"model {provider.model} is not listed")- return ModelProbeResult(True, provider.provider, provider.model, f"model {provider.model} is available")+ return _probe_bedrock_model_with_deadline(provider, timeout_seconds=timeout_seconds)+ if (+ not isinstance(timeout_seconds, (int, float))+ or isinstance(timeout_seconds, bool)+ or not math.isfinite(timeout_seconds)+ or timeout_seconds <= 0+ ):+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "model catalog timeout must be a positive number",+ failure_kind=ModelCatalogFailureKind.INVALID_CONFIGURATION,+ )+ deadline = monotonic() + timeout_secondstry:records = fetch_model_records(provider, timeout_seconds=timeout_seconds)except ModelCatalogError as exc:- return ModelProbeResult(False, provider.provider, provider.model, str(exc))+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ str(exc),+ failure_kind=exc.kind,+ http_status=exc.http_status,+ )available = {record.id for record in records}if provider.model not in available:+ if provider.provider == "anthropic" and _is_native_catalog_endpoint(provider):+ remaining = deadline - monotonic()+ if remaining <= 0:+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ "model catalog request timed out",+ failure_kind=ModelCatalogFailureKind.UNAVAILABLE,+ )+ try:+ resolved = fetch_anthropic_model_record(+ provider,+ provider.model,+ timeout_seconds=remaining,+ )+ except ModelCatalogError as exc:+ if exc.http_status == 404:+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ f"model {provider.model} is not available",+ failure_kind=ModelCatalogFailureKind.MODEL_NOT_FOUND,+ http_status=404,+ )+ return ModelProbeResult(+ False,+ provider.provider,+ provider.model,+ str(exc),+ failure_kind=exc.kind,+ http_status=exc.http_status,+ )+ return ModelProbeResult(+ True,+ provider.provider,+ provider.model,+ f"model {provider.model} resolves to {resolved.id}",+ )return ModelProbeResult(False, provider.provider, provider.model, f"model {provider.model} is not listed")return ModelProbeResult(True, provider.provider, provider.model, f"model {provider.model} is available")@@ -309,15 +1384,16 @@ def run_agent_runtime_preflight(agent_import_path=agent_import_path,)try:- with _nvidia_build_key_handoff(run_env, env_mode=env_mode) as subprocess_env:- completed = subprocess.run(- command,- capture_output=True,- text=True,- env=subprocess_env,- timeout=timeout_seconds,- check=False,- )+ handoff = _nvidia_build_key_handoff(run_env, env_mode=env_mode)+ completed = subprocess.run(+ command,+ capture_output=True,+ text=True,+ input=handoff.stdin_text,+ env=handoff.subprocess_env,+ timeout=timeout_seconds,+ check=False,+ )except subprocess.TimeoutExpired:return PreflightResult(False,diff --git a/src/skillevaluator/tier3/harbor/secure_docker_environment.py b/src/skillevaluator/tier3/harbor/secure_docker_environment.pyindex 46f06f26..4218bd65 100644--- a/src/skillevaluator/tier3/harbor/secure_docker_environment.py+++ b/src/skillevaluator/tier3/harbor/secure_docker_environment.py@@ -7,8 +7,8 @@ The pinned Harbor release serializes ``exec(env=...)`` values as``docker compose exec -e NAME=value``. Process arguments are host-visible, sothe compatibility backend passes only names on argv and values through thecompose subprocess environment. SkillEvaluator's selected backend is stronger:-it transfers values through a short-lived, file-backed handoff and removes the-container copy before running the requested command.+it receives the parent NVIDIA credential through stdin, then transfers values+through a short-lived container handoff removed before the requested command."""from __future__ import annotations@@ -19,7 +19,6 @@ import osimport reimport shleximport signal-import tempfileimport uuidfrom collections.abc import Mappingfrom pathlib import Path@@ -28,6 +27,11 @@ from typing import Anyfrom harbor.environments.base import ExecResultfrom harbor.environments.docker.docker import DockerEnvironment, _sanitize_docker_compose_project_name+from skillevaluator.tier3.harbor.sensitive_stdin import (+ NVIDIA_BUILD_STDIN_SENTINEL,+ read_nvidia_build_key_from_stdin,+)+SECURE_DOCKER_ENV_IMPORT_PATH = ("skillevaluator.tier3.harbor.secure_docker_environment:SkillEvaluatorSecureDockerEnvironment")@@ -149,9 +153,12 @@ async def _terminate_process_tree(await _await_task_uninterruptibly(cleanup, preserve_cancellation=preserve_cancellation)-def _file_backed_environment(environment: Mapping[str, str]) -> dict[str, str]:- """Resolve the private NVIDIA Build sentinel without putting its value in argv."""+def _host_handoff_environment(environment: Mapping[str, str]) -> dict[str, str]:+ """Resolve a private NVIDIA Build sentinel without putting its value in argv."""resolved = _validate_environment(environment)+ if resolved.get("NVIDIA_API_KEY") == NVIDIA_BUILD_STDIN_SENTINEL:+ resolved["NVIDIA_API_KEY"] = read_nvidia_build_key_from_stdin()+ return resolvedif resolved.get("NVIDIA_API_KEY") != _NVIDIA_BUILD_FILE_SENTINEL:return resolvedkey_file = os.environ.get(_NVIDIA_BUILD_KEY_FILE_ENV, "").strip()@@ -177,6 +184,13 @@ def _render_environment_script(environment: Mapping[str, str]) -> str:class SkillEvaluatorDockerEnvironment(DockerEnvironment):"""Pinned Harbor compatibility backend with host-visible argv safety."""+ @classmethod+ def preflight(cls) -> None:+ """Consume the private stdin handoff before Docker can inherit it."""+ if os.environ.get("NVIDIA_API_KEY", "").strip() == NVIDIA_BUILD_STDIN_SENTINEL:+ read_nvidia_build_key_from_stdin()+ super().preflight()+async def _contain_main_container(self) -> None:"""Stop and remove this Compose project's task container from the trusted host."""stopped = False@@ -272,9 +286,11 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):timeout_sec: int | None = None,*,env_overrides: Mapping[str, str] | None = None,+ stdin_bytes: bytes | None = None,+ redact_values: set[str] | None = None,stop_main_on_interrupt: bool = False,) -> ExecResult:- """Run compose with sensitive exec overrides only in the child env."""+ """Run compose with sensitive values only in child env or stdin."""full_command = ["docker","compose",@@ -290,15 +306,14 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):process_environment = self._compose_env_vars(include_os_env=True)process_environment.update(env_overrides or {})secret_values = {- value- for value in (env_overrides or {}).values()- if value and len(value) >= _MIN_EXACT_SECRET_LENGTH+ value for value in (env_overrides or {}).values() if value and len(value) >= _MIN_EXACT_SECRET_LENGTH}+ secret_values.update(redact_values or set())creation = asyncio.create_task(asyncio.create_subprocess_exec(*full_command,env=process_environment,- stdin=asyncio.subprocess.DEVNULL,+ stdin=asyncio.subprocess.PIPE if stdin_bytes is not None else asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,start_new_session=os.name == "posix",@@ -308,7 +323,9 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):process = await asyncio.shield(creation)except asyncio.CancelledError:process = await _await_task_uninterruptibly(creation, preserve_cancellation=False)- communication = asyncio.create_task(process.communicate())+ communication = asyncio.create_task(+ process.communicate(stdin_bytes) if stdin_bytes is not None else process.communicate()+ )cleanup = asyncio.create_task(self._contain_main_and_reap_compose(process,@@ -324,7 +341,9 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):) from excraise- communication = asyncio.create_task(process.communicate())+ communication = asyncio.create_task(+ process.communicate(stdin_bytes) if stdin_bytes is not None else process.communicate()+ )try:if timeout_sec:stdout_bytes, stderr_bytes = await asyncio.wait_for(@@ -380,7 +399,7 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):class SkillEvaluatorSecureDockerEnvironment(SkillEvaluatorDockerEnvironment):- """Transfer exec environments through short-lived container-only files."""+ """Stream exec environments into short-lived container-only files."""async def _exec_without_environment(self,@@ -433,15 +452,28 @@ class SkillEvaluatorSecureDockerEnvironment(SkillEvaluatorDockerEnvironment):user=user,)- merged = _file_backed_environment(merged)+ merged = _host_handoff_environment(merged)remote_path = f"/tmp/.skillevaluator-exec-env-{uuid.uuid4().hex}.sh"primary_error: BaseException | None = Nonetry:- with tempfile.TemporaryDirectory(prefix="skillevaluator-docker-env-") as temp_dir:- host_path = Path(temp_dir) / "environment.sh"- host_path.write_text(_render_environment_script(merged), encoding="utf-8")- host_path.chmod(0o600)- await self.upload_file(host_path, remote_path)+ secret_values = {value for value in merged.values() if value and len(value) >= _MIN_EXACT_SECRET_LENGTH}+ await self._run_docker_compose_command(+ [+ "exec",+ "-T",+ "-u",+ "root",+ "main",+ "sh",+ "-c",+ 'umask 077; cat > "$1"',+ "sh",+ remote_path,+ ],+ check=True,+ stdin_bytes=_render_environment_script(merged).encode("utf-8"),+ redact_values=secret_values,+ )if user is None:await self._run_docker_compose_command(@@ -467,9 +499,7 @@ class SkillEvaluatorSecureDockerEnvironment(SkillEvaluatorDockerEnvironment):cwd=cwd,timeout_sec=timeout_sec,user=user,- secret_values={- value for value in merged.values() if value and len(value) >= _MIN_EXACT_SECRET_LENGTH- },+ secret_values=secret_values,)except BaseException as exc:primary_error = exc@@ -488,3 +518,20 @@ class SkillEvaluatorSecureDockerEnvironment(SkillEvaluatorDockerEnvironment):primary_error.add_note(f"{message}: {cleanup_error}")else:raise RuntimeError(message) from cleanup_error++ async def exec_with_sensitive_env(+ self,+ command: str,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ timeout_sec: int | None = None,+ user: str | int | None = None,+ ) -> ExecResult:+ """Execute with values streamed into a private, container-only handoff."""+ return await self.exec(+ command=command,+ cwd=cwd,+ env=env,+ timeout_sec=timeout_sec,+ user=user,+ )diff --git a/src/skillevaluator/tier3/harbor/sensitive_stdin.py b/src/skillevaluator/tier3/harbor/sensitive_stdin.pynew file mode 100644index 00000000..63ccee35--- /dev/null+++ b/src/skillevaluator/tier3/harbor/sensitive_stdin.py@@ -0,0 +1,42 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Process-local reader for credentials delivered through standard input."""++from __future__ import annotations++import os+import sys+from threading import Lock++NVIDIA_BUILD_STDIN_SENTINEL = "skillevaluator-stdin-backed-nvidia-key"+NVIDIA_BUILD_KEY_STDIN_ENV = "SKILLEVALUATOR_NVIDIA_API_KEY_STDIN"++_UNSET = object()+++class _SecretCache:+ value: str | object = _UNSET+++_nvidia_build_key_cache = _SecretCache()+_nvidia_build_key_lock = Lock()+++def read_nvidia_build_key_from_stdin() -> str:+ """Read and cache the parent-provided key without storing it on disk."""+ if os.environ.get(NVIDIA_BUILD_KEY_STDIN_ENV) != "1":+ raise RuntimeError(f"{NVIDIA_BUILD_KEY_STDIN_ENV} is required for NVIDIA Build Docker runs")++ with _nvidia_build_key_lock:+ if _nvidia_build_key_cache.value is _UNSET:+ try:+ api_key = sys.stdin.read().strip()+ except (OSError, UnicodeError) as exc:+ raise RuntimeError("NVIDIA Build key stdin handoff is unavailable") from exc+ if not api_key:+ raise RuntimeError("NVIDIA Build key stdin handoff is empty")+ _nvidia_build_key_cache.value = api_key++ assert isinstance(_nvidia_build_key_cache.value, str)+ return _nvidia_build_key_cache.valuediff --git a/tests/test_cli.py b/tests/test_cli.pyindex 5a1cdd35..5a55cb58 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -523,6 +523,17 @@ def test_tier3_validate_help() -> None:assert "--harbor-contract" in result.output[email protected]("args", [["doctor", "--help"], ["tier3", "doctor", "--help"]])+def test_doctor_verify_models_help_describes_live_catalog_probe(args: list[str]) -> None:+ result = CliRunner().invoke(cli, args, terminal_width=240)++ assert result.exit_code == 0+ assert "--verify-models" in result.output+ normalized_output = " ".join(result.output.split()).lower()+ assert "catalog reachability" in normalized_output+ assert "authenticated" not in normalized_output++def test_removed_benchmark_authoring_command_is_unavailable() -> None:removed_command = "convert" + "-benchmark"diff --git a/tests/test_harbor_html_report_failures.py b/tests/test_harbor_html_report_failures.pyindex 9ebff846..7c71add6 100644--- a/tests/test_harbor_html_report_failures.py+++ b/tests/test_harbor_html_report_failures.py@@ -12,7 +12,7 @@ from typing import TYPE_CHECKINGfrom skillevaluator.evaluation.tier3_report import render_agent_eval_html_reportfrom skillevaluator.provider_config import ProviderConfig-from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor import runner, runtime_preflightfrom skillevaluator.tier3.harbor.collector import _build_comparison, collect_harbor_resultsfrom skillevaluator.tier3.harbor.metrics import DEFAULT_METRICSfrom skillevaluator.tier3.results_location import external_results_root, resolve_latest_results@@ -702,6 +702,16 @@ def test_html_generation_failure_is_persisted_identically_to_returned_result(monkeypatch.setattr(runner, "_run_agent_pair", lambda **_kwargs: [])monkeypatch.setattr(runner, "render_agent_eval_html_report", fail_html)monkeypatch.setattr(Path, "symlink_to", deny_symlink)+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )returned = runner.run_harbor_eval(skill_path,diff --git a/tests/test_harbor_local_mode.py b/tests/test_harbor_local_mode.pyindex 46a4becf..cdda2329 100644--- a/tests/test_harbor_local_mode.py+++ b/tests/test_harbor_local_mode.py@@ -13,7 +13,6 @@ import osimport shleximport signalimport socket-import statimport subprocessimport sysimport tempfile@@ -237,6 +236,15 @@ def test_local_nvidia_build_codex_starts_authenticated_host_bridge_and_cleans_upasync def upload_file(self, source: object, destination: object) -> None:retained_logs.append((str(destination), Path(source).read_text(encoding="utf-8")))+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ calls.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: Codex,_environment: object,@@ -535,6 +543,17 @@ def test_nvidia_build_codex_bridge_isolated_from_client_and_cleans_up((str(destination), source_path.read_text(encoding="utf-8"), source_path.stat().st_mode & 0o777))+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ user: str | int | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ destination = root_calls if user == "root" else calls+ destination.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: Codex,_environment: object,@@ -569,18 +588,19 @@ def test_nvidia_build_codex_bridge_isolated_from_client_and_cleans_up(asyncio.run(agent.run("test", Environment(), None))- assert any(destination.endswith("nvidia-build-bridge.py") for destination, _, _ in uploads)- key_upload = next(upload for upload in uploads if upload[0].endswith(".key"))- client_token_upload = next(upload for upload in uploads if upload[0].endswith(".token"))- assert key_upload[1] == "nvidia-secret"- assert key_upload[2] == 0o600- assert key_upload[0].startswith("/tmp/")- assert "/logs/" not in key_upload[0]- assert client_token_upload[1] not in {"", "nvidia-secret", "nvidia-build-loopback"}- assert len(client_token_upload[1]) >= 32- assert client_token_upload[2] == 0o600- assert client_token_upload[0].startswith("/tmp/")- assert "/logs/" not in client_token_upload[0]+ assert len(uploads) == 1+ assert uploads[0][0].endswith("nvidia-build-bridge.py")+ secret_handoff = next(+ (command, env) for command, env in root_calls if "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env+ )+ assert secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY"] == "nvidia-secret"+ client_token = secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN"]+ assert client_token not in {"", "nvidia-secret", "nvidia-build-loopback"}+ assert len(client_token) >= 32+ assert "nvidia-secret" not in secret_handoff[0]+ assert client_token not in secret_handoff[0]+ assert ".key" in secret_handoff[0]+ assert ".token" in secret_handoff[0]bridge_start = next((command, env) for command, env in root_calls if "nvidia-build-bridge.py" in command and "&" in command)@@ -593,7 +613,7 @@ def test_nvidia_build_codex_bridge_isolated_from_client_and_cleans_up(assert "--max-requests" in bridge_start[0]assert "skillevaluator-nvidia-build-" in bridge_start[0]assert "nvidia-secret" not in bridge_start[0]- assert client_token_upload[1] not in bridge_start[0]+ assert client_token not in bridge_start[0]assert "--port 0" in bridge_start[0]assert "--ready-file" in bridge_start[0]assert "18080" not in bridge_start[0]@@ -609,7 +629,7 @@ def test_nvidia_build_codex_bridge_isolated_from_client_and_cleans_up(assert "openai_base_url" not in setup_commandassert all("openai_base_url" not in command for command, _ in calls)assert "nvidia-secret" not in setup_command- assert setup_env["OPENAI_API_KEY"] == client_token_upload[1]+ assert setup_env["OPENAI_API_KEY"] == client_tokenassert "OPENAI_BASE_URL" not in setup_envclient_command, client_env = next((command, env) for command, env in calls if "codex exec" in command)assert "NVIDIA_API_KEY" not in client_env@@ -621,13 +641,70 @@ def test_nvidia_build_codex_bridge_isolated_from_client_and_cleans_up(assert "skillevaluator-nvidia-build-" in cleanupassert "nvidia-build-bridge.ready" in cleanupassert "nvidia-build-bridge.py" in cleanup- assert key_upload[0] in cleanup- assert client_token_upload[0] in cleanup+ assert ".key" in cleanup+ assert ".token" in cleanup+++def test_nvidia_build_container_bridge_streams_secrets_without_host_temp_files(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from harbor.agents.installed.codex import Codex++ from skillevaluator.tier3.harbor import local_agents++ agent = object.__new__(SkillEvaluatorNvidiaBuildCodex)+ agent.model_name = "nvidia/model"+ uploads: list[str] = []+ root_calls: list[tuple[str, dict[str, str]]] = []++ class Environment:+ async def upload_file(self, _source: object, destination: object) -> None:+ uploads.append(str(destination))++ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ root_calls.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="")++ def reject_host_secret_file(*_args, **_kwargs):+ raise AssertionError("bridge secrets must not be materialized in host temporary files")++ async def root_exec(+ _self: Codex,+ _environment: object,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ root_calls.append((command, dict(env or {})))+ stdout = "http://127.0.0.1:43123\n" if "--check-ready-file" in command else ""+ return SimpleNamespace(return_code=0, stdout=stdout)++ monkeypatch.setattr(local_agents.tempfile, "mkstemp", reject_host_secret_file)+ monkeypatch.setattr(Codex, "exec_as_root", root_exec)+ monkeypatch.setenv("NVIDIA_API_KEY", "nvidia-secret")++ asyncio.run(agent._start_bridge(Environment()))+ asyncio.run(agent._cleanup_bridge(Environment()))++ assert len(uploads) == 1+ assert uploads[0].endswith("nvidia-build-bridge.py")+ secret_handoff = next((command, env) for command, env in root_calls if ".key" in command and ".token" in command)+ assert secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY"] == "nvidia-secret"+ client_token = secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN"]+ assert len(client_token) >= 32+ assert "nvidia-secret" not in secret_handoff[0]+ assert client_token not in secret_handoff[0]+ assert "umask 077" in secret_handoff[0]@pytest.mark.parametrize("cancel_stage",- ["bridge-script-upload", "api-key-upload", "client-token-upload", "startup", "health-check"],+ ["bridge-script-upload", "secret-handoff", "startup", "health-check"],)def test_nvidia_build_container_bridge_cancellation_cleans_all_private_state_uninterruptibly(monkeypatch: pytest.MonkeyPatch,@@ -658,18 +735,39 @@ def test_nvidia_build_container_bridge_cancellation_cleans_all_private_state_unistage_reached.set()await asyncio.Future()+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ del command+ if env and "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env and cancel_stage == "secret-handoff":+ stage_reached.set()+ await asyncio.Future()+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def root_exec(_self: Codex,_environment: object,command: str,- **_kwargs: object,+ **kwargs: object,) -> SimpleNamespace:if 'kill "$(cat' in command:cleanup_commands.append(command)cleanup_started.set()await release_cleanup.wait()return SimpleNamespace(return_code=0, stdout="")- stage = "startup" if command.startswith("set -eu;") else "health-check"+ environment = kwargs.get("env")+ stage = (+ "secret-handoff"+ if isinstance(environment, dict) and "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in environment+ else "health-check"+ if "--check-ready-file" in command+ else "startup"+ if "nvidia-build-bridge.py" in command and "&" in command+ else "health-check"+ )if stage == cancel_stage:stage_reached.set()await asyncio.Future()@@ -721,30 +819,33 @@ def test_nvidia_build_bridge_prefers_file_backed_host_key_over_subprocess_sentinagent.model_name = "nvidia/model"agent._nvidia_build_bridge_started = Falseagent._nvidia_build_bridge_key_file = None- commands: list[str] = []- uploads: list[tuple[str, str, str, int]] = []+ root_calls: list[tuple[str, dict[str, str]]] = []+ uploads: list[str] = []host_key_file = tmp_path / "nvidia-build-host-key"host_key_file.write_text("real-nvidia-secret", encoding="utf-8")class Environment:async def upload_file(self, source: object, destination: object) -> None:- source_path = Path(source)- uploads.append(- (- source_path.name,- str(destination),- source_path.read_text(encoding="utf-8"),- stat.S_IMODE(source_path.stat().st_mode),- )- )+ del source+ uploads.append(str(destination))++ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ root_calls.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")async def root_exec(_self: Codex,_environment: object,command: str,+ env: dict[str, str] | None = None,**_kwargs: object,) -> SimpleNamespace:- commands.append(command)+ root_calls.append((command, dict(env or {})))stdout = "http://127.0.0.1:43123\n" if "--check-ready-file" in command else ""return SimpleNamespace(return_code=0, stdout=stdout)@@ -755,28 +856,78 @@ def test_nvidia_build_bridge_prefers_file_backed_host_key_over_subprocess_sentinasyncio.run(agent._start_bridge(Environment()))asyncio.run(agent._cleanup_bridge(Environment()))- key_source_name, _, key_upload, key_mode = next(upload for upload in uploads if upload[1].endswith(".key"))- token_source_name, _, _, token_mode = next(upload for upload in uploads if upload[1].endswith(".token"))- assert key_upload == "real-nvidia-secret"- assert key_source_name.startswith("nvidia-api-key-")- assert token_source_name.startswith("nvidia-client-token-")- if os.name != "nt":- assert key_mode == 0o600- assert token_mode == 0o600+ assert len(uploads) == 1+ assert uploads[0].endswith("nvidia-build-bridge.py")+ secret_handoff = next(+ (command, env) for command, env in root_calls if "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env+ )+ assert secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY"] == "real-nvidia-secret"+ client_token = secret_handoff[1]["SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN"]+ assert len(client_token) >= 32assert host_key_file.exists()- assert all("real-nvidia-secret" not in command for command in commands)- assert all("skillevaluator-file-backed-nvidia-key" not in command for command in commands)+ assert all("real-nvidia-secret" not in command for command, _env in root_calls)+ assert all("skillevaluator-file-backed-nvidia-key" not in command for command, _env in root_calls)+ assert client_token not in secret_handoff[0]def test_nvidia_build_bridge_rejects_file_backed_sentinel_without_host_key_file(monkeypatch: pytest.MonkeyPatch,) -> None:agent = object.__new__(SkillEvaluatorNvidiaBuildCodex)++ class Environment:+ async def exec_with_sensitive_env(self, **_kwargs: object) -> SimpleNamespace:+ raise AssertionError("credential validation must fail before execution")+monkeypatch.setenv("NVIDIA_API_KEY", "skillevaluator-file-backed-nvidia-key")monkeypatch.delenv("SKILLEVALUATOR_NVIDIA_API_KEY_FILE", raising=False)with pytest.raises(RuntimeError, match="SKILLEVALUATOR_NVIDIA_API_KEY_FILE"):- asyncio.run(agent._start_bridge(object()))+ asyncio.run(agent._start_bridge(Environment()))+++def test_nvidia_build_bridge_rejects_unsafe_environment_before_reading_or_transferring_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from skillevaluator.tier3.harbor import local_agents++ agent = object.__new__(SkillEvaluatorNvidiaBuildCodex)+ agent.model_name = "nvidia/model"+ uploads: list[str] = []+ executions: list[tuple[str, dict[str, str]]] = []+ key_reads: list[bool] = []++ class UnsafeEnvironment:+ async def upload_file(self, _source: object, destination: object) -> None:+ uploads.append(str(destination))++ async def exec(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ executions.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")++ def reject_key_read() -> str:+ key_reads.append(True)+ raise AssertionError("unsupported environments must be rejected before consuming stdin")++ monkeypatch.setattr(local_agents, "read_nvidia_build_key_from_stdin", reject_key_read)+ monkeypatch.setenv("NVIDIA_API_KEY", local_agents.NVIDIA_BUILD_STDIN_SENTINEL)++ with pytest.raises(RuntimeError, match="protected sensitive-value transport"):+ asyncio.run(agent._start_bridge(UnsafeEnvironment()))++ assert key_reads == []+ assert uploads == []+ assert executions == []++ agent._nvidia_build_bridge_client_env = {"OPENAI_API_KEY": "bridge-client-token-secret"}+ with pytest.raises(RuntimeError, match="protected sensitive-value transport"):+ asyncio.run(agent.exec_as_agent(UnsafeEnvironment(), command="codex exec -- test"))+ assert executions == []def test_nvidia_build_bridge_health_failure_cleans_up_before_raising(@@ -792,6 +943,16 @@ def test_nvidia_build_bridge_health_failure_cleans_up_before_raising(async def upload_file(self, _source: object, _destination: object) -> None:return None+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ commands.append(command)+ assert env and "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: Codex,_environment: object,@@ -826,6 +987,16 @@ def test_nvidia_build_bridge_start_failure_removes_uploaded_key(async def upload_file(self, _source: object, _destination: object) -> None:return None+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ commands.append(command)+ assert env and "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: Codex,_environment: object,@@ -861,6 +1032,16 @@ def test_nvidia_build_bridge_start_exception_removes_uploaded_key(async def upload_file(self, _source: object, _destination: object) -> None:return None+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ commands.append(command)+ assert env and "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY" in env+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: Codex,_environment: object,@@ -893,33 +1074,139 @@ def test_nvidia_build_bridge_wraps_compound_codex_shell_commands_before_unsettinagent.model_name = "nvidia/model"agent._nvidia_build_bridge_origin = "http://127.0.0.1:43123"agent._nvidia_build_bridge_client_env = {- "OPENAI_API_KEY": "nvidia-build-loopback",+ "OPENAI_API_KEY": "bridge-client-token-secret","OPENAI_BASE_URL": "http://127.0.0.1:43123/v1",}+ agent._extra_env = {+ "NVIDIA_API_KEY": "extra-upstream-secret",+ "CODEX_HOME": "/logs/agent/codex-home",+ }+ log_records: list[tuple[object, object]] = []+ agent.logger = SimpleNamespace(debug=lambda message, *args, **kwargs: log_records.append((message, (args, kwargs))))captured: list[tuple[str, dict[str, str]]] = []simple_command = "codex exec --model model -- test"compound_command = 'if [ -d "$CODEX_HOME/sessions" ]; then cp -R "$CODEX_HOME/sessions" /logs/agent/sessions; fi'- async def raw_exec(+ class Environment:+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ captured.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")++ async def reject_logged_exec(_self: Codex,_environment: object,command: str,env: dict[str, str] | None = None,**_kwargs: object,) -> SimpleNamespace:- captured.append((command, dict(env or {})))- return SimpleNamespace(return_code=0)+ _ = (command, env)+ raise AssertionError("bridge credentials must bypass Harbor's logging wrapper")- monkeypatch.setattr(Codex, "exec_as_agent", raw_exec)+ monkeypatch.setattr(Codex, "exec_as_agent", reject_logged_exec)for original_command in (simple_command, compound_command):- asyncio.run(agent.exec_as_agent(object(), command=original_command, env={"NVIDIA_API_KEY": "must-not-leak"}))+ asyncio.run(+ agent.exec_as_agent(+ Environment(),+ command=original_command,+ env={"NVIDIA_API_KEY": "per-call-upstream-secret"},+ )+ )assert [command for command, _ in captured] == [- f"env -u NVIDIA_API_KEY bash -c {shlex.quote('codex exec --model nvidia/model -- test')}",- f"env -u NVIDIA_API_KEY bash -c {shlex.quote(compound_command)}",+ f"env -u NVIDIA_API_KEY bash -o pipefail -c {shlex.quote('codex exec --model nvidia/model -- test')}",+ f"env -u NVIDIA_API_KEY bash -o pipefail -c {shlex.quote(compound_command)}",]assert all("NVIDIA_API_KEY" not in env for _, env in captured)+ assert all(env["OPENAI_API_KEY"] == "bridge-client-token-secret" for _, env in captured)+ assert all(env["CODEX_HOME"] == "/logs/agent/codex-home" for _, env in captured)+ assert log_records == []+++def test_nvidia_build_bridge_client_preserves_pipefail_in_real_inner_shell() -> None:+ from harbor.agents.installed.base import NonZeroAgentExitCodeError++ agent = object.__new__(SkillEvaluatorNvidiaBuildCodex)+ agent.model_name = "nvidia/model"+ agent._extra_env = {"NVIDIA_API_KEY": "upstream-key-must-be-unset"}+ agent._nvidia_build_bridge_origin = "http://127.0.0.1:43123"+ agent._nvidia_build_bridge_client_env = {"OPENAI_API_KEY": "bridge-client-token-secret"}++ class Environment:+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ process = await asyncio.create_subprocess_exec(+ "bash",+ "-c",+ command,+ env={**os.environ, **(env or {})},+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await process.communicate()+ return SimpleNamespace(+ return_code=process.returncode,+ stdout=stdout.decode(),+ stderr=stderr.decode(),+ )++ with pytest.raises(NonZeroAgentExitCodeError, match="exit code 1"):+ asyncio.run(agent.exec_as_agent(Environment(), command="false | true"))+++def test_nvidia_build_bridge_client_failure_does_not_expose_sensitive_output(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from harbor.agents.installed.base import NonZeroAgentExitCodeError+ from harbor.agents.installed.codex import Codex++ bridge_token = "bridge-client-token-secret"+ upstream_key = "upstream-nvidia-key-secret"+ agent = object.__new__(SkillEvaluatorNvidiaBuildCodex)+ agent.model_name = "nvidia/model"+ agent._extra_env = {"NVIDIA_API_KEY": upstream_key}+ agent._nvidia_build_bridge_origin = "http://127.0.0.1:43123"+ agent._nvidia_build_bridge_client_env = {"OPENAI_API_KEY": bridge_token}++ class Environment:+ async def exec_with_sensitive_env(self, **_kwargs: object) -> SimpleNamespace:+ return SimpleNamespace(+ return_code=17,+ stdout=f"provider echoed {bridge_token}",+ stderr=f"provider echoed {upstream_key}",+ )++ async def reject_logged_exec(+ _self: Codex,+ _environment: object,+ **_kwargs: object,+ ) -> SimpleNamespace:+ raise AssertionError("bridge credentials must bypass Harbor's logging wrapper")++ monkeypatch.setattr(Codex, "exec_as_agent", reject_logged_exec)++ with pytest.raises(NonZeroAgentExitCodeError) as exc_info:+ asyncio.run(+ agent.exec_as_agent(+ Environment(),+ command="codex exec -- test",+ env={"NVIDIA_API_KEY": "per-call-upstream-key-secret"},+ )+ )++ message = str(exc_info.value)+ assert message == "NVIDIA Build bridge client command failed with exit code 17"+ assert bridge_token not in message+ assert upstream_key not in messagedef test_nvidia_build_claude_bridge_configures_origin_and_full_model(@@ -935,6 +1222,15 @@ def test_nvidia_build_claude_bridge_configures_origin_and_full_model(async def upload_file(self, _source: object, _destination: object) -> None:return None+ async def exec_with_sensitive_env(+ self,+ command: str,+ env: dict[str, str] | None = None,+ **_kwargs: object,+ ) -> SimpleNamespace:+ calls.append((command, dict(env or {})))+ return SimpleNamespace(return_code=0, stdout="", stderr="")+async def raw_exec(_self: ClaudeCode,_environment: object,diff --git a/tests/test_harbor_runner_environment.py b/tests/test_harbor_runner_environment.pyindex 38fa865c..5ef717b6 100644--- a/tests/test_harbor_runner_environment.py+++ b/tests/test_harbor_runner_environment.py@@ -18,7 +18,7 @@ import pytestfrom harbor.utils.env import resolve_env_varsfrom skillevaluator.provider_config import ProviderConfig, ProviderConfigurationError, resolve_llm_provider-from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor import runner, runtime_preflightfrom skillevaluator.tier3.harbor.adapter import _verifier_env_vars@@ -1006,6 +1006,16 @@ def test_run_harbor_eval_stages_per_agent_credential_trees(monkeypatch.setattr(runner, "generate_harbor_tasks", emit)monkeypatch.setattr(runner, "_run_agent_pair", launch)+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )monkeypatch.setattr(runner,"collect_harbor_results",@@ -1064,9 +1074,130 @@ def test_run_harbor_eval_stages_per_agent_credential_trees("model": "legacy-judge-model","source": "LLM_JUDGE_MODEL","override_applied": True,+ "catalog_verification": "degraded",}[email protected]("grading_mode", ["default", "default_plus_custom"])[email protected]("judge_alias", ["LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"])[email protected]("judge_scope", ["task", "step"])+def test_native_runtime_judge_selection_skips_fallback_probe_through_real_staging(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ grading_mode: str,+ judge_alias: str,+ judge_scope: str,+) -> None:+ skill = tmp_path / "demo"+ evals = skill / "evals"+ native_task = evals / "harbor" / "case-001"+ native_task.mkdir(parents=True)+ (skill / "SKILL.md").write_text("# Demo\n", encoding="utf-8")+ (evals / "evals.json").write_text(+ '[{"id":"case-001","question":"Run the native case.","files":[]}]\n',+ encoding="utf-8",+ )+ (evals / "config.yml").write_text(+ f"schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: {grading_mode}\n",+ encoding="utf-8",+ )+ if grading_mode == "default_plus_custom":+ (evals / "grader.py").write_text("def grade(*args, **kwargs):\n return 1\n", encoding="utf-8")+ (native_task / "instruction.md").write_text("Run the native case.\n", encoding="utf-8")+ authored_judge = f'{judge_alias} = "authored-native-judge"\n'+ judge_config = (+ f"[verifier]\ntimeout_sec = 180.0\n\n[verifier.env]\n{authored_judge}\n"+ if judge_scope == "task"+ else f'[[steps]]\nname = "step-one"\n\n[steps.verifier.env]\n{authored_judge}\n'+ )+ (native_task / "task.toml").write_text(+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-001"\n\n'+ f'[metadata]\nentry_id = "case-001"\n\n{judge_config}[environment]\n',+ encoding="utf-8",+ )++ for name in ("LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(runner, "resolve_llm_provider", lambda: _provider("nv_build"))+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: (+ {"harbor": {"task_source": "native_harbor"}, "grading": {"mode": grading_mode}},+ None,+ ),+ )+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])++ probed_models: list[str] = []++ def probe(selected_provider: ProviderConfig) -> runtime_preflight.ModelProbeResult:+ probed_models.append(selected_provider.model)+ return runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ )++ staged_tasks: list[Path] = []++ def launch(**kwargs):+ staged_tasks.append(kwargs["with_skill"] / "case-001")+ return []++ monkeypatch.setattr(runtime_preflight, "probe_model", probe)+ monkeypatch.setattr(runner, "_run_agent_pair", launch)+ monkeypatch.setattr(+ runner,+ "collect_harbor_results",+ lambda **_kwargs: {"execution_status": "complete", "execution_errors": [], "metrics": [], "agents": {}},+ )++ def render_report(_skill_path: Path, output_dir: Path, **_kwargs) -> Path:+ report = output_dir / "report.html"+ report.write_text("<html></html>\n", encoding="utf-8")+ return report++ monkeypatch.setattr(runner, "render_agent_eval_html_report", render_report)++ result = runner.run_harbor_eval(+ skill,+ ["opencode"],+ agent_models={"opencode": "nvidia/nvidia/nemotron-3-nano-30b-a3b"},+ output_dir=tmp_path / "results",+ env_mode="docker",+ grading_mode=grading_mode,+ skip_baseline=True,+ keep_harbor_jobs=True,+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert probed_models == ["nvidia/nemotron-3-nano-30b-a3b"]+ assert result["execution_status"] == "complete"+ assert result["report_status"] == "complete"+ assert result["run_config"]["task_source"] == "native_harbor"+ assert result["run_config"]["judge"]["catalog_verification"] == "inconclusive"+ assert result["run_config"]["judge"]["effective_model_source"] == "native_harbor_runtime"+ assert result["run_config"]["credential_validation"]["status"] == "degraded"+ standard_target = next(+ target+ for target in result["run_config"]["credential_validation"]["targets"]+ if target["labels"] == ["standard grader"]+ )+ assert standard_target["status"] == "inconclusive"+ assert standard_target["model"] is None++ assert len(staged_tasks) == 1+ staged_config = tomllib.loads((staged_tasks[0] / "task.toml").read_text(encoding="utf-8"))+ if judge_scope == "task":+ staged_judge_env = staged_config["verifier"]["env"]+ else:+ staged_judge_env = staged_config["steps"][0]["verifier"]["env"]+ assert staged_judge_env[judge_alias] == "authored-native-judge"++def test_custom_only_native_verifier_placeholders_use_task_fallbacks_not_standard_override(monkeypatch: pytest.MonkeyPatch,tmp_path,@@ -1114,6 +1245,16 @@ def test_custom_only_native_verifier_placeholders_use_task_fallbacks_not_standarreturn []monkeypatch.setattr(runner, "_run_agent_pair", launch)+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )monkeypatch.setattr(runner,"collect_harbor_results",@@ -1170,6 +1311,16 @@ def test_run_harbor_eval_rejects_provenance_key_inside_skill_before_creation()monkeypatch.setattr(runner, "find_evals_file", lambda _path: skill / "evals" / "evals.json")monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )result = runner.run_harbor_eval(skill,diff --git a/tests/test_harbor_runtime_preflight.py b/tests/test_harbor_runtime_preflight.pyindex acab056a..634dc5c8 100644--- a/tests/test_harbor_runtime_preflight.py+++ b/tests/test_harbor_runtime_preflight.py@@ -5,12 +5,59 @@from __future__ import annotations+import errno+import gzip+import hashlibimport json+import osimport subprocess+import sys+from concurrent.futures import ThreadPoolExecutor+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path+from threading import Barrier, Event, Lock, Thread+from threading import enumerate as enumerate_threadsfrom unittest.mock import Mockimport pytest+from botocore import credentials as botocore_credentials+from botocore import exceptions as botocore_exceptions+from botocore import tokens as botocore_tokens+from botocore.exceptions import (+ ApiVersionNotFoundError,+ BaseEndpointResolverError,+ ConfigNotFound,+ ConfigParseError,+ DataNotFoundError,+ EndpointConnectionError,+ EndpointProviderError,+ InvalidConfigError,+ InvalidDefaultsMode,+ InvalidIMDSEndpointError,+ InvalidIMDSEndpointModeError,+ InvalidProxiesConfigError,+ InvalidRegionError,+ InvalidRetryConfigurationError,+ InvalidSTSRegionalEndpointsConfigError,+ MissingDependencyException,+ NoAuthTokenError,+ NoCredentialsError,+ ParamValidationError,+ PartialCredentialsError,+ ProfileNotFound,+ RefreshWithMFAUnsupportedError,+ ServiceNotInRegionError,+ SSOTokenLoadError,+ UnauthorizedSSOTokenError,+ UnknownCredentialError,+ UnknownRegionError,+ UnknownSignatureVersionError,+ UnsupportedSignatureVersionError,+)+from botocore.exceptions import (+ SSLError as BotocoreSSLError,+)+from botocore.session import Session as BotocoreSessionfrom skillevaluator.model_catalog import ModelCatalogError, ModelRecordfrom skillevaluator.provider_config import ProviderConfig@@ -27,6 +74,27 @@ def _dataset(tmp_path: Path) -> Path:return dataset+def _configure_isolated_aws_profile(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ *,+ config: str,+ credentials: str = "",+ profile: str = "test",+) -> None:+ config_path = tmp_path / "aws-config"+ credentials_path = tmp_path / "aws-credentials"+ config_path.write_text(config, encoding="utf-8")+ credentials_path.write_text(credentials, encoding="utf-8")+ for variable in tuple(os.environ):+ if variable.startswith("AWS_"):+ monkeypatch.delenv(variable)+ monkeypatch.setenv("AWS_CONFIG_FILE", str(config_path))+ monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(credentials_path))+ monkeypatch.setenv("AWS_PROFILE", profile)+ monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")++def _write_harbor_0132_unscored_result(jobs_dir: Path) -> Path:job_dir = jobs_dir / "runtime-preflight-opencode"trial_dir = job_dir / "case-001__attempt"@@ -116,6 +184,49 @@ def test_runtime_preflight_runs_one_case_once_without_verification(monkeypatch,assert run_kwargs["env"] == {"NVIDIA_API_KEY": "secret"}+def test_runtime_preflight_hands_nvidia_build_key_only_over_stdin(monkeypatch, tmp_path: Path) -> None:+ captured: dict[str, object] = {}+ secret = "nvidia-real-secret-value-for-test"++ monkeypatch.setattr(+ runtime_preflight,+ "build_harbor_run_command",+ lambda **_kwargs: ["harbor", "run", "--safe"],+ )++ def run(command, **kwargs):+ captured["command"] = command+ captured["run_kwargs"] = kwargs+ return subprocess.CompletedProcess(command, 0, "", "")++ monkeypatch.setattr(runtime_preflight.subprocess, "run", run)+ monkeypatch.setattr(+ runtime_preflight,+ "validate_harbor_agent_only_job_result",+ lambda *_args, **_kwargs: (True, "ok"),+ )++ result = runtime_preflight.run_agent_runtime_preflight(+ dataset=_dataset(tmp_path),+ agent="opencode",+ model="nvidia/model",+ env_mode="docker",+ jobs_dir=tmp_path / "jobs",+ run_env={"SKILL_EVAL_LLM_PROVIDER": "nv_build", "NVIDIA_API_KEY": secret},+ )++ assert result.ok is True+ run_kwargs = captured["run_kwargs"]+ assert isinstance(run_kwargs, dict)+ assert run_kwargs["input"] == secret+ environment = run_kwargs["env"]+ assert isinstance(environment, dict)+ assert secret not in environment.values()+ assert environment["NVIDIA_API_KEY"] == "skillevaluator-stdin-backed-nvidia-key"+ assert environment["SKILLEVALUATOR_NVIDIA_API_KEY_STDIN"] == "1"+ assert "SKILLEVALUATOR_NVIDIA_API_KEY_FILE" not in environment++def test_runtime_preflight_accepts_harbor_0132_unscored_agent_success(monkeypatch, tmp_path: Path) -> None:jobs_dir = tmp_path / "jobs"_write_harbor_0132_unscored_result(jobs_dir)@@ -495,8 +606,11 @@ def test_runtime_preflight_reports_agent_start_failure(monkeypatch, tmp_path: Padef test_runtime_preflight_timeout_is_bounded(monkeypatch, tmp_path: Path) -> None:monkeypatch.setattr(runtime_preflight, "build_harbor_run_command", lambda **_kwargs: ["harbor", "run"])+ secret = "nvidia-real-secret-value-for-test"- def timeout(*_args, **_kwargs):+ def timeout(*_args, **kwargs):+ assert kwargs["input"] == secret+ assert secret not in kwargs["env"].values()raise subprocess.TimeoutExpired(["harbor", "run"], timeout=30)monkeypatch.setattr(runtime_preflight.subprocess, "run", timeout)@@ -507,12 +621,13 @@ def test_runtime_preflight_timeout_is_bounded(monkeypatch, tmp_path: Path) -> Nomodel="nvidia/model",env_mode="docker",jobs_dir=tmp_path / "jobs",- run_env={},+ run_env={"SKILL_EVAL_LLM_PROVIDER": "nv_build", "NVIDIA_API_KEY": secret},timeout_seconds=30,)assert result.ok is Falseassert "timed out after 30s" in result.detail+ assert secret not in result.detaildef test_runtime_preflight_rejects_empty_task_tree(tmp_path: Path) -> None:@@ -612,7 +727,13 @@ def test_model_probe_reports_safe_shared_catalog_error(monkeypatch) -> None:monkeypatch.setattr(runtime_preflight,"fetch_model_records",- lambda *_args, **_kwargs: (_ for _ in ()).throw(ModelCatalogError("model catalog returned HTTP 401")),+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ ModelCatalogError(+ "model catalog returned HTTP 401",+ kind="authentication",+ http_status=401,+ )+ ),)provider = ProviderConfig(provider="openai",@@ -627,6 +748,427 @@ def test_model_probe_reports_safe_shared_catalog_error(monkeypatch) -> None:assert result.ok is Falseassert "HTTP 401" in result.detailassert "secret-key" not in result.detail+ assert getattr(result, "failure_kind", None) == "authentication"+ assert getattr(result, "http_status", None) == 401+++def test_anthropic_model_probe_resolves_alias_omitted_from_listing(monkeypatch) -> None:+ captured: dict[str, object] = {}+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_model_records",+ lambda *_args, **_kwargs: (ModelRecord("claude-canonical-20260824"),),+ )++ def resolve_alias(provider, model_id, *, timeout_seconds):+ captured.update(provider=provider, model_id=model_id, timeout_seconds=timeout_seconds)+ return ModelRecord("claude-canonical-20260824")++ monkeypatch.setattr(runtime_preflight, "fetch_anthropic_model_record", resolve_alias)+ provider = ProviderConfig(+ provider="anthropic",+ model="claude-stable-alias",+ api_key="secret-key",+ base_url=None,+ litellm_model="anthropic/claude-stable-alias",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=4.5)++ assert result.ok is True+ assert result.model == "claude-stable-alias"+ assert "claude-canonical-20260824" in result.detail+ assert captured["provider"] == provider+ assert captured["model_id"] == "claude-stable-alias"+ assert 0 < float(captured["timeout_seconds"]) <= 4.5+++def test_anthropic_alias_lookup_uses_remaining_catalog_probe_deadline(monkeypatch) -> None:+ captured: dict[str, object] = {}+ clock = iter((100.0, 100.06))+ monkeypatch.setattr(runtime_preflight, "monotonic", lambda: next(clock))+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_model_records",+ lambda *_args, **_kwargs: (ModelRecord("claude-canonical-20260824"),),+ )++ def resolve_alias(provider, model_id, *, timeout_seconds):+ captured.update(provider=provider, model_id=model_id, timeout_seconds=timeout_seconds)+ return ModelRecord("claude-canonical-20260824")++ monkeypatch.setattr(runtime_preflight, "fetch_anthropic_model_record", resolve_alias)+ provider = ProviderConfig(+ provider="anthropic",+ model="claude-stable-alias",+ api_key="secret-key",+ base_url=None,+ litellm_model="anthropic/claude-stable-alias",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=0.1)++ assert result.ok is True+ assert captured["timeout_seconds"] == pytest.approx(0.04)+++def test_anthropic_alias_lookup_stops_when_catalog_probe_deadline_is_exhausted(monkeypatch) -> None:+ clock = iter((100.0, 100.1))+ monkeypatch.setattr(runtime_preflight, "monotonic", lambda: next(clock))+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_model_records",+ lambda *_args, **_kwargs: (ModelRecord("claude-canonical-20260824"),),+ )+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_anthropic_model_record",+ lambda *_args, **_kwargs: pytest.fail("alias lookup must not start after the shared deadline"),+ )+ provider = ProviderConfig(+ provider="anthropic",+ model="claude-stable-alias",+ api_key="secret-key",+ base_url=None,+ litellm_model="anthropic/claude-stable-alias",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=0.1)++ assert result.ok is False+ assert result.failure_kind == "unavailable"+ assert "timed out" in result.detail++[email protected]("timeout_seconds", [0, True, float("nan")])+def test_http_catalog_probe_rejects_invalid_shared_deadline(monkeypatch, timeout_seconds) -> None:+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_model_records",+ lambda *_args, **_kwargs: pytest.fail("invalid timeout must fail before catalog I/O"),+ )+ provider = ProviderConfig(+ provider="openai",+ model="gpt-test",+ api_key="secret-key",+ base_url="https://api.openai.com/v1",+ litellm_model="openai/gpt-test",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=timeout_seconds)++ assert result.ok is False+ assert result.failure_kind == "invalid_configuration"+ assert "positive number" in result.detail+++def test_anthropic_model_probe_treats_native_single_model_404_as_fatal(monkeypatch) -> None:+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_model_records",+ lambda *_args, **_kwargs: (ModelRecord("different-model"),),+ )+ monkeypatch.setattr(+ runtime_preflight,+ "fetch_anthropic_model_record",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ ModelCatalogError(+ "model catalog returned HTTP 404",+ kind="unsupported",+ http_status=404,+ )+ ),+ )+ provider = ProviderConfig(+ provider="anthropic",+ model="missing-model",+ api_key="secret-key",+ base_url="https://api.anthropic.com:443",+ litellm_model="anthropic/missing-model",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.ok is False+ assert result.failure_kind == "model_not_found"+ assert result.http_status == 404+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+++ ("provider", "probe", "expected"),+ [+ (+ ProviderConfig("openai", "gpt-test", "key", "https://api.openai.com/v1", "openai/gpt-test"),+ {"ok": True, "failure_kind": None, "http_status": None},+ "verified",+ ),+ (+ ProviderConfig(+ "nv_build",+ "nvidia/model",+ "invalid-key",+ "https://integrate.api.nvidia.com/v1",+ "openai/nvidia/model",+ ),+ {"ok": True, "failure_kind": None, "http_status": 200},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "invalid-key",+ "https://gateway.example/v1",+ "openai/gpt-test",+ ),+ {"ok": True, "failure_kind": None, "http_status": 200},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://api.openai.com/v1",+ "openai/gpt-test",+ ),+ {"ok": True, "failure_kind": None, "http_status": 200},+ "verified",+ ),+ (+ ProviderConfig("openai", "gpt-test", "key", "https://api.openai.com/v1", "openai/gpt-test"),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "fatal",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://gateway.example/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai",+ "gpt-test",+ "key",+ "https://gateway.example/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "degraded",+ ),+ (+ ProviderConfig(+ "anthropic",+ "claude-test",+ "key",+ "https://gateway.example/v1",+ "anthropic/claude-test",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://api.openai.com/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "fatal",+ ),+ (+ ProviderConfig(+ "anthropic",+ "claude-test",+ "key",+ "https://api.anthropic.com/v1",+ "anthropic/claude-test",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "fatal",+ ),+ (+ ProviderConfig(+ "nv_build",+ "nvidia/model",+ "key",+ "https://integrate.api.nvidia.com/v1",+ "openai/nvidia/model",+ ),+ {"ok": False, "failure_kind": "authentication", "http_status": 401},+ "fatal",+ ),+ (+ ProviderConfig(+ "nv_build",+ "nvidia/model",+ "key",+ "https://integrate.api.nvidia.com/v1",+ "openai/nvidia/model",+ ),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "fatal",+ ),+ (+ ProviderConfig(+ "nv_build",+ "nvidia/model",+ "key",+ "https://integrate.api.nvidia.com/v1",+ "openai/nvidia/model",+ ),+ {"ok": False, "failure_kind": None, "http_status": None},+ "fatal",+ ),+ (+ ProviderConfig("openai", "gpt-test", "key", "https://api.openai.com/v1", "openai/gpt-test"),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "degraded",+ ),+ (+ ProviderConfig("openai", "gpt-test", "key", "https://gateway.example/v1", "openai/gpt-test"),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://api.openai.com/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "degraded",+ ),+ (+ ProviderConfig("bedrock", "model", None, None, "bedrock/model", region="us-west-2"),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "degraded",+ ),+ (+ ProviderConfig("anthropic", "claude-test", "key", None, "anthropic/claude-test"),+ {"ok": False, "failure_kind": None, "http_status": None},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://gateway.example/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": None, "http_status": None},+ "degraded",+ ),+ (+ ProviderConfig("openai", "gpt-test", "key", "https://api.openai.com/v1", "openai/gpt-test"),+ {"ok": False, "failure_kind": "unavailable", "http_status": 429},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "https://gateway.example/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "invalid_configuration", "http_status": None},+ "fatal",+ ),+ (+ ProviderConfig(+ "openai-compatible",+ "gpt-test",+ "key",+ "http://your-server:8000/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "unsupported", "http_status": None},+ "degraded",+ ),+ (+ ProviderConfig(+ "openai",+ "gpt-test",+ "key",+ "https://api.openai.com:443/v1",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "degraded",+ ),+ (+ ProviderConfig(+ "anthropic",+ "claude-alias",+ "key",+ "https://api.anthropic.com",+ "anthropic/claude-alias",+ ),+ {"ok": False, "failure_kind": None, "http_status": None},+ "degraded",+ ),+ (+ ProviderConfig(+ "anthropic",+ "claude-alias",+ "key",+ "https://api.anthropic.com:443/v1",+ "anthropic/claude-alias",+ ),+ {"ok": False, "failure_kind": "authorization", "http_status": 403},+ "fatal",+ ),+ (+ ProviderConfig(+ "openai",+ "gpt-test",+ "key",+ "https://api.openai.com:443/v1/",+ "openai/gpt-test",+ ),+ {"ok": False, "failure_kind": None, "http_status": None},+ "degraded",+ ),+ (+ ProviderConfig(+ "bedrock",+ "application-inference-profile/model-id",+ None,+ None,+ "bedrock/application-inference-profile/model-id",+ region="us-west-2",+ ),+ {"ok": False, "failure_kind": None, "http_status": None},+ "degraded",+ ),+ ],+)+def test_credential_probe_disposition_is_endpoint_aware(provider, probe: dict[str, object], expected: str) -> None:+ result = type(+ "Probe",+ (),+ {+ **probe,+ "provider": provider.provider,+ "model": provider.model,+ "detail": "safe detail",+ },+ )()++ assert runtime_preflight.credential_probe_disposition(provider, result) == expecteddef test_model_probe_rejects_non_http_catalog_url() -> None:@@ -645,17 +1187,18 @@ def test_model_probe_rejects_non_http_catalog_url() -> None:def test_model_probe_checks_bedrock_foundation_catalog(monkeypatch) -> None:- captured: dict[str, object] = {}+ captured: list[tuple[str, dict[str, object]]] = []class Bedrock:def list_foundation_models(self):return {"modelSummaries": [{"modelId": "anthropic.claude-sonnet-test-v1:0"}]}- def client(service, **kwargs):- captured.update({"service": service, **kwargs})- return Bedrock()+ class Session:+ def client(self, service, **kwargs):+ captured.append((service, kwargs))+ return Bedrock()- monkeypatch.setattr(runtime_preflight.boto3, "client", client)+ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)provider = ProviderConfig(provider="bedrock",model="us.anthropic.claude-sonnet-test-v1:0",@@ -665,69 +1208,2386 @@ def test_model_probe_checks_bedrock_foundation_catalog(monkeypatch) -> None:region="us-west-2",)- result = runtime_preflight.probe_model(provider)+ result = runtime_preflight.probe_model(provider, timeout_seconds=4.5)assert result.ok is True- assert captured == {"service": "bedrock", "region_name": "us-west-2"}+ assert [service for service, _kwargs in captured] == ["bedrock", "bedrock-runtime"]+ for _service, kwargs in captured:+ assert kwargs["region_name"] == "us-west-2"+ request_config = kwargs["config"]+ assert request_config.connect_timeout == pytest.approx(4.5, rel=1e-3)+ assert request_config.read_timeout == pytest.approx(4.5, rel=1e-3)+ assert request_config.retries == {"max_attempts": 0}-def test_runtime_preflight_failure_stops_full_matrix(monkeypatch, tmp_path: Path) -> None:- from skillevaluator.tier3.harbor import runner-- skill = tmp_path / "demo"- (skill / "evals").mkdir(parents=True)- (skill / "evals" / "evals.json").write_text("[]\n", encoding="utf-8")- provider = ProviderConfig(- provider="nv_build",- model="meta/llama-3.1-8b-instruct",- api_key="nvapi-test",- base_url="https://integrate.api.nvidia.com/v1",- litellm_model="openai/meta/llama-3.1-8b-instruct",+ ("catalog_endpoint", "runtime_endpoint", "expected_disposition"),+ [+ (+ "https://bedrock.us-west-2.amazonaws.com",+ "https://bedrock-runtime.us-west-2.amazonaws.com",+ "verified",+ ),+ (+ "https://bedrock-fips.us-west-2.amazonaws.com",+ "https://bedrock-runtime-fips.us-west-2.amazonaws.com",+ "verified",+ ),+ (+ "https://bedrock.us-west-2.api.aws",+ "https://bedrock-runtime.us-west-2.api.aws",+ "verified",+ ),+ (+ "http://127.0.0.1:18001",+ "https://bedrock-runtime.us-west-2.amazonaws.com",+ "degraded",+ ),+ (+ "https://bedrock.us-west-2.amazonaws.com",+ "http://127.0.0.1:18002",+ "degraded",+ ),+ ("http://127.0.0.1:18001", "http://127.0.0.1:18002", "degraded"),+ ],+)+def test_bedrock_catalog_success_only_verifies_native_catalog_and_runtime_endpoints(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ catalog_endpoint: str,+ runtime_endpoint: str,+ expected_disposition: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",)+ botocore_session = BotocoreSession()- def emit(_skill, target, **_kwargs):- task = target / "case-001"- task.mkdir(parents=True)- return [task]+ class Client:+ def __init__(self, endpoint_url: str) -> None:+ self.meta = type("Meta", (), {"endpoint_url": endpoint_url})()- full_matrix = Mock(return_value=[])- preflight_run_env: dict[str, str] = {}- monkeypatch.setenv("LLM_JUDGE_MODEL", "host-legacy")- monkeypatch.delenv("SKILL_EVAL_JUDGE_MODEL", raising=False)- monkeypatch.setattr(runner, "resolve_llm_provider", lambda: provider)- monkeypatch.setattr(- runner,- "load_evals_config",- lambda _path: ({"harbor": {"task_source": "evals_json"}}, None),- )- monkeypatch.setattr(runner, "find_evals_file", lambda _path: skill / "evals" / "evals.json")- monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])- monkeypatch.setattr(runner, "generate_harbor_tasks", emit)- monkeypatch.setattr(runner, "_run_agent_pair", full_matrix)+ def list_foundation_models(self):+ return {"modelSummaries": [{"modelId": "test-model"}]}- def fail_preflight(**kwargs):- preflight_run_env.update(kwargs["run_env"])- return runtime_preflight.PreflightResult(- False,- "opencode",- "nvidia/meta/llama-3.1-8b-instruct",- "401 Unauthorized",- "runtime-preflight-opencode",- )+ class Session:+ _session = botocore_session- monkeypatch.setattr(runtime_preflight, "run_agent_runtime_preflight", fail_preflight)+ def client(self, service: str, **_kwargs):+ return Client(catalog_endpoint if service == "bedrock" else runtime_endpoint)- result = runner.run_harbor_eval(- skill,- ["opencode"],- output_dir=tmp_path / "results",- env_mode="docker",- agent_runtime_preflight=True,- )+ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")- assert result["execution_status"] == "failed"- assert result["execution_errors"] == ["opencode runtime preflight failed: 401 Unauthorized"]- assert preflight_run_env["LLM_JUDGE_MODEL"] == "host-legacy"+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.ok is True+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+++def test_bedrock_custom_endpoint_metadata_cannot_make_custom_hosts_authoritative(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ data_path.mkdir()+ (data_path / "endpoints.json").write_text(+ json.dumps(+ {+ "version": 3,+ "partitions": [+ {+ "partition": "aws",+ "partitionName": "AWS Standard",+ "dnsSuffix": "example.invalid",+ "regionRegex": "^(us)-\\w+-\\d+$",+ "regions": {"us-west-2": {}},+ "defaults": {+ "hostname": "{service}.{region}.{dnsSuffix}",+ "protocols": ["https"],+ "signatureVersions": ["v4"],+ },+ "services": {+ "bedrock": {"endpoints": {"us-west-2": {"hostname": "catalog.attacker.invalid"}}},+ "bedrock-runtime": {"endpoints": {"us-west-2": {"hostname": "runtime.attacker.invalid"}}},+ },+ }+ ],+ }+ ),+ encoding="utf-8",+ )+ builtin_data_path = Path(BotocoreSession().get_component("data_loader").BUILTIN_DATA_PATH)+ (data_path / "endpoints").symlink_to(builtin_data_path / "endpoints")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ real_session = runtime_preflight.boto3.session.Session()+ clients = {+ service_name: real_session.client(service_name, region_name="us-west-2")+ for service_name in ("bedrock", "bedrock-runtime")+ }+ clients["bedrock"].list_foundation_models = lambda: {"modelSummaries": [{"modelId": "test-model"}]}++ class Session:+ _session = real_session._session++ def get_credentials(self):+ return real_session.get_credentials()++ def client(self, service_name: str, **_kwargs):+ return clients[service_name]++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert clients["bedrock"].meta.endpoint_url == "https://catalog.attacker.invalid"+ assert clients["bedrock-runtime"].meta.endpoint_url == "https://runtime.attacker.invalid"+ assert result.ok is True+ assert result.catalog_authoritative is False+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+++def test_bedrock_custom_endpoint_rules_cannot_make_custom_hosts_authoritative(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ endpoint_rule_set = {+ "version": "1.0",+ "parameters": {+ "Region": {"builtIn": "AWS::Region", "required": True, "type": "String"},+ "UseDualStack": {+ "builtIn": "AWS::UseDualStack",+ "required": True,+ "default": False,+ "type": "Boolean",+ },+ "UseFIPS": {+ "builtIn": "AWS::UseFIPS",+ "required": True,+ "default": False,+ "type": "Boolean",+ },+ },+ "rules": [+ {+ "conditions": [],+ "type": "endpoint",+ "endpoint": {+ "url": "https://rules.attacker.invalid",+ "properties": {},+ "headers": {},+ },+ }+ ],+ }+ for service_name, api_version in (+ ("bedrock", "2023-04-20"),+ ("bedrock-runtime", "2023-09-30"),+ ):+ rule_path = data_path / service_name / api_version / "endpoint-rule-set-1.json"+ rule_path.parent.mkdir(parents=True)+ rule_path.write_text(json.dumps(endpoint_rule_set), encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ real_session = runtime_preflight.boto3.session.Session()+ clients = {+ service_name: real_session.client(service_name, region_name="us-west-2")+ for service_name in ("bedrock", "bedrock-runtime")+ }+ clients["bedrock"].list_foundation_models = lambda: {"modelSummaries": [{"modelId": "test-model"}]}++ class Session:+ _session = real_session._session++ def get_credentials(self):+ return real_session.get_credentials()++ def client(self, service_name: str, **_kwargs):+ return clients[service_name]++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ routed_urls = {+ clients[service_name]+ ._ruleset_resolver.construct_endpoint(+ clients[service_name].meta.service_model.operation_model(operation_name),+ {},+ {},+ )+ .url+ for service_name, operation_name in (+ ("bedrock", "ListFoundationModels"),+ ("bedrock-runtime", "InvokeModel"),+ )+ }+ assert routed_urls == {"https://rules.attacker.invalid"}+ assert result.ok is True+ assert result.catalog_authoritative is False+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+++ ("status_code", "expected_ok", "expected_kind", "expected_disposition"),+ [(200, True, None, "degraded"), (401, False, "authentication", "fatal")],+)+def test_bedrock_bearer_token_only_uses_real_catalog_transport(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ status_code: int,+ expected_ok: bool,+ expected_kind: str | None,+ expected_disposition: str,+) -> None:+ auth_schemes = BotocoreSession().get_service_model("bedrock").metadata.get("auth", [])+ if "smithy.api#httpBearerAuth" not in auth_schemes:+ pytest.skip("installed Botocore does not support Bedrock bearer authentication")++ seen_authorization: list[bool] = []++ class CatalogResponse(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ seen_authorization.append(self.headers.get("Authorization") == "Bearer test-bearer-token")+ body = (+ {"modelSummaries": [{"modelId": "test-model"}]}+ if status_code == 200+ else {"message": "private rejected bearer"}+ )+ encoded = json.dumps(body).encode()+ self.send_response(status_code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)++ def log_message(self, _format, *_args) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "test-bearer-token")+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ with ThreadingHTTPServer(("127.0.0.1", 0), CatalogResponse) as server:+ endpoint = f"http://127.0.0.1:{server.server_port}"+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK", endpoint)+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", endpoint)+ worker = Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ worker.join(timeout=5)++ assert seen_authorization == [True]+ assert result.ok is expected_ok+ assert result.failure_kind == expected_kind+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+ assert "test-bearer-token" not in result.detail+ assert "private rejected bearer" not in result.detail+++ "bearer_token",+ ["bad\nvalue", "bad\rvalue", "bad\x7fvalue", "bad value", "bad\N{LATIN SMALL LETTER E WITH ACUTE}value"],+)+def test_bedrock_model_probe_rejects_unsafe_bearer_token_characters(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ bearer_token: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", bearer_token)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "InvalidConfigError" in result.detail+ assert bearer_token not in result.detail+++ ("error_code", "http_status", "expected_kind", "expected_disposition"),+ [+ ("UnexpectedAuthCode", 401, "authentication", "fatal"),+ ("InvalidClientTokenId", 400, "authentication", "fatal"),+ ("SignatureDoesNotMatch", 403, "authentication", "fatal"),+ ("InvalidAccessKeyId", 403, "authentication", "fatal"),+ ("ExpiredToken", 403, "authentication", "fatal"),+ ("MissingAuthenticationToken", 403, "authentication", "fatal"),+ ("RequestExpired", 400, "invalid_configuration", "fatal"),+ ("AccessDeniedException", 403, "authorization", "degraded"),+ ("ThrottlingException", 429, "unavailable", "degraded"),+ ("InternalServerException", 500, "unavailable", "degraded"),+ ("ServiceUnavailableException", 503, "unavailable", "degraded"),+ ],+)+def test_bedrock_model_probe_classifies_client_errors(+ monkeypatch,+ error_code: str,+ http_status: int,+ expected_kind: str,+ expected_disposition: str,+) -> None:+ class Bedrock:+ def list_foundation_models(self):+ raise runtime_preflight.ClientError(+ {+ "Error": {"Code": error_code, "Message": "must stay private"},+ "ResponseMetadata": {"HTTPStatusCode": http_status},+ },+ "ListFoundationModels",+ )++ class Session:+ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.ok is False+ assert result.failure_kind == expected_kind+ assert result.http_status == http_status+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+ assert "must stay private" not in result.detail+++ ("operation_name", "error_code", "http_status", "expected_kind", "expected_disposition"),+ [+ ("AssumeRole", "AccessDenied", 403, "authentication", "fatal"),+ ("AssumeRoleWithWebIdentity", "InvalidIdentityToken", 400, "authentication", "fatal"),+ ("AssumeRoleWithWebIdentity", "IDPRejectedClaim", 400, "authentication", "fatal"),+ ("GetRoleCredentials", "AccessDeniedException", 403, "authentication", "fatal"),+ ("AssumeRoleWithWebIdentity", "IDPCommunicationError", 400, "unavailable", "degraded"),+ ("AssumeRole", "ThrottlingException", 429, "unavailable", "degraded"),+ ("AssumeRole", "InternalServerError", 500, "unavailable", "degraded"),+ ],+)+def test_bedrock_model_probe_classifies_credential_bootstrap_client_errors(+ monkeypatch: pytest.MonkeyPatch,+ operation_name: str,+ error_code: str,+ http_status: int,+ expected_kind: str,+ expected_disposition: str,+) -> None:+ class Session:+ def __init__(self) -> None:+ raise runtime_preflight.ClientError(+ {+ "Error": {"Code": error_code, "Message": "must stay private"},+ "ResponseMetadata": {"HTTPStatusCode": http_status},+ },+ operation_name,+ )++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.failure_kind == expected_kind+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+ assert result.http_status == http_status+ assert "must stay private" not in result.detail+++def test_bedrock_model_probe_degrades_when_active_imds_is_unavailable(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.delenv("AWS_EC2_METADATA_DISABLED")+ monkeypatch.setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", "http://127.0.0.1:9")+ monkeypatch.setenv("AWS_METADATA_SERVICE_TIMEOUT", "1")+ monkeypatch.setenv("AWS_METADATA_SERVICE_NUM_ATTEMPTS", "1")+ monkeypatch.setenv("NO_PROXY", "*")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "127.0.0.1" not in result.detail++[email protected]("bearer_token", [None, " \t "])+def test_bedrock_model_probe_fails_when_credentials_are_absent_and_imds_is_disabled(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ bearer_token: str | None,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ if bearer_token is not None:+ monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", bearer_token)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "authentication"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+++ ("status_code", "expected_kind", "expected_disposition"),+ [(500, "unavailable", "degraded"), (404, "authentication", "fatal")],+)+def test_bedrock_model_probe_distinguishes_transient_imds_from_no_role(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ status_code: int,+ expected_kind: str,+ expected_disposition: str,+) -> None:+ requests: list[str] = []++ class MetadataResponse(BaseHTTPRequestHandler):+ def _respond(self) -> None:+ requests.append(self.path)+ self.send_response(status_code)+ self.end_headers()++ def do_GET(self) -> None:+ self._respond()++ def do_PUT(self) -> None:+ self._respond()++ def log_message(self, _format, *_args) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.delenv("AWS_EC2_METADATA_DISABLED")+ monkeypatch.setenv("AWS_METADATA_SERVICE_TIMEOUT", "1")+ monkeypatch.setenv("AWS_METADATA_SERVICE_NUM_ATTEMPTS", "1")+ monkeypatch.setenv("NO_PROXY", "*")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ with ThreadingHTTPServer(("127.0.0.1", 0), MetadataResponse) as server:+ monkeypatch.setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", f"http://127.0.0.1:{server.server_port}")+ worker = Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ worker.join(timeout=5)++ assert requests+ assert result.failure_kind == expected_kind+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+ assert "127.0.0.1" not in result.detail++[email protected]("credential_body", [b"{bad", b'{"AccessKeyId":"test"}', b""])+def test_bedrock_model_probe_degrades_malformed_imds_credential_responses(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ credential_body: bytes,+) -> None:+ class MetadataResponse(BaseHTTPRequestHandler):+ def _write(self, body: bytes) -> None:+ self.send_response(200)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_PUT(self) -> None:+ self._write(b"token")++ def do_GET(self) -> None:+ if self.path.endswith("/iam/security-credentials/"):+ self._write(b"TestRole")+ else:+ self._write(credential_body)++ def log_message(self, _format, *_args) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.delenv("AWS_EC2_METADATA_DISABLED")+ monkeypatch.setenv("AWS_METADATA_SERVICE_TIMEOUT", "1")+ monkeypatch.setenv("AWS_METADATA_SERVICE_NUM_ATTEMPTS", "1")+ monkeypatch.setenv("NO_PROXY", "*")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ with ThreadingHTTPServer(("127.0.0.1", 0), MetadataResponse) as server:+ monkeypatch.setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", f"http://127.0.0.1:{server.server_port}")+ worker = Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ worker.join(timeout=5)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "TestRole" not in result.detail+++def test_bedrock_model_probe_degrades_malformed_imds_role_listing(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ class MetadataResponse(BaseHTTPRequestHandler):+ def _write(self, status_code: int, body: bytes = b"") -> None:+ self.send_response(status_code)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_PUT(self) -> None:+ self._write(200, b"token")++ def do_GET(self) -> None:+ if self.path.endswith("/iam/security-credentials/"):+ self._write(200, b"Role1\nRole2")+ else:+ self._write(404)++ def log_message(self, _format, *_args) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.delenv("AWS_EC2_METADATA_DISABLED")+ monkeypatch.setenv("AWS_METADATA_SERVICE_TIMEOUT", "1")+ monkeypatch.setenv("AWS_METADATA_SERVICE_NUM_ATTEMPTS", "1")+ monkeypatch.setenv("NO_PROXY", "*")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ with ThreadingHTTPServer(("127.0.0.1", 0), MetadataResponse) as server:+ monkeypatch.setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", f"http://127.0.0.1:{server.server_port}")+ worker = Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ worker.join(timeout=5)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "Role1" not in result.detail++[email protected]("proxy_url", ["http://[::1", "http://127.0.0.1:banana"])+def test_bedrock_model_probe_classifies_malformed_effective_proxy_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ proxy_url: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ for variable in ("https_proxy", "all_proxy", "ALL_PROXY", "no_proxy"):+ monkeypatch.delenv(variable, raising=False)+ monkeypatch.setenv("HTTPS_PROXY", proxy_url)+ monkeypatch.setenv("NO_PROXY", "")+ provider = ProviderConfig(+ provider="bedrock",+ model="test-model",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/test-model",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=2)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "HTTPClientError" in result.detail+ assert proxy_url not in result.detail+++def test_bedrock_model_probe_degrades_valid_but_unavailable_proxy(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ for variable in ("https_proxy", "all_proxy", "ALL_PROXY", "no_proxy"):+ monkeypatch.delenv(variable, raising=False)+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")+ monkeypatch.setenv("NO_PROXY", "")+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=2)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "127.0.0.1" not in result.detail+++def test_bedrock_model_probe_does_not_blame_proxy_bypassed_by_no_proxy(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ class CatalogResponse(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ body = b'{"modelSummaries":[{"modelId":"test-model"}]}'+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, _format, *_args) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ for variable in ("http_proxy", "all_proxy", "ALL_PROXY", "no_proxy"):+ monkeypatch.delenv(variable, raising=False)+ monkeypatch.setenv("HTTP_PROXY", "http://[::1")+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ with ThreadingHTTPServer(("127.0.0.1", 0), CatalogResponse) as server:+ endpoint = f"http://127.0.0.1:{server.server_port}"+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK", endpoint)+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", endpoint)+ worker = Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ worker.join(timeout=5)++ assert result.ok is True+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+++ ("error", "expected_kind"),+ [+ (NoCredentialsError(), "authentication"),+ (UnauthorizedSSOTokenError(), "authentication"),+ (RefreshWithMFAUnsupportedError(), "authentication"),+ (SSOTokenLoadError(error_msg="private SSO token detail"), "authentication"),+ (NoAuthTokenError(), "authentication"),+ (+ PartialCredentialsError(+ provider="env",+ cred_var="AWS_SECRET_ACCESS_KEY",+ ),+ "invalid_configuration",+ ),+ (ProfileNotFound(profile="missing"), "invalid_configuration"),+ (ConfigParseError(path="/private/config"), "invalid_configuration"),+ (ConfigNotFound(path="/private/config"), "invalid_configuration"),+ (+ ApiVersionNotFoundError(data_path="/private/data", api_version="private version"),+ "invalid_configuration",+ ),+ (DataNotFoundError(data_path="/private/data"), "invalid_configuration"),+ (BaseEndpointResolverError(), "invalid_configuration"),+ (EndpointProviderError(msg="private endpoint detail"), "invalid_configuration"),+ (InvalidConfigError(error_msg="invalid profile"), "invalid_configuration"),+ (InvalidDefaultsMode(mode="private mode", valid_modes=["standard"]), "invalid_configuration"),+ (InvalidIMDSEndpointError(endpoint="private endpoint"), "invalid_configuration"),+ (+ InvalidIMDSEndpointModeError(mode="private mode", valid_modes=["ipv4", "ipv6"]),+ "invalid_configuration",+ ),+ (InvalidProxiesConfigError(), "invalid_configuration"),+ (InvalidRegionError(region_name="not a region"), "invalid_configuration"),+ (+ InvalidRetryConfigurationError(+ retry_config_option="private option",+ valid_options=["mode", "max_attempts"],+ ),+ "invalid_configuration",+ ),+ (+ InvalidSTSRegionalEndpointsConfigError(sts_regional_endpoints_config="private mode"),+ "invalid_configuration",+ ),+ (MissingDependencyException(msg="private dependency"), "invalid_configuration"),+ (ParamValidationError(report="private parameter detail"), "invalid_configuration"),+ (+ ServiceNotInRegionError(service_name="private service", region_name="private region"),+ "invalid_configuration",+ ),+ (UnknownCredentialError(name="private credential provider"), "invalid_configuration"),+ (UnknownRegionError(region_name="private region", error_msg="private detail"), "invalid_configuration"),+ (UnknownSignatureVersionError(signature_version="private signature"), "invalid_configuration"),+ (UnsupportedSignatureVersionError(signature_version="private signature"), "invalid_configuration"),+ (FileNotFoundError("private credential file"), "invalid_configuration"),+ (IsADirectoryError("private credential directory"), "invalid_configuration"),+ (NotADirectoryError("private credential parent"), "invalid_configuration"),+ (PermissionError("private credential file"), "invalid_configuration"),+ *(+ [+ (+ botocore_exceptions.UnsupportedServiceProtocolsError(+ botocore_supported_protocols="private protocols",+ service="private service",+ service_supported_protocols="private protocols",+ ),+ "invalid_configuration",+ )+ ]+ if hasattr(botocore_exceptions, "UnsupportedServiceProtocolsError")+ else []+ ),+ *(+ [+ (+ botocore_exceptions.InvalidChecksumConfigError(+ config_key="request_checksum_calculation",+ valid_options=["when_supported"],+ config_value="private value",+ ),+ "invalid_configuration",+ )+ ]+ if hasattr(botocore_exceptions, "InvalidChecksumConfigError")+ else []+ ),+ *(+ [+ (+ botocore_exceptions.UnknownTokenProviderError(name="private token provider"),+ "invalid_configuration",+ )+ ]+ if hasattr(botocore_exceptions, "UnknownTokenProviderError")+ else []+ ),+ *(+ [(botocore_exceptions.LoginRefreshRequired(), "authentication")]+ if hasattr(botocore_exceptions, "LoginRefreshRequired")+ else []+ ),+ ],+)+def test_bedrock_model_probe_fails_on_deterministic_sdk_errors(+ monkeypatch: pytest.MonkeyPatch,+ error: Exception,+ expected_kind: str,+) -> None:+ class Session:+ def __init__(self) -> None:+ raise error++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.ok is False+ assert result.failure_kind == expected_kind+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert type(error).__name__ in result.detail+ assert str(error) not in result.detail++[email protected]("phase", ["session", "catalog"])+def test_bedrock_model_probe_degrades_unattributed_value_errors(+ monkeypatch: pytest.MonkeyPatch,+ phase: str,+) -> None:+ error = ValueError("private remote response detail")++ class Bedrock:+ def list_foundation_models(self):+ raise error++ class Session:+ def __init__(self) -> None:+ if phase == "session":+ raise error++ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.failure_kind == ("unknown" if phase == "session" else "invalid_response")+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private remote response detail" not in result.detail+++def test_bedrock_model_probe_degrades_transport_sdk_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ class Session:+ def __init__(self) -> None:+ raise EndpointConnectionError(endpoint_url="https://bedrock.us-west-2.amazonaws.com/private")++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private" not in result.detail+++def test_bedrock_model_probe_classifies_real_invalid_region_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key")+ monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="not a region",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=1)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "InvalidRegionError" in result.detail+ assert "not a region" not in result.detail+++ ("environment", "expected_error"),+ [+ ({"AWS_DEFAULTS_MODE": "private invalid mode"}, "InvalidDefaultsMode"),+ ({"AWS_EC2_METADATA_SERVICE_ENDPOINT": "private invalid endpoint"}, "InvalidIMDSEndpointError"),+ ({"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "private invalid mode"}, "InvalidIMDSEndpointModeError"),+ ({"AWS_RETRY_MODE": "private invalid mode"}, "InvalidRetryModeError"),+ ({"AWS_MAX_ATTEMPTS": "private invalid integer"}, "ValueError"),+ ({"AWS_METADATA_SERVICE_TIMEOUT": "private invalid integer"}, "ValueError"),+ ({"AWS_METADATA_SERVICE_TIMEOUT": "0"}, "InvalidConfigError"),+ ({"AWS_METADATA_SERVICE_TIMEOUT": "-1"}, "InvalidConfigError"),+ ({"AWS_METADATA_SERVICE_NUM_ATTEMPTS": "private invalid integer"}, "ValueError"),+ ({"AWS_ENDPOINT_URL": "private invalid endpoint"}, "ValueError"),+ ({"AWS_ENDPOINT_URL_BEDROCK": "private invalid endpoint"}, "ValueError"),+ ({"AWS_ENDPOINT_URL_BEDROCK_RUNTIME": "private invalid endpoint"}, "ValueError"),+ (+ {"AWS_CSM_ENABLED": "true", "AWS_CSM_PORT": "private invalid integer"},+ "ValueError",+ ),+ ],+)+def test_bedrock_model_probe_classifies_real_invalid_aws_environment_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ environment: dict[str, str],+ expected_error: str,+) -> None:+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key")+ monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")+ for variable, value in environment.items():+ monkeypatch.setenv(variable, value)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert expected_error in result.detail+ assert all(value not in result.detail for value in environment.values())+++def test_bedrock_model_probe_classifies_real_invalid_profile_api_version_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+region = us-west-2+api_versions =+ bedrock = 1900-01-01+""",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "DataNotFoundError" in result.detail+ assert "1900-01-01" not in result.detail+++def test_bedrock_model_probe_classifies_real_invalid_profile_max_attempts_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+region = us-west-2+max_attempts = private invalid integer+""",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "ValueError" in result.detail+ assert "private invalid integer" not in result.detail++[email protected]("max_attempts", ["0", "-1"])+def test_bedrock_model_probe_classifies_out_of_range_profile_max_attempts_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ max_attempts: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+max_attempts = {max_attempts}+""",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "InvalidMaxRetryAttemptsError" in result.detail+ assert max_attempts not in result.detail++[email protected]("service_name", ["bedrock", "bedrock-runtime"])+def test_bedrock_model_probe_classifies_real_malformed_local_service_data_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ service_name: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ service_model = data_path / service_name / "9999-01-01" / "service-2.json"+ service_model.parent.mkdir(parents=True)+ service_model.write_text("{private malformed service data", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK", "http://127.0.0.1:1")+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed service data" not in result.detail+++def test_bedrock_model_probe_classifies_invalid_compressed_local_sdk_data_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ endpoint_rules = data_path / "bedrock" / "2023-04-20" / "endpoint-rule-set-1.json.gz"+ endpoint_rules.parent.mkdir(parents=True)+ endpoint_rules.write_text("private invalid gzip data", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "BadGzipFile" in result.detail+ assert "private invalid gzip data" not in result.detail+++def test_bedrock_model_probe_does_not_blame_remote_bad_gzip_as_local_configuration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class Bedrock:+ def list_foundation_models(self):+ raise gzip.BadGzipFile("private remote response")++ class Session:+ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "unknown"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private remote response" not in result.detail++[email protected]("credential_source", ["web_identity", "container"])+def test_bedrock_model_probe_classifies_invalid_local_credential_token_encoding_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ credential_source: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ token_path = tmp_path / "private-token"+ token_path.write_bytes(b"\xff")+ if credential_source == "web_identity":+ monkeypatch.setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/Test")+ monkeypatch.setenv("AWS_WEB_IDENTITY_TOKEN_FILE", str(token_path))+ else:+ monkeypatch.setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", "http://127.0.0.1:9/credentials")+ monkeypatch.setenv("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", str(token_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "UnicodeDecodeError" in result.detail+ assert str(token_path) not in result.detail+++def test_bedrock_model_probe_does_not_blame_remote_unicode_error_as_local_configuration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class Bedrock:+ def list_foundation_models(self):+ raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "private remote response")++ class Session:+ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_response"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private remote response" not in result.detail+++def test_bedrock_model_probe_classifies_malformed_assume_role_service_data_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+role_arn = arn:aws:iam::123456789012:role/Test+source_profile = source+region = us-west-2+""",+ credentials="""\+[source]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ service_model = data_path / "sts" / "9999-01-01" / "service-2.json"+ service_model.parent.mkdir(parents=True)+ service_model.write_text("{private malformed service data", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed service data" not in result.detail+++def test_bedrock_model_probe_classifies_malformed_assume_role_endpoint_rules_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+role_arn = arn:aws:iam::123456789012:role/Test+source_profile = source+region = us-west-2+""",+ credentials="""\+[source]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ endpoint_rules = data_path / "sts" / "2011-06-15" / "endpoint-rule-set-1.json"+ endpoint_rules.parent.mkdir(parents=True)+ endpoint_rules.write_text("{private malformed endpoint rules", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed endpoint rules" not in result.detail+++ ("service_name", "api_version"),+ [("bedrock", "2023-04-20"), ("bedrock-runtime", "2023-09-30")],+)+def test_bedrock_model_probe_classifies_malformed_runtime_endpoint_rules_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ service_name: str,+ api_version: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ endpoint_rules = data_path / service_name / api_version / "endpoint-rule-set-1.json"+ endpoint_rules.parent.mkdir(parents=True)+ endpoint_rules.write_text("{private malformed endpoint rules", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed endpoint rules" not in result.detail+++def test_bedrock_model_probe_classifies_malformed_local_endpoints_data_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ data_path = tmp_path / "aws-data"+ data_path.mkdir()+ (data_path / "endpoints.json").write_text("{private malformed endpoints data", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed endpoints data" not in result.detail+++def test_bedrock_model_probe_classifies_malformed_nested_sso_service_data_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+role_arn = arn:aws:iam::123456789012:role/Test+source_profile = source+region = us-west-2++[profile source]+sso_start_url = https://private.awsapps.example/start+sso_region = us-west-2+sso_account_id = 123456789012+sso_role_name = TestRole+""",+ )+ data_path = tmp_path / "aws-data"+ service_model = data_path / "sso" / "9999-01-01" / "service-2.json"+ service_model.parent.mkdir(parents=True)+ service_model.write_text("{private malformed service data", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert "private malformed service data" not in result.detail+++ ("expires_at", "expected_error"),+ [+ ("private malformed timestamp", "ParserError"),+ (None, "TypeError"),+ (123, "TypeError"),+ ([], "TypeError"),+ ({}, "TypeError"),+ ],+)+def test_bedrock_model_probe_classifies_malformed_local_sso_token_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ expires_at: object,+ expected_error: str,+) -> None:+ start_url = "https://private.awsapps.example/start"+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+sso_start_url = {start_url}+sso_region = us-west-2+sso_account_id = 123456789012+sso_role_name = TestRole+""",+ )+ cache_dir = tmp_path / "sso-cache"+ cache_dir.mkdir()+ cache_key = hashlib.sha1(start_url.encode()).hexdigest()+ (cache_dir / f"{cache_key}.json").write_text(+ json.dumps(+ {+ "accessToken": "private-access-token",+ "expiresAt": expires_at,+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(botocore_credentials.SSOProvider, "_SSO_TOKEN_CACHE_DIR", str(cache_dir))+ monkeypatch.setattr(botocore_tokens.SSOTokenProvider, "_SSO_TOKEN_CACHE_DIR", str(cache_dir))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "authentication"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert expected_error in result.detail or "UnauthorizedSSOTokenError" in result.detail+ assert "private" not in result.detail+++def test_bedrock_model_probe_classifies_malformed_local_login_token_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ if not hasattr(botocore_credentials, "LoginProvider"):+ pytest.skip("installed Botocore has no login credential provider")+ session_name = "private-login-session"+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+login_session = {session_name}+""",+ )+ cache_dir = tmp_path / "login-cache"+ cache_dir.mkdir()+ cache_key = hashlib.sha256(session_name.encode()).hexdigest()+ (cache_dir / f"{cache_key}.json").write_text(+ json.dumps(+ {+ "accessToken": {+ "accessKeyId": "test-access-key",+ "secretAccessKey": "test-secret-key",+ "sessionToken": "test-token",+ "accountId": "123456789012",+ "expiresAt": "private malformed timestamp",+ },+ "refreshToken": "test-refresh-token",+ "dpopKey": "test-key",+ "clientId": "test-client",+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv("AWS_LOGIN_CACHE_DIRECTORY", str(cache_dir))+ monkeypatch.setattr(botocore_credentials, "EC", object(), raising=False)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "authentication"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "ParserError" in result.detail+ assert session_name not in result.detail+++def test_bedrock_model_probe_classifies_malformed_credential_process_without_blame_unused_service_data(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ credential_process = tmp_path / "credential-process.py"+ credential_process.write_text("print('{')\n", encoding="utf-8")+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+credential_process = "{sys.executable}" "{credential_process}"+""",+ )+ data_path = tmp_path / "aws-data"+ service_model = data_path / "sts" / "9999-01-01" / "service-2.json"+ service_model.parent.mkdir(parents=True)+ service_model.write_text("{\n", encoding="utf-8")+ monkeypatch.setenv("AWS_DATA_PATH", str(data_path))+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "JSONDecodeError" in result.detail+ assert str(credential_process) not in result.detail++[email protected]("configuration_source", ["environment", "profile"])[email protected]("bundle_state", ["missing", "invalid"])+def test_bedrock_model_probe_classifies_proven_invalid_ca_bundle_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ bundle_state: str,+ configuration_source: str,+) -> None:+ bundle_path = tmp_path / "private-ca-bundle.pem"+ if bundle_state == "invalid":+ bundle_path.write_text("private invalid CA data", encoding="utf-8")+ if configuration_source == "environment":+ monkeypatch.setenv("AWS_CA_BUNDLE", str(bundle_path))+ real_session = None+ else:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+ca_bundle = {bundle_path}+""",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ real_session = runtime_preflight.boto3.session.Session()+ error = BotocoreSSLError(endpoint_url="https://private.example", error="private TLS detail")++ class Session:+ def __init__(self) -> None:+ if real_session is None:+ raise error+ self._session = real_session._session++ def client(self, *_args, **_kwargs):+ raise error++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "SSLError" in result.detail+ assert "private" not in result.detail+++def test_bedrock_model_probe_degrades_unattributed_tls_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ error = BotocoreSSLError(endpoint_url="https://private.example", error="private TLS detail")++ class Session:+ def __init__(self) -> None:+ raise error++ monkeypatch.delenv("AWS_CA_BUNDLE", raising=False)+ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private" not in result.detail+++def test_bedrock_model_probe_rejects_invalid_ca_bundle_before_https_runtime(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ bundle_path = tmp_path / "missing-ca-bundle.pem"+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ monkeypatch.setenv("AWS_CA_BUNDLE", str(bundle_path))+ real_session = runtime_preflight.boto3.session.Session()++ class Client:+ meta = type("Meta", (), {"endpoint_url": "https://private.example"})()++ def list_foundation_models(self):+ return {"modelSummaries": [{"modelId": "test-model"}]}++ class Session:+ def __init__(self) -> None:+ self._session = real_session._session++ def get_credentials(self):+ return real_session.get_credentials()++ def client(self, *_args, **_kwargs):+ return Client()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert str(bundle_path) not in result.detail+++def test_bedrock_model_probe_classifies_real_invalid_credential_process_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+region = us-west-2+credential_process = private-command "unterminated+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "ValueError" in result.detail+ assert "private-command" not in result.detail+++def test_bedrock_model_probe_classifies_real_unexecutable_credential_process_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ credential_process = tmp_path / "credential-process"+ credential_process.write_text("private invalid executable", encoding="utf-8")+ credential_process.chmod(0o700)+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+credential_process = {credential_process}+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "OSError" in result.detail+ assert str(credential_process) not in result.detail+++ ("payload", "exit_code", "expected_kind", "expected_disposition"),+ [+ ({"Version": 1}, 0, "invalid_configuration", "fatal"),+ ({"Version": 2}, 0, "invalid_configuration", "fatal"),+ (+ {+ "Version": 1,+ "AccessKeyId": "test-access-key",+ "SecretAccessKey": "test-secret-key",+ "SessionToken": "test-session-token",+ "Expiration": "private malformed timestamp",+ },+ 0,+ "invalid_configuration",+ "fatal",+ ),+ (None, 1, "unavailable", "degraded"),+ ],+)+def test_bedrock_model_probe_classifies_structural_credential_process_output_causally(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ payload: dict[str, object] | None,+ exit_code: int,+ expected_kind: str,+ expected_disposition: str,+) -> None:+ credential_process = tmp_path / "credential-process.py"+ if exit_code != 0:+ credential_process.write_text(+ 'import sys\nprint("private process failure", file=sys.stderr)\nsys.exit(1)\n',+ encoding="utf-8",+ )+ else:+ credential_process.write_text(f"print({json.dumps(payload)!r})\n", encoding="utf-8")+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config=f"""\+[profile test]+region = us-west-2+credential_process = "{sys.executable}" "{credential_process}"+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == expected_kind+ assert runtime_preflight.credential_probe_disposition(provider, result) == expected_disposition+ assert "private" not in result.detail+ assert str(credential_process) not in result.detail+++def test_bedrock_model_probe_degrades_transient_credential_process_spawn_error(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ original_init = botocore_credentials.ProcessProvider.__init__++ def failing_init(self, *args, **kwargs) -> None:+ original_init(self, *args, **kwargs)++ def fail_to_spawn(*_args, **_kwargs):+ raise BlockingIOError(errno.EAGAIN, "private temporary spawn failure")++ self._popen = fail_to_spawn++ monkeypatch.setattr(botocore_credentials.ProcessProvider, "__init__", failing_init)+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+region = us-west-2+credential_process = private-command+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "unavailable"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private" not in result.detail+++ ("environment", "expected_error"),+ [+ ({"AWS_STS_REGIONAL_ENDPOINTS": "private invalid mode"}, "InvalidSTSRegionalEndpointsConfigError"),+ ({"AWS_RETRY_MODE": "private invalid mode"}, "InvalidRetryModeError"),+ ({"AWS_MAX_ATTEMPTS": "private invalid integer"}, "ValueError"),+ ({"AWS_ENDPOINT_URL_STS": "private invalid endpoint"}, "ValueError"),+ ],+)+def test_bedrock_model_probe_classifies_real_invalid_assume_role_configuration_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ environment: dict[str, str],+ expected_error: str,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+role_arn = arn:aws:iam::123456789012:role/Test+source_profile = source+region = us-west-2+""",+ credentials="""\+[source]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ for variable, value in environment.items():+ monkeypatch.setenv(variable, value)+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert expected_error in result.detail+ assert all(value not in result.detail for value in environment.values())+++def test_bedrock_model_probe_classifies_real_invalid_assume_role_parameters_as_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="""\+[profile test]+role_arn = arn:aws:iam::123456789012:role/Test+role_session_name = !+source_profile = source+region = us-west-2+""",+ credentials="""\+[source]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ provider = ProviderConfig(+ provider="bedrock",+ model="us.anthropic.claude-sonnet-test-v1:0",+ api_key=None,+ base_url=None,+ litellm_model="bedrock/us.anthropic.claude-sonnet-test-v1:0",+ region="us-west-2",+ )++ result = runtime_preflight.probe_model(provider, timeout_seconds=5)++ assert result.failure_kind == "invalid_configuration"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "fatal"+ assert "ParamValidationError" in result.detail+ assert "role_session_name" not in result.detail+++def test_bedrock_model_probe_degrades_malformed_catalog_timestamp(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ lifecycle_shape = BotocoreSession().get_service_model("bedrock").shape_for("FoundationModelLifecycle")+ if "startOfLifeTime" not in lifecycle_shape.members:+ pytest.skip("installed Botocore service model has no Bedrock lifecycle timestamps")+ requests: list[str] = []++ class MalformedCatalog(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requests.append(self.path)+ payload = json.dumps(+ {+ "modelSummaries": [+ {+ "modelId": "test-model",+ "modelLifecycle": {+ "status": "ACTIVE",+ "startOfLifeTime": "private malformed timestamp",+ },+ }+ ]+ }+ ).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, _format: str, *_args: object) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ credentials="""\+[test]+aws_access_key_id = test-access-key+aws_secret_access_key = test-secret-key+""",+ )+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")+ with ThreadingHTTPServer(("127.0.0.1", 0), MalformedCatalog) as server:+ monkeypatch.setenv("AWS_ENDPOINT_URL_BEDROCK", f"http://127.0.0.1:{server.server_port}")+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ thread.join(timeout=2)++ assert requests == ["/foundation-models"]+ assert result.failure_kind == "invalid_response"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private malformed timestamp" not in result.detail+++def test_bedrock_model_probe_degrades_malformed_container_credential_timestamp(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ requests: list[str] = []++ class MalformedCredentials(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requests.append(self.path)+ payload = json.dumps(+ {+ "AccessKeyId": "test-access-key",+ "SecretAccessKey": "test-secret-key",+ "Token": "test-token",+ "Expiration": "private malformed timestamp",+ }+ ).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, _format: str, *_args: object) -> None:+ return++ _configure_isolated_aws_profile(+ monkeypatch,+ tmp_path,+ config="[profile test]\nregion = us-west-2\n",+ )+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")+ with ThreadingHTTPServer(("127.0.0.1", 0), MalformedCredentials) as server:+ monkeypatch.setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", f"http://127.0.0.1:{server.server_port}/creds")+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ provider = ProviderConfig("bedrock", "test-model", None, None, "bedrock/test-model", region="us-west-2")+ result = runtime_preflight.probe_model(provider, timeout_seconds=5)+ finally:+ server.shutdown()+ thread.join(timeout=2)++ assert requests == ["/creds"]+ assert result.failure_kind == "unknown"+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert "private malformed timestamp" not in result.detail+++def test_bedrock_model_probe_uses_a_fresh_session_per_route(monkeypatch) -> None:+ sessions: list[object] = []++ class Bedrock:+ def list_foundation_models(self):+ return {"modelSummaries": []}++ class Session:+ def __init__(self):+ sessions.append(self)++ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ first = ProviderConfig("bedrock", "model-a", None, None, "bedrock/model-a", region="us-west-2")+ second = ProviderConfig("bedrock", "model-b", None, None, "bedrock/model-b", region="us-west-2")++ runtime_preflight.probe_model(first)+ runtime_preflight.probe_model(second)++ assert len(sessions) == 2+ assert sessions[0] is not sessions[1]+++def test_bedrock_model_probe_allows_distinct_routes_to_overlap(monkeypatch) -> None:+ rendezvous = Barrier(2)+ counter_lock = Lock()+ active = 0+ max_active = 0++ class Bedrock:+ def list_foundation_models(self):+ nonlocal active, max_active+ with counter_lock:+ active += 1+ max_active = max(max_active, active)+ try:+ rendezvous.wait(timeout=0.5)+ return {"modelSummaries": []}+ finally:+ with counter_lock:+ active -= 1++ class Session:+ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ providers = [+ ProviderConfig("bedrock", "model-a", None, None, "bedrock/model-a", region="us-west-2"),+ ProviderConfig("bedrock", "model-b", None, None, "bedrock/model-b", region="us-west-2"),+ ]++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(runtime_preflight.probe_model, providers))++ assert max_active == 2+ assert all(result.failure_kind is None and "not listed" in result.detail for result in results)+++def test_bedrock_model_probe_deadline_covers_blocked_credential_provider(monkeypatch) -> None:+ release = Event()+ credential_provider_finished = Event()+ existing_threads = {id(thread) for thread in enumerate_threads()}++ class Session:+ def __init__(self):+ release.wait(timeout=1)+ credential_provider_finished.set()++ def client(self, *_args, **_kwargs):+ raise AssertionError("client creation must remain inside the deadline worker")++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "model", None, None, "bedrock/model", region="us-west-2")+ try:+ result = runtime_preflight.probe_model(provider, timeout_seconds=0.02)+ credential_provider_finished_before_release = credential_provider_finished.is_set()+ finally:+ release.set()+ for thread in enumerate_threads():+ if id(thread) not in existing_threads and thread.name == "bedrock-model-catalog-probe":+ thread.join(timeout=0.2)++ assert result.ok is False+ assert result.failure_kind == "unavailable"+ assert "timed out" in result.detail+ assert credential_provider_finished_before_release is False+++def test_bedrock_model_probe_deadline_caps_blocked_workers(monkeypatch) -> None:+ release = Event()+ existing_threads = {id(thread) for thread in enumerate_threads()}++ class Session:+ def __init__(self):+ release.wait(timeout=1)++ def client(self, *_args, **_kwargs):+ raise AssertionError("client creation must remain inside the deadline worker")++ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ provider = ProviderConfig("bedrock", "model", None, None, "bedrock/model", region="us-west-2")+ try:+ results = [runtime_preflight.probe_model(provider, timeout_seconds=0.005) for _ in range(10)]+ probe_threads = [+ thread+ for thread in enumerate_threads()+ if id(thread) not in existing_threads and thread.name == "bedrock-model-catalog-probe"+ ]+ finally:+ release.set()++ assert all(result.failure_kind == "unavailable" and "timed out" in result.detail for result in results)+ assert len(probe_threads) == 4+ for thread in probe_threads:+ thread.join(timeout=0.2)++[email protected]("failure_phase", ["constructor", "start"])+def test_bedrock_model_probe_releases_slot_when_worker_creation_fails(+ monkeypatch: pytest.MonkeyPatch,+ failure_phase: str,+) -> None:+ real_thread = runtime_preflight.Thread+ attempts = 0++ class ThreadFailsOnce:+ def __init__(self, *args, **kwargs) -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1 and failure_phase == "constructor":+ raise RuntimeError("private worker-constructor detail")+ self._thread = real_thread(*args, **kwargs)++ def start(self) -> None:+ if attempts == 1 and failure_phase == "start":+ raise RuntimeError("private worker-start detail")+ self._thread.start()++ class Bedrock:+ def list_foundation_models(self):+ return {"modelSummaries": [{"modelId": "model"}]}++ class Session:+ def client(self, *_args, **_kwargs):+ return Bedrock()++ monkeypatch.setattr(runtime_preflight, "Thread", ThreadFailsOnce)+ monkeypatch.setattr(runtime_preflight.boto3.session, "Session", Session)+ monkeypatch.setattr(runtime_preflight, "_BEDROCK_PROBE_SLOT", runtime_preflight.BoundedSemaphore(1))+ provider = ProviderConfig("bedrock", "model", None, None, "bedrock/model", region="us-west-2")++ failed = runtime_preflight.probe_model(provider, timeout_seconds=0.1)+ recovered = runtime_preflight.probe_model(provider, timeout_seconds=0.1)++ assert failed.ok is False+ assert failed.failure_kind == "unknown"+ assert runtime_preflight.credential_probe_disposition(provider, failed) == "degraded"+ assert "RuntimeError" in failed.detail+ assert "private worker" not in failed.detail+ assert recovered.ok is True+++def test_runtime_preflight_failure_stops_full_matrix(monkeypatch, tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor import runner++ skill = tmp_path / "demo"+ (skill / "evals").mkdir(parents=True)+ (skill / "evals" / "evals.json").write_text("[]\n", encoding="utf-8")+ provider = ProviderConfig(+ provider="nv_build",+ model="meta/llama-3.1-8b-instruct",+ api_key="nvapi-test",+ base_url="https://integrate.api.nvidia.com/v1",+ litellm_model="openai/meta/llama-3.1-8b-instruct",+ )++ def emit(_skill, target, **_kwargs):+ task = target / "case-001"+ task.mkdir(parents=True)+ return [task]++ full_matrix = Mock(return_value=[])+ preflight_run_env: dict[str, str] = {}+ monkeypatch.setenv("LLM_JUDGE_MODEL", "host-legacy")+ monkeypatch.delenv("SKILL_EVAL_JUDGE_MODEL", raising=False)+ monkeypatch.setattr(runner, "resolve_llm_provider", lambda: provider)+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: ({"harbor": {"task_source": "evals_json"}}, None),+ )+ monkeypatch.setattr(runner, "find_evals_file", lambda _path: skill / "evals" / "evals.json")+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])+ monkeypatch.setattr(runner, "generate_harbor_tasks", emit)+ monkeypatch.setattr(runner, "_run_agent_pair", full_matrix)+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )++ def fail_preflight(**kwargs):+ preflight_run_env.update(kwargs["run_env"])+ return runtime_preflight.PreflightResult(+ False,+ "opencode",+ "nvidia/meta/llama-3.1-8b-instruct",+ "401 Unauthorized",+ "runtime-preflight-opencode",+ )++ monkeypatch.setattr(runtime_preflight, "run_agent_runtime_preflight", fail_preflight)++ result = runner.run_harbor_eval(+ skill,+ ["opencode"],+ output_dir=tmp_path / "results",+ env_mode="docker",+ agent_runtime_preflight=True,+ )++ assert result["execution_status"] == "failed"+ assert result["execution_errors"] == ["opencode runtime preflight failed: 401 Unauthorized"]+ assert preflight_run_env["LLM_JUDGE_MODEL"] == "host-legacy"assert preflight_run_env["SKILL_EVAL_JUDGE_MODEL"] == "host-legacy"full_matrix.assert_not_called()result_path = Path(result["run_dir"]) / "result.json"@@ -737,3 +3597,53 @@ def test_runtime_preflight_failure_stops_full_matrix(monkeypatch, tmp_path: Pathassert result["harbor_jobs_retention_reason"] == "not_retained"assert not (Path(result["run_dir"]) / "_harbor-jobs").exists()assert not (Path(result["run_dir"]) / "_harbor-tasks").exists()+ assert result["run_config"]["credential_validation"]["status"] == "degraded"+ validation_targets = result["run_config"]["credential_validation"]["targets"]+ assert {target["status"] for target in validation_targets} == {"degraded"}+ assert {target["detail"] for target in validation_targets} == {+ "model catalog access does not verify runtime credentials for this endpoint"+ }+ persisted = json.loads(result_path.read_text(encoding="utf-8"))+ assert persisted["run_config"] == result["run_config"]+ run_config_path = Path(result["run_dir"]) / "run_config.json"+ assert json.loads(run_config_path.read_text(encoding="utf-8")) == result["run_config"]++[email protected]("provider_name", ["openai", "openai-compatible", "anthropic"])+def test_live_custom_catalog_401_is_inconclusive_without_exposing_secret(provider_name: str) -> None:+ requests: list[str] = []+ secret = "loopback-provider-secret"++ class RejectingCatalog(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requests.append(self.path)+ self.send_response(401)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(json.dumps({"error": f"rejected {secret}"}).encode())++ def log_message(self, *_args) -> None:+ return None++ with ThreadingHTTPServer(("127.0.0.1", 0), RejectingCatalog) as server:+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ provider = ProviderConfig(+ provider=provider_name,+ model="requested-model",+ api_key=secret,+ base_url=f"http://127.0.0.1:{server.server_port}/v1",+ litellm_model=f"{'anthropic' if provider_name == 'anthropic' else 'openai'}/requested-model",+ )+ result = runtime_preflight.probe_model(provider)+ finally:+ server.shutdown()+ thread.join(timeout=2)++ assert result.ok is False+ assert result.failure_kind == "authentication"+ assert result.http_status == 401+ assert runtime_preflight.credential_probe_disposition(provider, result) == "degraded"+ assert secret not in result.detail+ assert requests == ["/v1/models"]diff --git a/tests/test_harbor_secure_docker_environment.py b/tests/test_harbor_secure_docker_environment.pyindex 3b2a7dab..d7daceac 100644--- a/tests/test_harbor_secure_docker_environment.py+++ b/tests/test_harbor_secure_docker_environment.py@@ -217,6 +217,55 @@ def test_compose_check_false_redacts_success_output(assert result.stderr == "stderr [REDACTED]"+def test_compose_stdin_handoff_redacts_secret_without_argv_or_environment(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ environment = object.__new__(SkillEvaluatorDockerEnvironment)+ environment.session_id = "secure-stdin-test"+ environment.environment_name = "secure-stdin-test"+ environment.environment_dir = tmp_path+ environment._resources_compose_path = None+ environment._mounts_compose_path = None+ environment._use_prebuilt = True+ environment._is_windows_container = False+ environment.extra_docker_compose_paths = []+ environment._network_policy = SimpleNamespace(network_mode="public")+ environment._compose_env_vars = MethodType(lambda _self, **_kwargs: {"PATH": "/usr/bin"}, environment)+ captured: dict[str, object] = {}++ class Process:+ returncode = 9++ async def communicate(self, input_bytes: bytes | None = None) -> tuple[bytes, None]:+ captured["input"] = input_bytes+ return f"failure included {_SENTINEL}".encode(), None++ async def create_subprocess(*args: object, **kwargs: object) -> Process:+ captured["args"] = args+ captured["env"] = kwargs["env"]+ captured["stdin"] = kwargs["stdin"]+ return Process()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", create_subprocess)++ with pytest.raises(RuntimeError) as caught:+ asyncio.run(+ environment._run_docker_compose_command(+ ["exec", "-T", "main", "true"],+ stdin_bytes=b"private-stream-payload",+ redact_values={_SENTINEL},+ )+ )++ assert captured["input"] == b"private-stream-payload"+ assert captured["stdin"] is asyncio.subprocess.PIPE+ assert _SENTINEL not in " ".join(str(arg) for arg in captured["args"])+ assert _SENTINEL not in captured["env"].values()+ assert _SENTINEL not in str(caught.value)+ assert "[REDACTED]" in str(caught.value)++def test_redact_ignores_short_env_values_that_would_corrupt_loopback_origins() -> None:from skillevaluator.tier3.harbor.secure_docker_environment import _redact@@ -809,7 +858,7 @@ def test_real_docker_interrupted_exec_stops_task_container_only(monkeypatch.setattr(asyncio, "create_subprocess_exec", capture_exec_client)normal_result = asyncio.run(- environment.exec(+ environment.exec_with_sensitive_env("printf 'normal-output\\n'; printf 'normal-error\\n' >&2; ""printf 'control-token=%s\\n' \"${SKILLEVALUATOR_EXEC_TOKEN-unset}\"; exit 7",env={"NVIDIA_API_KEY": credential},diff --git a/tests/test_model_catalog.py b/tests/test_model_catalog.pyindex 231db7d7..22ebc4b1 100644--- a/tests/test_model_catalog.py+++ b/tests/test_model_catalog.py@@ -19,6 +19,7 @@ from skillevaluator import model_catalogfrom skillevaluator.model_catalog import (ModelCatalogError,ModelRecord,+ fetch_anthropic_model_record,fetch_model_records,select_catalog_models,)@@ -112,6 +113,27 @@ def test_fetch_model_records_uses_anthropic_native_headers(monkeypatch) -> None:assert "Authorization" not in captured["headers"]+def test_fetch_anthropic_model_record_encodes_alias_as_one_path_segment(monkeypatch) -> None:+ captured: dict[str, object] = {}++ def fake_urlopen(request, *, timeout):+ captured.update(url=request.full_url, headers=dict(request.header_items()), timeout=timeout)+ return _Response({"id": "claude-canonical-20260824", "display_name": "Claude"})++ monkeypatch.setattr(model_catalog, "urlopen", fake_urlopen)++ record = fetch_anthropic_model_record(+ _provider("anthropic"),+ "claude/alias",+ timeout_seconds=4.5,+ )++ assert record == ModelRecord("claude-canonical-20260824")+ assert captured["url"] == "https://api.anthropic.com/v1/models/claude%2Falias"+ assert captured["timeout"] == 4.5+ assert captured["headers"]["X-api-key"] == "top-secret-key"++def test_fetch_model_records_follows_bounded_anthropic_cursor_pages(monkeypatch) -> None:urls: list[str] = []pages = iter(@@ -459,8 +481,9 @@ def test_bedrock_catalog_defers_to_existing_doctor_without_network(monkeypatch)lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("network must not be called")),)- with pytest.raises(ModelCatalogError, match=r"doctor --verify-models"):+ with pytest.raises(ModelCatalogError, match=r"doctor --verify-models") as caught:fetch_model_records(_provider("bedrock", api_key=None))+ assert getattr(caught.value, "kind", None) == "unsupported"def test_fetch_normalizes_deduplicates_and_skips_unsafe_records(monkeypatch) -> None:@@ -511,6 +534,41 @@ def test_fetch_never_exposes_http_body_reason_url_or_key(monkeypatch) -> None:assert all(secret not in message for secret in ("top-secret-key", "secret-path", "query-secret", "password"))+ ("status", "expected_kind"),+ [+ (401, "authentication"),+ (403, "authorization"),+ (404, "unsupported"),+ (405, "unsupported"),+ (408, "unavailable"),+ (429, "unavailable"),+ (500, "unavailable"),+ (418, "other_http"),+ ],+)+def test_fetch_classifies_http_failures_without_exposing_response(+ monkeypatch,+ status: int,+ expected_kind: str,+) -> None:+ error = HTTPError(+ "https://example.test/private-path",+ status,+ "reason contains top-secret-key",+ {},+ io.BytesIO(b"body contains top-secret-key"),+ )+ monkeypatch.setattr(model_catalog, "urlopen", lambda *_args, **_kwargs: (_ for _ in ()).throw(error))++ with pytest.raises(ModelCatalogError) as caught:+ fetch_model_records(_provider("openai"))++ assert getattr(caught.value, "kind", None) == expected_kind+ assert getattr(caught.value, "http_status", None) == status+ assert "top-secret-key" not in str(caught.value)++def test_fetch_redacts_transport_reason(monkeypatch) -> None:monkeypatch.setattr(model_catalog,@@ -522,6 +580,7 @@ def test_fetch_redacts_transport_reason(monkeypatch) -> None:fetch_model_records(_provider("nv_build"))assert str(caught.value) == "model catalog request failed: URLError"+ assert getattr(caught.value, "kind", None) == "unavailable"@pytest.mark.parametrize(@@ -552,34 +611,37 @@ def test_fetch_redacts_low_level_http_protocol_failures(monkeypatch, failure: Exdef test_fetch_rejects_oversized_and_invalid_json_responses(monkeypatch) -> None:monkeypatch.setattr(model_catalog, "urlopen", lambda *_args, **_kwargs: _Response(b"x" * (2 * 1024 * 1024 + 1)))- with pytest.raises(ModelCatalogError, match="safe size limit"):+ with pytest.raises(ModelCatalogError, match="safe size limit") as oversized:fetch_model_records(_provider("openai"))+ assert getattr(oversized.value, "kind", None) == "invalid_response"monkeypatch.setattr(model_catalog, "urlopen", lambda *_args, **_kwargs: _Response(b"not-json"))- with pytest.raises(ModelCatalogError, match="invalid JSON"):+ with pytest.raises(ModelCatalogError, match="invalid JSON") as invalid_json:fetch_model_records(_provider("openai"))+ assert getattr(invalid_json.value, "kind", None) == "invalid_response"@pytest.mark.parametrize(- "base_url",+ ("base_url", "expected_kind"),[- "http://example.test/v1",- "http://192.168.1.2/v1",- "http://169.254.1.1/v1",- "http://0.0.0.0/v1",- "file:///tmp/catalog",- "https://user:[email protected]/v1",- "https://example.test/v1?token=secret",- "https://example.test/v1#fragment",- "https://example.test\\@evil.test/v1",- " https://example.test/v1",- "https://example.test/v1\n",- "https://example.test:invalid/v1",+ ("http://example.test/v1", "unsupported"),+ ("http://192.168.1.2/v1", "unsupported"),+ ("http://169.254.1.1/v1", "unsupported"),+ ("http://0.0.0.0/v1", "unsupported"),+ ("file:///tmp/catalog", "invalid_configuration"),+ ("https://user:[email protected]/v1", "invalid_configuration"),+ ("https://example.test/v1?token=secret", "invalid_configuration"),+ ("https://example.test/v1#fragment", "invalid_configuration"),+ ("https://example.test\\@evil.test/v1", "invalid_configuration"),+ (" https://example.test/v1", "invalid_configuration"),+ ("https://example.test/v1\n", "invalid_configuration"),+ ("https://example.test:invalid/v1", "invalid_configuration"),],)-def test_catalog_rejects_unsafe_base_urls(base_url: str) -> None:- with pytest.raises(ModelCatalogError, match="model catalog base URL"):+def test_catalog_rejects_unsafe_base_urls(base_url: str, expected_kind: str) -> None:+ with pytest.raises(ModelCatalogError, match="model catalog base URL") as caught:fetch_model_records(_provider("openai-compatible", base_url=base_url))+ assert getattr(caught.value, "kind", None) == expected_kind@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "127.0.0.2", "[::1]"])diff --git a/tests/test_models_command.py b/tests/test_models_command.pyindex ecbc850d..3da075a5 100644--- a/tests/test_models_command.py+++ b/tests/test_models_command.py@@ -52,7 +52,9 @@ def test_models_help_exposes_catalog_options_without_runtime_verification() -> Nassert "--json" in result.outputassert "--verify" not in result.outputassert "--agents" not in result.output- assert "catalog" in result.output.lower()+ normalized_output = " ".join(result.output.split()).lower()+ assert "catalog reachability" in normalized_output+ assert "authenticated" not in normalized_outputdef test_models_missing_provider_uses_canonical_configuration_error(monkeypatch) -> None:diff --git a/tests/test_oss_packaging.py b/tests/test_oss_packaging.pyindex b59ebef2..5d80f381 100644--- a/tests/test_oss_packaging.py+++ b/tests/test_oss_packaging.py@@ -44,6 +44,7 @@ PACKAGED_NVIDIA_BUILD_RUNTIME_FILES = {"skillevaluator/tier3/harbor/local_agents.py","skillevaluator/tier3/harbor/nvidia_build_bridge.py","skillevaluator/tier3/harbor/secure_docker_environment.py",+ "skillevaluator/tier3/harbor/sensitive_stdin.py",}SOURCE_SCAN_EXCLUDED_DIRS = {".git",diff --git a/tests/test_secure_docker_environment.py b/tests/test_secure_docker_environment.pyindex 499db5fc..42f5d2bd 100644--- a/tests/test_secure_docker_environment.py+++ b/tests/test_secure_docker_environment.py@@ -6,15 +6,21 @@from __future__ import annotationsimport asyncio+import hashlibimport importlibimport importlib.util+import io+import os+import subprocess+import sys+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom types import SimpleNamespaceimport pytest-def test_secure_docker_exec_hands_environment_over_by_file_without_argv_values(+def test_secure_docker_exec_streams_environment_without_host_file_or_argv_values(monkeypatch,tmp_path: Path,) -> None:@@ -27,8 +33,10 @@ def test_secure_docker_exec_hands_environment_over_by_file_without_argv_values(environment.task_env_config = SimpleNamespace(workdir="/workspace")environment._platform = SimpleNamespace(exec_shell_args=lambda command: ["bash", "-c", command])+ del tmp_pathuploaded: list[tuple[str, str]] = []docker_commands: list[list[str]] = []+ handoff_payloads: list[str] = []async def fake_upload_file(source_path: Path | str, target_path: str) -> None:uploaded.append((Path(source_path).read_text(encoding="utf-8"), target_path))@@ -38,10 +46,15 @@ def test_secure_docker_exec_hands_environment_over_by_file_without_argv_values(check: bool = True,timeout_sec: int | None = None,*,+ stdin_bytes: bytes | None = None,+ redact_values: set[str] | None = None,stop_main_on_interrupt: bool = False,):del check, timeout_secassert stop_main_on_interrupt is ("if ! ." in " ".join(command))+ if stdin_bytes is not None:+ handoff_payloads.append(stdin_bytes.decode("utf-8"))+ assert redact_values is not Nonedocker_commands.append(command)return SimpleNamespace(stdout="ok", stderr=None, return_code=0)@@ -57,8 +70,10 @@ def test_secure_docker_exec_hands_environment_over_by_file_without_argv_values()assert result.return_code == 0- assert uploaded and secret in uploaded[0][0]- assert "persistent-secret-value" in uploaded[0][0]+ assert uploaded == []+ assert len(handoff_payloads) == 1+ assert secret in handoff_payloads[0]+ assert "persistent-secret-value" in handoff_payloads[0]rendered_argv = "\n".join("\0".join(command) for command in docker_commands)assert secret not in rendered_argvassert "persistent-secret-value" not in rendered_argv@@ -99,7 +114,7 @@ def test_secure_docker_exec_redacts_persistent_and_per_call_credentials_from_alldef __init__(self, *, expose_secrets: bool) -> None:self._expose_secrets = expose_secrets- async def communicate(self) -> tuple[bytes, bytes]:+ async def communicate(self, _input: bytes | None = None) -> tuple[bytes, bytes]:if not self._expose_secrets:return b"", b""output = f"stdout {persistent_secret} {per_call_secret}".encode()@@ -140,7 +155,7 @@ def test_nvidia_build_docker_command_uses_secure_environment_and_bridge() -> Nonassert "--env" not in command-def test_secure_docker_exec_cleans_remote_handoff_when_upload_reports_failure(+def test_secure_docker_exec_cleans_remote_handoff_when_streaming_reports_failure(monkeypatch,tmp_path: Path,) -> None:@@ -153,16 +168,25 @@ def test_secure_docker_exec_cleans_remote_handoff_when_upload_reports_failure(environment._platform = SimpleNamespace(exec_shell_args=lambda command: ["bash", "-c", command])removed: list[str] = []- async def upload_then_fail(_source_path: Path | str, _target_path: str) -> None:- raise ConnectionError("docker cp disconnected after creating the file")+ async def stream_then_fail(+ _command: list[str],+ _check: bool = True,+ _timeout_sec: int | None = None,+ *,+ stdin_bytes: bytes | None = None,+ **_kwargs,+ ) -> SimpleNamespace:+ if stdin_bytes is not None:+ raise ConnectionError("docker exec disconnected after creating the file")+ return SimpleNamespace(stdout="", stderr=None, return_code=0)async def remove_handoff(remote_path: str) -> None:removed.append(remote_path)- monkeypatch.setattr(environment, "upload_file", upload_then_fail)+ monkeypatch.setattr(environment, "_run_docker_compose_command", stream_then_fail)monkeypatch.setattr(environment, "_remove_handoff", remove_handoff)- with pytest.raises(ConnectionError, match="docker cp disconnected"):+ with pytest.raises(ConnectionError, match="docker exec disconnected"):asyncio.run(environment.exec("true", env={"NVIDIA_API_KEY": "secret-for-test"}))assert len(removed) == 1@@ -184,9 +208,18 @@ def test_secure_docker_exec_repeated_cancellation_does_not_interrupt_handoff_clerelease_cleanup = asyncio.Event()cleanup_finished = False- async def blocked_upload(_source_path: Path | str, _target_path: str) -> None:- upload_started.set()- await asyncio.Event().wait()+ async def blocked_stream(+ _command: list[str],+ _check: bool = True,+ _timeout_sec: int | None = None,+ *,+ stdin_bytes: bytes | None = None,+ **_kwargs,+ ) -> SimpleNamespace:+ if stdin_bytes is not None:+ upload_started.set()+ await asyncio.Event().wait()+ return SimpleNamespace(stdout="", stderr=None, return_code=0)async def remove_handoff(_remote_path: str) -> None:nonlocal cleanup_finished@@ -194,7 +227,7 @@ def test_secure_docker_exec_repeated_cancellation_does_not_interrupt_handoff_cleawait release_cleanup.wait()cleanup_finished = True- monkeypatch.setattr(environment, "upload_file", blocked_upload)+ monkeypatch.setattr(environment, "_run_docker_compose_command", blocked_stream)monkeypatch.setattr(environment, "_remove_handoff", remove_handoff)task = asyncio.create_task(environment.exec("true", env={"NVIDIA_API_KEY": "secret-for-test"}))@@ -226,9 +259,11 @@ def test_secure_docker_exec_fails_closed_when_final_secret_cleanup_fails(monkeypcheck: bool = True,timeout_sec: int | None = None,*,+ stdin_bytes: bytes | None = None,+ redact_values: set[str] | None = None,stop_main_on_interrupt: bool = False,):- del check, timeout_sec+ del check, timeout_sec, stdin_bytes, redact_valuesassert stop_main_on_interrupt is ("if ! ." in " ".join(command))return SimpleNamespace(stdout="ok", stderr=None, return_code=0)@@ -257,20 +292,24 @@ def test_secure_docker_remove_handoff_rejects_nonzero_docker_result(monkeypatch)asyncio.run(environment._remove_handoff("/tmp/secret-handoff"))-def test_harbor_subprocess_receives_only_file_backed_nvidia_sentinel(monkeypatch, tmp_path: Path) -> None:+def test_harbor_subprocess_receives_nvidia_key_only_over_stdin(monkeypatch, tmp_path: Path) -> None:from skillevaluator.tier3.harbor import runnersecret = "nvidia-real-secret-value-for-test"- observed_key_files: list[Path] = []++ def reject_temporary_directory(*_args, **_kwargs):+ raise AssertionError("NVIDIA key handoff must not create a temporary directory")++ monkeypatch.setattr(runner.tempfile, "TemporaryDirectory", reject_temporary_directory)def fake_run(command, **kwargs):environment = kwargs["env"]assert secret not in commandassert secret not in environment.values()- assert environment["NVIDIA_API_KEY"] == runner._NVIDIA_BUILD_FILE_SENTINEL- key_file = Path(environment["SKILLEVALUATOR_NVIDIA_API_KEY_FILE"])- observed_key_files.append(key_file)- assert key_file.read_text(encoding="utf-8") == secret+ assert environment["NVIDIA_API_KEY"] == runner._NVIDIA_BUILD_STDIN_SENTINEL+ assert environment[runner._NVIDIA_BUILD_KEY_STDIN_ENV] == "1"+ assert runner._NVIDIA_BUILD_KEY_FILE_ENV not in environment+ assert kwargs["input"] == secretreturn SimpleNamespace(returncode=0, stdout="", stderr="")monkeypatch.setattr(runner.subprocess, "run", fake_run)@@ -296,4 +335,194 @@ def test_harbor_subprocess_receives_only_file_backed_nvidia_sentinel(monkeypatch)assert (ok, detail) == (True, "")- assert observed_key_files and all(not path.exists() for path in observed_key_files)+ handoff = runner._nvidia_build_key_handoff(+ {"SKILL_EVAL_LLM_PROVIDER": "nv_build", "NVIDIA_API_KEY": secret},+ env_mode="docker",+ )+ assert secret not in repr(handoff)++ other_secret = "non-nvidia-provider-secret-value-for-test"+ other_handoff = runner._nvidia_build_key_handoff(+ {"SKILL_EVAL_LLM_PROVIDER": "openai", "OPENAI_API_KEY": other_secret},+ env_mode="docker",+ )+ assert other_handoff.subprocess_env["OPENAI_API_KEY"] == other_secret+ assert other_secret not in repr(other_handoff)+++def test_harbor_subprocess_redacts_stdin_key_from_early_failure(monkeypatch, tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor import runner++ secret = "nvidia-real-secret-value-for-test"++ def fake_run(command, **kwargs):+ assert kwargs["input"] == secret+ assert secret not in kwargs["env"].values()+ return SimpleNamespace(returncode=1, stdout="", stderr=f"provider rejected {secret}")++ monkeypatch.setattr(runner.subprocess, "run", fake_run)++ ok, detail = runner._run_harbor(+ dataset=tmp_path / "dataset",+ agent="opencode",+ job_name="secure-build",+ env_mode="docker",+ model="nvidia/nvidia/nemotron-3-nano-30b-a3b",+ jobs_dir=tmp_path / "jobs",+ run_env={"SKILL_EVAL_LLM_PROVIDER": "nv_build", "NVIDIA_API_KEY": secret},+ n_attempts=1,+ n_concurrent=1,+ timeout_multiplier=1.0,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ )++ assert ok is False+ assert secret not in detail+ assert "redacted" in detail.lower()+++def test_stdin_handoff_is_shared_by_docker_environment_and_nvidia_agent(monkeypatch) -> None:+ from skillevaluator.tier3.harbor import local_agents, runner, secure_docker_environment, sensitive_stdin++ secret = "nvidia-real-secret-value-for-test"+ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", io.StringIO(secret))+ monkeypatch.setenv("NVIDIA_API_KEY", runner._NVIDIA_BUILD_STDIN_SENTINEL)+ monkeypatch.setenv(runner._NVIDIA_BUILD_KEY_STDIN_ENV, "1")++ resolved = secure_docker_environment._host_handoff_environment(+ {"NVIDIA_API_KEY": runner._NVIDIA_BUILD_STDIN_SENTINEL}+ )+ agent_key = local_agents.SkillEvaluatorNvidiaBuildCodex._resolve_bridge_api_key()++ assert resolved["NVIDIA_API_KEY"] == secret+ assert agent_key == secret+ assert sensitive_stdin.sys.stdin.read() == ""+++def test_secure_docker_preflight_consumes_stdin_key_before_docker_child(monkeypatch) -> None:+ from harbor.environments.docker.docker import DockerEnvironment++ from skillevaluator.tier3.harbor import runner, secure_docker_environment, sensitive_stdin++ secret = "nvidia-real-secret-value-for-test"+ observed: list[str] = []+ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", io.StringIO(secret))+ monkeypatch.setenv("NVIDIA_API_KEY", runner._NVIDIA_BUILD_STDIN_SENTINEL)+ monkeypatch.setenv(runner._NVIDIA_BUILD_KEY_STDIN_ENV, "1")++ def docker_preflight(_cls) -> None:+ assert sensitive_stdin._nvidia_build_key_cache.value == secret+ observed.append(secret)+ assert sensitive_stdin.sys.stdin.read() == ""++ monkeypatch.setattr(DockerEnvironment, "preflight", classmethod(docker_preflight))++ secure_docker_environment.SkillEvaluatorSecureDockerEnvironment.preflight()++ assert observed == [secret]+++def test_stdin_handoff_fails_closed_without_marker(monkeypatch) -> None:+ from skillevaluator.tier3.harbor import runner, secure_docker_environment, sensitive_stdin++ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", io.StringIO("must-not-be-read"))+ monkeypatch.delenv(runner._NVIDIA_BUILD_KEY_STDIN_ENV, raising=False)++ with pytest.raises(RuntimeError, match="SKILLEVALUATOR_NVIDIA_API_KEY_STDIN"):+ secure_docker_environment._host_handoff_environment({"NVIDIA_API_KEY": runner._NVIDIA_BUILD_STDIN_SENTINEL})++ assert sensitive_stdin.sys.stdin.read() == "must-not-be-read"+++def test_non_handoff_environment_does_not_consume_stdin(monkeypatch) -> None:+ from skillevaluator.tier3.harbor import secure_docker_environment, sensitive_stdin++ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", io.StringIO("unrelated-input"))++ resolved = secure_docker_environment._host_handoff_environment({"NVIDIA_API_KEY": "ordinary-key"})++ assert resolved == {"NVIDIA_API_KEY": "ordinary-key"}+ assert sensitive_stdin.sys.stdin.read() == "unrelated-input"+++def test_stdin_handoff_is_read_once_under_concurrency(monkeypatch) -> None:+ from skillevaluator.tier3.harbor import runner, sensitive_stdin++ class CountingInput(io.StringIO):+ reads = 0++ def read(self, *args, **kwargs):+ self.reads += 1+ return super().read(*args, **kwargs)++ secret = "nvidia-real-secret-value-for-test"+ source = CountingInput(secret)+ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", source)+ monkeypatch.setenv(runner._NVIDIA_BUILD_KEY_STDIN_ENV, "1")++ with ThreadPoolExecutor(max_workers=8) as executor:+ results = list(executor.map(lambda _index: sensitive_stdin.read_nvidia_build_key_from_stdin(), range(32)))++ assert results == [secret] * 32+ assert source.reads == 1+++def test_real_child_process_receives_nvidia_key_only_through_stdin() -> None:+ from skillevaluator.tier3.harbor import runner++ secret = "nvidia-real-secret-value-for-test"+ expected_digest = hashlib.sha256(secret.encode("utf-8")).hexdigest()+ child = (+ "import hashlib; "+ "from skillevaluator.tier3.harbor.sensitive_stdin import read_nvidia_build_key_from_stdin; "+ "print(hashlib.sha256(read_nvidia_build_key_from_stdin().encode('utf-8')).hexdigest())"+ )+ environment = dict(os.environ)+ environment["NVIDIA_API_KEY"] = runner._NVIDIA_BUILD_STDIN_SENTINEL+ environment[runner._NVIDIA_BUILD_KEY_STDIN_ENV] = "1"+ environment.pop(runner._NVIDIA_BUILD_KEY_FILE_ENV, None)++ completed = subprocess.run(+ [sys.executable, "-c", child],+ input=secret,+ text=True,+ capture_output=True,+ env=environment,+ check=True,+ )++ assert completed.stdout.strip() == expected_digest+ assert completed.stderr == ""+ assert secret not in child+ assert secret not in environment.values()+ assert secret not in completed.stdout+++def test_empty_stdin_handoff_fails_before_docker_preflight(monkeypatch) -> None:+ from harbor.environments.docker.docker import DockerEnvironment++ from skillevaluator.tier3.harbor import runner, secure_docker_environment, sensitive_stdin++ docker_preflight_called = False+ monkeypatch.setattr(sensitive_stdin._nvidia_build_key_cache, "value", sensitive_stdin._UNSET)+ monkeypatch.setattr(sensitive_stdin.sys, "stdin", io.StringIO(""))+ monkeypatch.setenv("NVIDIA_API_KEY", runner._NVIDIA_BUILD_STDIN_SENTINEL)+ monkeypatch.setenv(runner._NVIDIA_BUILD_KEY_STDIN_ENV, "1")++ def docker_preflight(_cls) -> None:+ nonlocal docker_preflight_called+ docker_preflight_called = True++ monkeypatch.setattr(DockerEnvironment, "preflight", classmethod(docker_preflight))++ with pytest.raises(RuntimeError, match="stdin handoff is empty"):+ secure_docker_environment.SkillEvaluatorSecureDockerEnvironment.preflight()++ assert docker_preflight_called is Falsediff --git a/tests/test_tier3_config_key_parity.py b/tests/test_tier3_config_key_parity.pyindex dce96580..b243fcfc 100644--- a/tests/test_tier3_config_key_parity.py+++ b/tests/test_tier3_config_key_parity.py@@ -79,6 +79,16 @@ def _run_engine(monkeypatch.setattr(runner, "_run_agent_pair", pair)monkeypatch.setattr(runner, "collect_harbor_results", collect)monkeypatch.setattr(runner, "render_agent_eval_html_report", lambda *_args, **_kwargs: tmp_path / "report.html")+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: runtime_preflight.ModelProbeResult(+ True,+ selected_provider.provider,+ selected_provider.model,+ f"model {selected_provider.model} is available",+ ),+ )agents = engine_kwargs.pop("agents", ["opencode"])result = runner.run_harbor_eval(skill,diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex 1de6e7dc..a2734761 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -599,9 +599,12 @@ def _stub_runner(html_report=None,environment_check=None,credential_check=None,+ model_probe=None,task_emitter=None,skill_name: str = "demo-skill",+ provider_name: str = "openai",provider_model: str = "gpt-5",+ provider_base_url: str | None = None,):from skillevaluator.tier3.harbor import runner@@ -609,11 +612,14 @@ def _stub_runner((skill / "evals").mkdir(parents=True)evals_file = skill / "evals" / "evals.json"evals_file.write_text("{}", encoding="utf-8")+ resolved_base_url = provider_base_url+ if resolved_base_url is None and provider_name == "openai":+ resolved_base_url = "https://api.openai.com/v1"provider = SimpleNamespace(- provider="openai",+ provider=provider_name,model=provider_model,api_key="exact-provider-secret",- base_url=None,+ base_url=resolved_base_url,)def emit_tasks(_skill, output, **_kwargs):@@ -658,6 +664,22 @@ def _stub_runner(monkeypatch.setattr(runner, "_run_agent_pair", run_agent or (lambda **_kwargs: []))from skillevaluator.tier3.harbor import runtime_preflight+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ model_probe+ or (+ lambda selected_provider: SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )+ ),+ )+monkeypatch.setattr(runtime_preflight,"run_agent_runtime_preflight",@@ -674,6 +696,737 @@ def _stub_runner(return runner, skill+def _configure_native_task_source(+ monkeypatch: pytest.MonkeyPatch,+ runner,+ skill: Path,+ *,+ grading_mode: str = "default",+) -> None:+ native_task = skill / "evals" / "harbor" / "case-1"+ native_task.mkdir(parents=True)+ (native_task / "instruction.md").write_text("Run the native case.\n", encoding="utf-8")+ (native_task / "task.toml").write_text(+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-1"\n\n'+ '[metadata]\nentry_id = "case-1"\n\n[verifier.env]\n'+ 'LLM_JUDGE_MODEL = "authored-native-judge"\n',+ encoding="utf-8",+ )+ (skill / "evals" / "config.yml").write_text(+ f"schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: {grading_mode}\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: (+ {+ "harbor": {"task_source": "native_harbor"},+ "grading": {"mode": grading_mode},+ },+ None,+ ),+ )++ def emit_native(_skill, output: Path, **_kwargs):+ output.mkdir(parents=True, exist_ok=True)+ return [output / "case-1"]++ monkeypatch.setattr(runner, "stage_native_harbor_tasks", emit_native)++[email protected]("agent_runtime_preflight", [True, False])+def test_credential_validation_401_stops_before_image_and_task_preparation(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ agent_runtime_preflight: bool,+) -> None:+ secret = "exact-provider-secret"+ probe_calls: list[Any] = []+ image_calls: list[Path] = []+ task_calls: list[Path] = []++ def reject_credential(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=False,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model catalog returned HTTP 401; rejected {secret}",+ failure_kind="authentication",+ http_status=401,+ )++ def build_image(skill_path: Path, *_args, **_kwargs) -> str:+ image_calls.append(skill_path)+ return "skillevaluator-test-image"++ def emit_tasks(_skill, output: Path, **_kwargs):+ task_calls.append(output)+ output.mkdir(parents=True, exist_ok=True)+ return [output / "case-1"]++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=reject_credential,+ task_emitter=emit_tasks,+ )+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: (+ {+ "harbor": {+ "task_source": "evals_json",+ "base_image_mode": "reuse",+ "n_attempts": 1,+ "n_concurrent": 1,+ "max_agents": 1,+ }+ },+ None,+ ),+ )+ monkeypatch.setattr(runner, "build_eval_base_image", build_image)+ reporter = _RecordingReporter()++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=agent_runtime_preflight,+ progress_reporter=reporter,+ )++ assert probe_calls and probe_calls[0].provider == "openai"+ assert result.get("error")+ assert "HTTP 401" in json.dumps(result)+ assert image_calls == []+ assert task_calls == []+ transitions = [(event.stage, event.state) for event in reporter.events]+ assert ("credential-validation", "failed") in transitions+ assert ("credential-validation", "complete") not in transitions+ rendered = json.dumps(result) + json.dumps([(event.stage, event.state, event.detail) for event in reporter.events])+ assert secret not in rendered+++ ("provider_name", "provider_base_url", "failure_kind", "http_status", "detail"),+ [+ ("openai", "https://api.openai.com/v1", "unavailable", None, "model catalog request timed out"),+ ("openai", "https://api.openai.com/v1", "authorization", 403, "model catalog returned HTTP 403"),+ ("openai", "https://api.openai.com/v1", None, None, "model requested-model is not listed"),+ (+ "openai-compatible",+ "https://gateway.example/v1",+ "authentication",+ 401,+ "model catalog returned HTTP 401",+ ),+ ("openai", "https://gateway.example/v1", "authentication", 401, "model catalog returned HTTP 401"),+ ("anthropic", "https://gateway.example/v1", "authentication", 401, "model catalog returned HTTP 401"),+ ],+)[email protected]("agent_runtime_preflight", [True, False])+def test_inconclusive_credential_probe_degrades_and_continues(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ provider_name: str,+ provider_base_url: str,+ failure_kind: str | None,+ http_status: int | None,+ detail: str,+ agent_runtime_preflight: bool,+) -> None:+ probe_calls: list[Any] = []+ task_calls: list[Path] = []++ def inconclusive(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=False,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=detail,+ failure_kind=failure_kind,+ http_status=http_status,+ )++ def emit_tasks(_skill, output: Path, **_kwargs):+ task_calls.append(output)+ output.mkdir(parents=True, exist_ok=True)+ return [output / "case-1"]++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=inconclusive,+ task_emitter=emit_tasks,+ provider_name=provider_name,+ provider_model="requested-model",+ provider_base_url=provider_base_url,+ )+ reporter = _RecordingReporter()++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=agent_runtime_preflight,+ progress_reporter=reporter,+ )++ assert "error" not in result+ assert len(probe_calls) == (2 if provider_name == "anthropic" else 1)+ assert any(call.provider == provider_name for call in probe_calls)+ assert task_calls+ transitions = [(event.stage, event.state) for event in reporter.events]+ assert ("credential-validation", "degraded") in transitions+ assert ("credential-validation", "complete") not in transitions+ assert transitions[-1] == ("run-finished", "complete")+ validation = result["run_config"]["credential_validation"]+ assert validation["status"] == "degraded"+ assert {target["status"] for target in validation["targets"]} == {"degraded"}+ persisted = json.loads(Path(result["result_path"]).read_text(encoding="utf-8"))+ assert persisted["run_config"]["credential_validation"] == validation+++def test_credential_validation_probes_an_identical_agent_route_once(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=succeed)++ result = runner.run_harbor_eval(+ skill,+ ["codex", "opencode"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert len(probe_calls) == 1+ assert probe_calls[0].provider == "openai"+++def test_credential_validation_probes_each_distinct_agent_route(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-runtime-secret")++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=succeed)++ result = runner.run_harbor_eval(+ skill,+ ["codex", "claude-code"],+ agent_models={"claude-code": "anthropic/claude-test"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert {probe.provider for probe in probe_calls} == {"openai", "anthropic"}+++def test_credential_validation_includes_distinct_standard_grading_route(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-runtime-secret")++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=succeed)+ monkeypatch.setattr(+ runner,+ "_provider_environment",+ lambda _provider: {+ "OPENAI_API_KEY": "exact-provider-secret",+ "LLM_JUDGE_MODEL": "judge-gpt",+ },+ )++ result = runner.run_harbor_eval(+ skill,+ ["claude-code"],+ agent_models={"claude-code": "anthropic/claude-test"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert {(probe.provider, probe.model) for probe in probe_calls} == {+ ("anthropic", "claude-test"),+ ("openai", "judge-gpt"),+ }+++def test_missing_native_task_source_stops_before_credential_probes(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []++ def record_probe(selected_provider):+ probe_calls.append(selected_provider)+ raise AssertionError("credential probes must not run without the selected task source")++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=record_probe)+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: ({"harbor": {"task_source": "native_harbor"}}, None),+ )+ reporter = _RecordingReporter()++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ progress_reporter=reporter,+ )++ assert result == {"error": ["No native Harbor task source found at evals/harbor."]}+ assert probe_calls == []+ transitions = [(event.stage, event.state) for event in reporter.events]+ assert ("environment-preflight", "complete") in transitions+ assert ("with-skill-tasks", "failed") in transitions+ assert not any(stage == "credential-validation" for stage, _state in transitions)++[email protected]("grading_mode", ["default", "default_plus_custom"])+def test_native_standard_grading_without_host_override_marks_judge_probe_inconclusive(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ grading_mode: str,+) -> None:+ probe_calls: list[Any] = []+ provider_fallback = "unused-provider-fallback"++ def probe(selected_provider):+ probe_calls.append(selected_provider)+ if selected_provider.model == provider_fallback:+ return SimpleNamespace(+ ok=False,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail="model catalog returned HTTP 401",+ failure_kind="authentication",+ http_status=401,+ )+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=probe,+ provider_model=provider_fallback,+ )+ _configure_native_task_source(monkeypatch, runner, skill, grading_mode=grading_mode)+ reporter = _RecordingReporter()++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ agent_models={"codex": "actual-agent-model"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ progress_reporter=reporter,+ )++ assert "error" not in result+ assert [(call.provider, call.model) for call in probe_calls] == [("openai", "actual-agent-model")]+ assert ("credential-validation", "degraded") in [(event.stage, event.state) for event in reporter.events]+ assert result["run_config"]["task_source"] == "native_harbor"+ assert result["run_config"]["judge"]["catalog_verification"] == "inconclusive"+ assert result["run_config"]["judge"]["effective_model_source"] == "native_harbor_runtime"+ assert result["run_config"]["credential_validation"]["status"] == "degraded"+ judge_target = next(+ target+ for target in result["run_config"]["credential_validation"]["targets"]+ if target["labels"] == ["standard grader"]+ )+ assert judge_target == {+ "labels": ["standard grader"],+ "provider": "openai",+ "model": None,+ "fallback_model": provider_fallback,+ "status": "inconclusive",+ "detail": (+ "native Harbor resolves the effective judge model at runtime; "+ "task or step verifier env may supersede the configured fallback"+ ),+ }+++def test_auto_with_both_task_sources_uses_evals_json_and_probes_the_standard_judge(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=succeed,+ provider_model="standard-judge-model",+ )+ native_task = skill / "evals" / "harbor" / "case-1"+ native_task.mkdir(parents=True)+ (native_task / "instruction.md").write_text("Unused native case.\n", encoding="utf-8")+ (native_task / "task.toml").write_text(+ 'schema_version = "1.3"\n[task]\nname = "nvidia/case-1"\n[metadata]\nentry_id = "case-1"\n',+ encoding="utf-8",+ )+ (skill / "evals" / "config.yml").write_text(+ "schema_version: 1\nharbor:\n task_source: auto\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: ({"harbor": {"task_source": "auto"}}, None),+ )++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ agent_models={"codex": "actual-agent-model"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert result["run_config"]["task_source"] == "evals_json"+ assert {(call.provider, call.model) for call in probe_calls} == {+ ("openai", "actual-agent-model"),+ ("openai", "standard-judge-model"),+ }+ assert result["run_config"]["judge"]["catalog_verification"] == "verified"+++def test_auto_with_native_only_custom_grading_skips_the_standard_judge_probe(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=succeed)+ (skill / "evals" / "evals.json").unlink()+ native_task = skill / "evals" / "harbor" / "case-1"+ native_task.mkdir(parents=True)+ (native_task / "instruction.md").write_text("Run the native case.\n", encoding="utf-8")+ (native_task / "task.toml").write_text(+ 'schema_version = "1.3"\n[task]\nname = "nvidia/case-1"\n[metadata]\nentry_id = "case-1"\n',+ encoding="utf-8",+ )+ (skill / "evals" / "config.yml").write_text(+ "schema_version: 1\nharbor:\n task_source: auto\ngrading:\n mode: custom_only\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ runner,+ "load_evals_config",+ lambda _path: (+ {"harbor": {"task_source": "auto"}, "grading": {"mode": "custom_only"}},+ None,+ ),+ )+ monkeypatch.setattr(runner, "find_evals_file", lambda _path: None)++ def emit_native(_skill, output: Path, **_kwargs):+ output.mkdir(parents=True, exist_ok=True)+ return [output / "case-1"]++ monkeypatch.setattr(runner, "stage_native_harbor_tasks", emit_native)++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert result["run_config"]["task_source"] == "native_harbor"+ assert result["run_config"]["judge"] == {"enabled": False}+ assert len(probe_calls) == 1++[email protected]("grading_mode", ["default", "default_plus_custom"])[email protected]("override_name", ["LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"])+def test_native_standard_grading_host_override_is_the_exact_judge_probe(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ grading_mode: str,+ override_name: str,+) -> None:+ probe_calls: list[Any] = []++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=succeed,+ provider_model="provider-fallback",+ )+ _configure_native_task_source(monkeypatch, runner, skill, grading_mode=grading_mode)+ monkeypatch.setattr(+ runner,+ "_provider_environment",+ lambda _provider: {+ "OPENAI_API_KEY": "exact-provider-secret",+ override_name: "host-judge-model",+ },+ )++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ agent_models={"codex": "actual-agent-model"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert {(call.provider, call.model) for call in probe_calls} == {+ ("openai", "actual-agent-model"),+ ("openai", "host-judge-model"),+ }+ assert result["run_config"]["judge"] == {+ "enabled": True,+ "provider": "openai",+ "model": "host-judge-model",+ "source": override_name,+ "override_applied": True,+ "catalog_verification": "verified",+ }+++def test_native_inconclusive_judge_probe_does_not_skip_the_same_route_used_by_an_agent(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []+ staged: list[Path] = []++ def reject_agent_credential(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=False,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail="model catalog returned HTTP 401",+ failure_kind="authentication",+ http_status=401,+ )++ def emit_native(_skill, output: Path, **_kwargs):+ staged.append(output)+ return []++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=reject_agent_credential,+ provider_model="shared-route-model",+ )+ _configure_native_task_source(monkeypatch, runner, skill)+ monkeypatch.setattr(runner, "stage_native_harbor_tasks", emit_native)++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ agent_models={"codex": "shared-route-model"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert result.get("error")+ assert [(call.provider, call.model) for call in probe_calls] == [("openai", "shared-route-model")]+ assert staged == []+++def test_distinct_standard_grading_probe_failure_is_redacted_and_stops_staging(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ evaluator_secret = "evaluator-only-provider-secret"+ task_calls: list[Path] = []+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-runtime-secret")++ def probe(selected_provider):+ if selected_provider.provider == "openai":+ return SimpleNamespace(+ ok=False,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model catalog returned HTTP 401; rejected {evaluator_secret}",+ failure_kind="authentication",+ http_status=401,+ )+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ def emit_tasks(_skill, output: Path, **_kwargs):+ task_calls.append(output)+ return []++ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ model_probe=probe,+ task_emitter=emit_tasks,+ )+ monkeypatch.setattr(+ runner,+ "_provider_environment",+ lambda _provider: {"OPENAI_API_KEY": evaluator_secret},+ )+ monkeypatch.setattr(+ runner,+ "resolve_llm_provider",+ lambda: SimpleNamespace(+ provider="openai",+ model="gpt-5",+ api_key=evaluator_secret,+ base_url="https://api.openai.com/v1",+ ),+ )+ reporter = _RecordingReporter()++ result = runner.run_harbor_eval(+ skill,+ ["claude-code"],+ agent_models={"claude-code": "anthropic/claude-test"},+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ progress_reporter=reporter,+ )++ rendered = json.dumps(result) + json.dumps([event.detail for event in reporter.events])+ assert result.get("error")+ assert "HTTP 401" in rendered+ assert evaluator_secret not in rendered+ assert task_calls == []+++def test_custom_only_credential_validation_skips_unused_evaluator_route(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ probe_calls: list[Any] = []+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-runtime-secret")++ def succeed(selected_provider):+ probe_calls.append(selected_provider)+ return SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ )++ runner, skill = _stub_runner(monkeypatch, tmp_path, model_probe=succeed)++ result = runner.run_harbor_eval(+ skill,+ ["claude-code"],+ agent_models={"claude-code": "anthropic/claude-test"},+ grading_mode="custom_only",+ output_dir=tmp_path / "results",+ agent_runtime_preflight=False,+ )++ assert "error" not in result+ assert [(probe.provider, probe.model) for probe in probe_calls] == [("anthropic", "claude-test")]++def test_default_run_cleans_transient_harbor_artifacts(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -1073,7 +1826,13 @@ def test_default_task_staging_failure_cleans_transient_artifacts(def fail_staging(*_args, **_kwargs):raise ValueError("invalid task")- runner, skill = _stub_runner(monkeypatch, tmp_path, task_emitter=fail_staging)+ runner, skill = _stub_runner(+ monkeypatch,+ tmp_path,+ task_emitter=fail_staging,+ provider_name="openai-compatible",+ provider_base_url="https://gateway.example/v1",+ )result = runner.run_harbor_eval(skill, ["codex"], output_dir=tmp_path / "results")@@ -1082,6 +1841,20 @@ def test_default_task_staging_failure_cleans_transient_artifacts(assert not (run_dir / "_harbor-jobs").exists()assert not (run_dir / "_harbor-tasks").exists()assert result["harbor_jobs_retained"] is False+ assert result["run_config"]["credential_validation"]["status"] == "degraded"+ assert result["run_config"]["credential_validation"]["targets"] == [+ {+ "labels": ["codex", "standard grader"],+ "provider": "openai-compatible",+ "model": "gpt-5",+ "status": "degraded",+ "detail": "model catalog access does not verify runtime credentials for this endpoint",+ }+ ]+ persisted = json.loads(Path(result["result_path"]).read_text(encoding="utf-8"))+ assert persisted["run_config"] == result["run_config"]+ run_config_path = run_dir / "run_config.json"+ assert json.loads(run_config_path.read_text(encoding="utf-8")) == result["run_config"]@pytest.mark.parametrize("failure_arm", ["with-skill", "baseline"])@@ -1244,7 +2017,12 @@ def test_runner_emits_truthful_stages_plan_and_per_agent_state(monkeypatch.setattr(runner,"resolve_llm_provider",- lambda: SimpleNamespace(provider="openai", model="gpt-5", api_key="sk-test-secret", base_url=None),+ lambda: SimpleNamespace(+ provider="openai",+ model="gpt-5",+ api_key="sk-test-secret",+ base_url="https://api.openai.com/v1",+ ),)monkeypatch.setattr(runner,@@ -1282,6 +2060,18 @@ def test_runner_emits_truthful_stages_plan_and_per_agent_state(monkeypatch.setattr(runner, "_harbor_subprocess_environment", lambda **_kwargs: {})from skillevaluator.tier3.harbor import runtime_preflight+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected_provider: SimpleNamespace(+ ok=True,+ provider=selected_provider.provider,+ model=selected_provider.model,+ detail=f"model {selected_provider.model} is available",+ failure_kind=None,+ http_status=None,+ ),+ )monkeypatch.setattr(runtime_preflight,"run_agent_runtime_preflight",diff --git a/tests/test_tier3_public_runtime.py b/tests/test_tier3_public_runtime.pyindex f20e88b2..05e9fbab 100644--- a/tests/test_tier3_public_runtime.py+++ b/tests/test_tier3_public_runtime.py@@ -20,6 +20,7 @@ import pytestfrom click.testing import CliRunnerfrom skillevaluator.cli import cli+from skillevaluator.model_catalog import ModelCatalogFailureKindfrom skillevaluator.provider_config import ProviderConfig, resolve_llm_providerfrom skillevaluator.tier3 import commands as tier3_commandsfrom skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config@@ -484,7 +485,7 @@ def test_doctor_build_codex_ignores_native_pair_and_accepts_build_model(monkeypaassert "pass" in result.output-def test_doctor_verify_models_probes_the_resolved_agent_provider(monkeypatch) -> None:+def test_doctor_verify_models_warns_when_catalog_success_does_not_verify_credentials(monkeypatch) -> None:from skillevaluator.tier3.harbor import runtime_preflightprovider = ProviderConfig(@@ -512,12 +513,106 @@ def test_doctor_verify_models_probes_the_resolved_agent_provider(monkeypatch) ->)assert result.exit_code == 0+ assert "warn" in result.output+ assert "does not verify runtime credentials" in " ".join(result.output.split()).lower()probe.assert_called_once()probed_provider = probe.call_args.args[0]assert probed_provider.provider == "nv_build"assert probed_provider.model == "meta/llama-3.1-8b-instruct"+ ("failure_kind", "http_status", "expected_status", "expected_exit_code"),+ [+ (ModelCatalogFailureKind.AUTHORIZATION, 403, "warn", 0),+ (ModelCatalogFailureKind.AUTHENTICATION, 401, "fail", 1),+ ],+)+def test_doctor_verify_models_uses_probe_disposition_for_catalog_failures(+ monkeypatch,+ failure_kind: ModelCatalogFailureKind,+ http_status: int,+ expected_status: str,+ expected_exit_code: int,+) -> None:+ from skillevaluator.tier3.harbor import runtime_preflight++ provider = ProviderConfig(+ provider="openai",+ model="gpt-test",+ api_key="openai-key",+ base_url="https://api.openai.com/v1",+ litellm_model="openai/gpt-test",+ )+ probe = Mock(+ return_value=ModelProbeResult(+ False,+ "openai",+ "gpt-test",+ f"model catalog returned HTTP {http_status}",+ failure_kind=failure_kind,+ http_status=http_status,+ )+ )+ monkeypatch.setattr(tier3_commands, "resolve_llm_provider", lambda: provider)+ monkeypatch.setattr(tier3_commands, "_check_prerequisites", lambda **_kwargs: [])+ monkeypatch.setattr(runtime_preflight, "probe_model", probe)++ result = CliRunner().invoke(+ cli,+ ["doctor", "--agents", "codex", "--env-mode", "docker", "--verify-models"],+ )++ assert result.exit_code == expected_exit_code+ assert expected_status in result.output+++ ("provider_name", "base_url", "agent"),+ [+ ("openai", "https://gateway.example/v1", "codex"),+ ("anthropic", "https://gateway.example/v1", "claude-code"),+ ],+)+def test_doctor_verify_models_warns_for_custom_endpoint_catalog_authentication_failure(+ monkeypatch: pytest.MonkeyPatch,+ provider_name: str,+ base_url: str,+ agent: str,+) -> None:+ from skillevaluator.tier3.harbor import runtime_preflight++ provider = ProviderConfig(+ provider=provider_name,+ model="model-test",+ api_key="provider-key",+ base_url=base_url,+ litellm_model=f"{provider_name}/model-test",+ )+ probe = Mock(+ return_value=ModelProbeResult(+ False,+ provider_name,+ "model-test",+ "model catalog returned HTTP 401",+ failure_kind=ModelCatalogFailureKind.AUTHENTICATION,+ http_status=401,+ )+ )+ monkeypatch.setattr(tier3_commands, "resolve_llm_provider", lambda: provider)+ monkeypatch.setattr(tier3_commands, "_check_prerequisites", lambda **_kwargs: [])+ monkeypatch.setattr(runtime_preflight, "probe_model", probe)++ result = CliRunner().invoke(+ cli,+ ["doctor", "--agents", agent, "--env-mode", "docker", "--verify-models"],+ )++ assert result.exit_code == 0+ assert "warn" in result.output+ assert "HTTP 401" in result.output++def test_doctor_reports_missing_independent_cross_provider_credential(monkeypatch) -> None:provider = ProviderConfig(provider="openai",