Skip to content

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.

feat(tier3): add opt-in judge fallback and strict retry policies (#343)

Narendran Raghavan8a851c6b90a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b05fb58..256d86e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,17 @@ All notable changes to SkillEvaluator are documented in this file.
gains `chat(messages)` for multi-turn requests with the same retries and typed
errors as `completions()`.
+- Opt-in `LLM_JUDGE_FALLBACK_POLICY` and `LLM_JUDGE_RETRY_POLICY` for the Tier 3
+ standard judges. `LLM_JUDGE_FALLBACK_POLICY=replace` lets only the judge
+ model and the `LLM_JUDGE_FALLBACK_MODELS` entries answer, without the
+ built-in `claude-opus-4-8` refusal fallback. `LLM_JUDGE_RETRY_POLICY=strict`
+ tries at most three models with two requests each within the judge's time
+ budget, moves on only when a model is unavailable, ends the judge on a
+ refusal or a quota, budget, safety, or security error, and scores only a
+ first reply that is exactly one JSON object. Any other value stops a run
+ with standard grading before trials start. The defaults, `append` and
+ `legacy`, keep the current behavior.
+
- Allow hosted CI reports and PR comments from scans called through explicitly
approved reusable workflow wrappers. Direct callers retain the existing setup;
signed evaluator identity and exact consumer workflow approvals remain required.
diff --git a/docs/custom-graders.mdx b/docs/custom-graders.mdx
index 4f114278..403e8ffb 100644
--- a/docs/custom-graders.mdx
+++ b/docs/custom-graders.mdx
@@ -239,7 +239,8 @@ The staged task also has explicit compatibility boundaries:
environment controls are also rejected. An exact `${NAME}` assignment for a
provider or judge control is accepted in task/step `verifier.env` only when
the operator explicitly staged that same name; unrelated verifier variables
- remain available. An operator-set `LLM_JUDGE_FALLBACK_MODELS` value is
+ remain available. Operator-set `LLM_JUDGE_FALLBACK_MODELS`,
+ `LLM_JUDGE_FALLBACK_POLICY`, and `LLM_JUDGE_RETRY_POLICY` values are
forwarded only to the standard verifier job, never to the agent environment
or a `custom_only` run. SkillEvaluator's Python verifier runs in isolated mode
from a replaced `tests/skill_evaluator/` payload so authored helper modules
diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdx
index e34d039d..12eaa55a 100644
--- a/docs/environment-variables.mdx
+++ b/docs/environment-variables.mdx
@@ -166,6 +166,8 @@ execution environments are covered in
| `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, `override_applied`, reasoning effort, 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. |
| `LLM_JUDGE_FALLBACK_MODELS` | unset | Comma-separated fallback models for the Tier 3 standard judges in the Harbor verifier. When the provider rejects the judge model as not found, invalid, or not accessible to the key, the verifier tries each fallback in order with the same provider. Fallback applies to the `openai`, `nv_build`, and `openai-compatible` providers. A safety refusal or an empty reply from the judge model also moves to the next fallback, on every provider. The value is forwarded only to standard verifier jobs, never to the agent environment or `custom_only` runs. |
+| `LLM_JUDGE_FALLBACK_POLICY` | `append` | Opt-in limit on which models may answer a Tier 3 standard judge. `append` keeps the built-in refusal fallback, which sends a refused Claude 5.5 or later judge to `claude-opus-4-8`. `replace` turns it off, so only the judge model and the `LLM_JUDGE_FALLBACK_MODELS` entries answer. Values are case-insensitive; any other value stops a run with standard grading before trials start, and the verifier fails every standard judge on it before a request is sent. Forwarded like `LLM_JUDGE_FALLBACK_MODELS`, and recorded as `judge.fallback_policy` in `run_config.json` when set. See [Judge fallback and retry policies](tier3-live-evaluation.mdx#judge-fallback-and-retry-policies). |
+| `LLM_JUDGE_RETRY_POLICY` | `legacy` | Opt-in retry policy for the Tier 3 standard judges. `strict` tries at most three models (the judge model, then the first two `LLM_JUDGE_FALLBACK_MODELS` entries) with at most two requests each within the per-judge time budget, moves on only when a model is unavailable, ends the judge on a refusal or a quota, budget, safety, or security error, and scores only a first completed reply that is exactly one JSON object. `legacy` keeps the standard retries, fallbacks, format retry, and salvage. Values are case-insensitive; any other value stops a run with standard grading before trials start, and the verifier fails every standard judge on it before a request is sent. Forwarded like `LLM_JUDGE_FALLBACK_MODELS`, and recorded as `judge.retry_policy` in `run_config.json` when set. See [Judge fallback and retry policies](tier3-live-evaluation.mdx#judge-fallback-and-retry-policies). |
| `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. |
| `SKILLEVALUATOR_GKE_CLUSTER`, `SKILLEVALUATOR_GKE_REGION`, `SKILLEVALUATOR_GKE_NAMESPACE`, `SKILLEVALUATOR_GKE_REGISTRY_LOCATION`, `SKILLEVALUATOR_GKE_REGISTRY_NAME` | — | Target cluster, region, namespace, and Artifact Registry coordinates for `--env-mode gke` when not supplied via `--ek`. |
| `SKILLEVALUATOR_GKE_ALLOW_WORKLOAD_IDENTITY` | `false` | Opt in (`1`, `true`, `yes`) to single-pod GKE Workload Identity (`CLAUDE_CODE_USE_VERTEX=1` or a GCP-bound Kubernetes ServiceAccount). Restricted to trusted skills because the pod ServiceAccount and GCE/GKE metadata server are shared with evaluated skill commands. |
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index d4551581..99a62d8a 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -819,6 +819,56 @@ is an evaluation infrastructure failure, not a `0.0` score, and the affected
condition publishes no scores; see
[Tier 3 judge failure semantics](environment-variables.mdx#tier-3-judge-failure-semantics).
+### Judge fallback and retry policies
+
+Two opt-in host variables limit which models may answer a standard judge and
+how often it is asked. Both default to the behavior above. They are forwarded
+like `LLM_JUDGE_FALLBACK_MODELS`: only to standard verifier jobs, never to the
+agent environment or `custom_only` runs.
+
+- **`LLM_JUDGE_FALLBACK_POLICY=replace`.** Only the judge model and your
+ `LLM_JUDGE_FALLBACK_MODELS` entries answer. The built-in `claude-opus-4-8`
+ refusal fallback for Claude 5.5 or later judges is not used, on the native
+ Claude API or on Bedrock. The default, `append`, keeps it.
+- **`LLM_JUDGE_RETRY_POLICY=strict`.** Each judge tries at most three models:
+ the judge model, then the first two `LLM_JUDGE_FALLBACK_MODELS` entries. It
+ sends at most two requests to each, and all of them share the judge's time
+ budget.
+ - A request that fails with a retryable HTTP status, a connection error, or
+ Bedrock throttling is retried at most once, then the next model is tried.
+ A model the provider reports as not found, invalid, or not accessible to
+ the key moves on without a retry. That covers the errors
+ `LLM_JUDGE_FALLBACK_MODELS` already falls back on, OpenAI's
+ `model_not_found`, a Claude `not_found_error` that names the model, and
+ Bedrock's `AccessDeniedException`, `ResourceNotFoundException`, and
+ invalid model identifier errors. A `Retry-After` wait above the maximum
+ retry delay moves on without waiting. A wait or request that would pass
+ the judge's deadline ends the judge.
+ - A refusal, a TLS certificate failure, an authentication error, and any
+ other non-retryable HTTP status end the judge. So does a provider error,
+ even on HTTP 429, that says a quota, budget, billing, or credit limit was
+ reached, or that a content filter, safety, or security policy rejected
+ the request. Only the provider's error code, type, and message are read
+ (the first 500 characters of a body that is not JSON), and only whole
+ phrases such as `insufficient_quota`, `budget exceeded`,
+ `credit balance`, or `content_filter` count, so a model id or proxy host
+ name in the error does not. These are not retried or handed to another
+ model, and the built-in refusal fallback is not used either.
+ - The first completed reply is final. It must be exactly one JSON object,
+ with only whitespace around it: no prose, Markdown fences, second object,
+ duplicate key, or `NaN`. An empty, invalid, or truncated reply fails the
+ judge without the format retry or `behavior_check` salvage, and
+ `goal_accuracy` skips the RAGAS scorer, which sends its own requests.
+ - The default, `legacy`, keeps the retries, fallbacks, format retry, and
+ salvage described above.
+
+Values are case-insensitive. Any other value stops a run with standard
+grading at configuration, before any trial starts. If one still reaches the
+verifier, every standard judge fails before a request is sent, so the affected
+conditions publish no scores. When set, `run_config.json` records the values as
+`judge.fallback_policy` and `judge.retry_policy`. A `custom_only` run does not
+read them.
+
## Reading results
In the terminal, a finished run renders **Results by Evaluator** — each
diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py
index 4a234a2e..aab8e5aa 100644
--- a/src/skillevaluator/tier3/harbor/adapter.py
+++ b/src/skillevaluator/tier3/harbor/adapter.py
@@ -219,7 +219,10 @@ _COMPOSE_ALLOWED_BUILD_KEYS = frozenset(
_COMPOSE_ALLOWED_NETWORK_KEYS = frozenset({"attachable", "enable_ipv4", "enable_ipv6", "internal", "labels"})
_COMPOSE_ALLOWED_VOLUME_KEYS = frozenset({"labels"})
_VERIFIER_JUDGE_MODEL_ENV_VARS = frozenset({"LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"})
-_VERIFIER_JUDGE_FALLBACK_ENV_VARS = frozenset({"LLM_JUDGE_FALLBACK_MODELS"})
+# Fallback models and the opt-in fallback and retry policies of the standard judges.
+_VERIFIER_JUDGE_FALLBACK_ENV_VARS = frozenset(
+ {"LLM_JUDGE_FALLBACK_MODELS", "LLM_JUDGE_FALLBACK_POLICY", "LLM_JUDGE_RETRY_POLICY"}
+)
_VERIFIER_JUDGE_CONTROL_ENV_VARS = (
_VERIFIER_JUDGE_MODEL_ENV_VARS | _VERIFIER_JUDGE_FALLBACK_ENV_VARS | {"SKILL_EVAL_JUDGE_CHARACTER_FACTS"}
)
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 3c8c46d1..d8c081f1 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -2927,6 +2927,32 @@ def _gateway_anthropic_agent_credentials(
}
+# Opt-in standard judge policies, read again by the verifier template:
+# host variable -> (run_config.json judge key, accepted values, default first).
+_JUDGE_POLICY_ENV_VARS = {
+ "LLM_JUDGE_FALLBACK_POLICY": ("fallback_policy", ("append", "replace")),
+ "LLM_JUDGE_RETRY_POLICY": ("retry_policy", ("legacy", "strict")),
+}
+
+
+def _judge_policies(environ: Mapping[str, str]) -> tuple[dict[str, str], list[str]]:
+ """Return the set judge policies keyed for ``run_config.json``, and an error for each unknown value.
+
+ Values are case-insensitive and an empty value means unset, as in the verifier.
+ """
+ policies: dict[str, str] = {}
+ errors: list[str] = []
+ for name, (key, choices) in _JUDGE_POLICY_ENV_VARS.items():
+ value = environ.get(name, "").strip().lower()
+ if not value:
+ continue
+ if value in choices:
+ policies[key] = value
+ else:
+ errors.append(f"{name} must be {' or '.join(choices)}")
+ return policies, errors
+
+
def _judge_model_config(
provider: ProviderConfig,
provider_env: Mapping[str, str],
@@ -2954,6 +2980,8 @@ def _judge_model_config(
}
if character_facts := provider_env.get("SKILL_EVAL_JUDGE_CHARACTER_FACTS"):
configuration["character_facts"] = character_facts
+ # Only a known value is recorded; the run stops before trials on any other.
+ configuration.update(_judge_policies(provider_env)[0])
return configuration
@@ -5173,6 +5201,12 @@ def _run_harbor_eval_impl(
if grading_mode not in {"default", "default_plus_custom", "custom_only"}:
reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="invalid grading mode"))
return {"error": ["grading.mode must be default, default_plus_custom, or custom_only"]}
+ # The standard judges would all fail on an unknown policy, after the agent
+ # trials had spent their budget; custom_only runs never forward the policies.
+ judge_policy_errors = _judge_policies(os.environ)[1] if grading_mode != "custom_only" else []
+ if judge_policy_errors:
+ reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="invalid judge policy"))
+ return {"error": judge_policy_errors}
if workspace_mode not in {"isolated", "group"}:
reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="invalid workspace mode"))
return {"error": ["skill_workspace.mode must be isolated or group"]}
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index 811f12de..358f8579 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -848,6 +848,192 @@ def _fallback_models(primary_model):
return _dedupe_models([primary_model, *env_fallbacks])
+def _judge_policy(name, choices):
+ """Read one judge policy variable: unset or empty selects ``choices[0]``; another value raises."""
+ value = os.environ.get(name, "").strip().lower()
+ if not value:
+ return choices[0]
+ if value not in choices:
+ raise ValueError(f"{name} must be {' or '.join(choices)}")
+ return value
+
+
+def _judge_fallback_policy():
+ """Return LLM_JUDGE_FALLBACK_POLICY: ``append`` (default) or ``replace``.
+
+ The only fallback model this verifier adds on its own is the Claude Opus
+ 4.8 refusal fallback for Claude 5.5 or later judges (server-side on the
+ native Claude API, a second request on Bedrock). ``replace`` turns it off,
+ so only the primary judge and the LLM_JUDGE_FALLBACK_MODELS entries answer.
+ """
+ return _judge_policy("LLM_JUDGE_FALLBACK_POLICY", ("append", "replace"))
+
+
+def _judge_retry_policy():
+ """Return LLM_JUDGE_RETRY_POLICY: ``legacy`` (default) or ``strict`` (see _call_strict_judge)."""
+ return _judge_policy("LLM_JUDGE_RETRY_POLICY", ("legacy", "strict"))
+
+
+def _judge_policies_valid():
+ """Return whether LLM_JUDGE_FALLBACK_POLICY and LLM_JUDGE_RETRY_POLICY both hold a known value."""
+ try:
+ _judge_fallback_policy()
+ _judge_retry_policy()
+ except ValueError:
+ return False
+ return True
+
+
+def _strict_judge_replies():
+ """Return whether a completed judge reply must be one whole JSON object and is final.
+
+ True under LLM_JUDGE_RETRY_POLICY=strict. An invalid policy value also
+ counts as strict here; the provider call rejects it before sending anything.
+ """
+ try:
+ return _judge_retry_policy() == "strict"
+ except ValueError:
+ return True
+
+
+def _builtin_refusal_fallback_allowed():
+ """Return whether the built-in Claude Opus 4.8 refusal fallback may answer a refused judge.
+
+ It is off under LLM_JUDGE_FALLBACK_POLICY=replace, and under
+ LLM_JUDGE_RETRY_POLICY=strict, where a refusal ends the judge.
+ """
+ try:
+ return _judge_fallback_policy() == "append" and _judge_retry_policy() == "legacy"
+ except ValueError:
+ return False
+
+
+# LLM_JUDGE_RETRY_POLICY=strict tries at most this many models, the primary
+# first, and sends each at most this many requests. All of them share the
+# judge's wall-time budget (_ACTIVE_JUDGE_DEADLINE).
+_STRICT_JUDGE_MAX_MODELS = 3
+_STRICT_JUDGE_REQUESTS_PER_MODEL = 2
+# Requests left for the model the strict policy is trying; None outside it.
+_STRICT_JUDGE_REQUESTS_LEFT: ContextVar[list[int] | None] = ContextVar("strict_judge_requests_left", default=None)
+# Under the strict policy, a provider error that says one of these is not
+# retried or handed to another model, even when it is an HTTP 429: another
+# model cannot lift a quota, budget, billing or credit limit, and must not be
+# asked to overturn a content-filter, safety or security rejection. Whole
+# phrases only, joined by a space or underscore, so a model id or host name
+# such as ``content-safety-judge`` or ``security-proxy`` is not a reason.
+_STRICT_JUDGE_STOP_PATTERN = re.compile(
+ r"\b(?:"
+ r"insufficient[ _]quota|quota[ _]exceeded|exceeded (?:your|the) (?:current )?quota"
+ r"|budget(?: has been)?[ _](?:exceeded|exhausted)|exceeded (?:your|the) (?:\w+ )?budget"
+ r"|billing[ _](?:hard[ _]limit|not[ _]active)"
+ r"|credit balance|insufficient[ _]credits?|out of credits"
+ r"|content[ _](?:filter|policy|management policy)"
+ r"|safety (?:system|filter|policy|block)"
+ r"|security (?:policy|filter|block|violation)"
+ r"|(?:blocked|flagged|rejected) by (?:the |a |an )?(?:\w+ )?(?:safety|security|content)"
+ r"|policy[ _](?:rejection|violation)"
+ r")\b",
+ re.IGNORECASE,
+)
+_STRICT_JUDGE_ERROR_BODY_CHARS = 500
+
+
+class _StrictJudgeRequestLimitError(RuntimeError):
+ """The strict policy's per-model request limit is used up."""
+
+
+def _spend_strict_judge_request():
+ """Count one request against the strict per-model limit; a no-op outside the strict policy."""
+ left = _STRICT_JUDGE_REQUESTS_LEFT.get()
+ if left is None:
+ return
+ if left[0] <= 0:
+ raise _StrictJudgeRequestLimitError(
+ f"strict judge policy allows {_STRICT_JUDGE_REQUESTS_PER_MODEL} requests per model"
+ )
+ left[0] -= 1
+
+
+def _provider_error_fields(body):
+ """Return the code, type and message of a JSON error body, or None when the body has none."""
+ if len(body) > _STRICT_JUDGE_ERROR_BODY_CHARS * 20:
+ return None
+ try:
+ parsed = json.loads(body)
+ except (RecursionError, ValueError):
+ return None
+ detail = parsed.get("error", parsed) if isinstance(parsed, dict) else None
+ if isinstance(detail, str):
+ return detail or None
+ if not isinstance(detail, dict):
+ return None
+ fields = [detail[key] for key in ("code", "type", "message", "detail") if isinstance(detail.get(key), str)]
+ return " ".join(fields) or None
+
+
+def _strict_judge_error_stops(error):
+ """Return whether a provider error is a quota, budget, billing, safety or security rejection.
+
+ Only what the provider said is read: the code, type and message of a JSON
+ error body, else the start of the body (the excerpt the error detail
+ shows, so a long proxy error page's footer cannot end the judge), or a
+ Bedrock error's code and message. A connection error has no provider
+ verdict, so the words in its reason, such as a proxy host name, never count.
+ """
+ if isinstance(error, urllib.error.HTTPError):
+ body = _http_error_body(error)
+ text = _provider_error_fields(body)
+ if text is None:
+ text = body[:_STRICT_JUDGE_ERROR_BODY_CHARS]
+ elif isinstance(error, (urllib.error.URLError, OSError)):
+ return False
+ else:
+ response = getattr(error, "response", None)
+ info = response.get("Error") if isinstance(response, dict) else None
+ if isinstance(info, dict):
+ text = f"{info.get('Code') or ''} {info.get('Message') or ''}"
+ else:
+ text = str(error)
+ return _STRICT_JUDGE_STOP_PATTERN.search(text) is not None
+
+
+# Besides the model errors every policy hands to LLM_JUDGE_FALLBACK_MODELS
+# (_should_try_fallback), the strict policy reads these as a model the
+# provider does not have or the key cannot use: OpenAI's model_not_found
+# ("The model `x` does not exist ..."), a Claude not_found_error about the
+# model, and Bedrock's access-denied, not-found and invalid-model errors.
+_STRICT_MODEL_UNAVAILABLE_PATTERN = re.compile(
+ r"\bmodel_not_found\b|\bnot_found_error model:|\bthe model\b.{0,200}?\bdoes not exist\b", re.IGNORECASE
+)
+_STRICT_BEDROCK_MODEL_UNAVAILABLE_CODES = frozenset({"AccessDeniedException", "ResourceNotFoundException"})
+
+
+def _strict_model_unavailable(error):
+ """Return whether a failed strict judge request says the model is missing or not open to the key."""
+ if isinstance(error, urllib.error.HTTPError):
+ body = _http_error_body(error)
+ text = _provider_error_fields(body)
+ if text is None:
+ text = body[:_STRICT_JUDGE_ERROR_BODY_CHARS]
+ return _STRICT_MODEL_UNAVAILABLE_PATTERN.search(text) is not None
+ response = getattr(error, "response", None)
+ info = response.get("Error") if isinstance(response, dict) else None
+ if not isinstance(info, dict):
+ return False
+ code = str(info.get("Code") or "")
+ return code in _STRICT_BEDROCK_MODEL_UNAVAILABLE_CODES or (
+ code == "ValidationException" and "model identifier" in str(info.get("Message") or "").lower()
+ )
+
+
+def _strict_judge_retry_allowed(error):
+ """Return whether the strict policy lets the transport retry *error* on the same model."""
+ left = _STRICT_JUDGE_REQUESTS_LEFT.get()
+ if left is None:
+ return True
+ return left[0] > 0 and not _strict_judge_error_stops(error)
+
+
def _resolve_url(provider):
if provider == "nv_build":
url = os.environ.get("SKILL_EVAL_LLM_BASE_URL") or NVIDIA_BUILD_CHAT_URL
@@ -934,11 +1120,22 @@ def _sanitize_error_value(value, extra_secret_values=()):
return sanitize(value)
-def _format_http_error_with_fallback(error):
+def _http_error_body(error):
+ """Return a failed response's body text, reading it only once."""
+ body = getattr(error, "_skill_evaluator_body", None)
+ if isinstance(body, str):
+ return body
try:
body = error.read().decode("utf-8", "replace").strip()
except Exception:
body = ""
+ with contextlib.suppress(Exception):
+ error._skill_evaluator_body = body
+ return body
+
+
+def _format_http_error_with_fallback(error):
+ body = _http_error_body(error)
raw_detail = f"HTTP {error.code}: {error.reason}"
safe_detail = raw_detail
if body:
@@ -1521,6 +1718,7 @@ def _urlopen_with_retry(request, timeout=90):
attempt = 0
while True:
request_timeout = _remaining_judge_timeout(timeout)
+ _spend_strict_judge_request()
try:
with urllib.request.urlopen(request, timeout=request_timeout) as response: # nosec B310
return response.read()
@@ -1532,6 +1730,7 @@ def _urlopen_with_retry(request, timeout=90):
or (not is_http and not is_network)
or (is_http and not _is_retriable_http_status(error.code))
or _is_certificate_failure(error)
+ or not _strict_judge_retry_allowed(error)
):
raise
@@ -1678,7 +1877,11 @@ def _call_anthropic(prompt, model, max_tokens, temperature, response_schema=None
effort = _effective_reasoning_effort("anthropic", model, JUDGE_REASONING_EFFORT)
# Server-side fallback (beta, native Claude API only): a safety-classifier
# refusal is retried on the fallback model within the same call.
- server_side_fallback = _is_claude_5_5_or_later(model) and urlparse(target_url).hostname == "api.anthropic.com"
+ server_side_fallback = (
+ _is_claude_5_5_or_later(model)
+ and urlparse(target_url).hostname == "api.anthropic.com"
+ and _builtin_refusal_fallback_allowed()
+ )
def _build_request(include_schema):
payload = {
@@ -1842,6 +2045,7 @@ def _call_bedrock(prompt, model, max_tokens, temperature, timeout=90, provenance
endpoint = getattr(client, "_endpoint", None)
if endpoint is not None and hasattr(endpoint, "timeout"):
endpoint.timeout = request_timeout
+ _spend_strict_judge_request()
try:
return client.converse(
modelId=model_id,
@@ -1850,7 +2054,11 @@ def _call_bedrock(prompt, model, max_tokens, temperature, timeout=90, provenance
)
except Exception as error:
is_retriable, status_label, retry_after_str = _classify_bedrock_retry_error(error)
- if attempt >= retry_config.max_retries or not is_retriable:
+ if (
+ attempt >= retry_config.max_retries
+ or not is_retriable
+ or not _strict_judge_retry_allowed(error)
+ ):
raise
sleep_duration = _compute_bounded_retry_delay(
@@ -1871,7 +2079,7 @@ def _call_bedrock(prompt, model, max_tokens, temperature, timeout=90, provenance
attempt += 1
response = _converse(model)
- fallback_model = _bedrock_refusal_fallback_model(model)
+ fallback_model = _bedrock_refusal_fallback_model(model) if _builtin_refusal_fallback_allowed() else None
if response.get("stopReason") == "content_filtered" and fallback_model:
# Bedrock has no server-side fallback, so retry a classifier refusal here.
response = _converse(fallback_model)
@@ -1888,6 +2096,9 @@ def _call_bedrock(prompt, model, max_tokens, temperature, timeout=90, provenance
except _JudgeRefusedError:
raise
except Exception as exc:
+ if _STRICT_JUDGE_REQUESTS_LEFT.get() is not None and _strict_judge_failure(exc)[1]:
+ # The strict policy lets the next candidate answer for an unavailable model.
+ raise
return None, f"Bedrock request failed: {exc}"
@@ -1993,6 +2204,105 @@ def _record_judge_call(provenance, requested_model, sent_model):
)
+def _call_judge_model(prompt, provider, model, max_tokens, temperature, response_schema, schema_name, provenance):
+ """Send one judge prompt to *model*; ``provenance["model"]`` becomes the model that answered."""
+ if provider == "anthropic":
+ return _call_anthropic(
+ prompt,
+ model,
+ max_tokens,
+ temperature,
+ response_schema=response_schema,
+ provenance=provenance,
+ )
+ if provider == "bedrock":
+ return _call_bedrock(prompt, model, max_tokens, temperature, provenance=provenance)
+ return _call_openai_compatible(
+ prompt,
+ provider,
+ model,
+ max_tokens,
+ temperature,
+ response_schema=response_schema,
+ schema_name=schema_name,
+ )
+
+
+def _strict_judge_failure(error):
+ """Describe a failed strict judge request and whether the next candidate may answer instead.
+
+ Only unavailability moves on: a transient HTTP status, connection failure
+ or Bedrock throttling that outlasted its one retry, a model the provider
+ does not have or the key cannot use (_should_try_fallback and
+ _strict_model_unavailable), or a used-up per-model request limit.
+ Everything else ends the judge.
+ """
+ if isinstance(error, _JudgeRefusedError):
+ return str(error), False
+ if isinstance(error, _StrictJudgeRequestLimitError):
+ return str(error), True
+ if isinstance(error, urllib.error.HTTPError):
+ detail, model_unavailable = _format_http_error_with_fallback(error)
+ if _strict_judge_error_stops(error):
+ return detail, False
+ return detail, model_unavailable or _strict_model_unavailable(error) or _is_retriable_http_status(error.code)
+ detail = f"Public provider call failed: {error}"
+ if isinstance(error, TimeoutError) and "LLM judge time budget exhausted" in str(error):
+ return detail, False
+ if _is_certificate_failure(error) or _strict_judge_error_stops(error):
+ return detail, False
+ if isinstance(error, (urllib.error.URLError, OSError)):
+ return detail, True
+ # Bedrock throttling and service errors (see _call_bedrock), or a model it cannot serve.
+ return detail, _classify_bedrock_retry_error(error)[0] or _strict_model_unavailable(error)
+
+
+def _call_strict_judge(provider, requested_model, models, call_model):
+ """Ask the judge under LLM_JUDGE_RETRY_POLICY=strict.
+
+ At most _STRICT_JUDGE_MAX_MODELS candidates are tried, the primary first,
+ with at most _STRICT_JUDGE_REQUESTS_PER_MODEL requests to each, all inside
+ the judge's wall-time budget. See _strict_judge_failure for which failures
+ move on to the next candidate. The first completed reply is final, even an
+ empty or invalid one: a second request from the same required judge, such
+ as behavior_check's format retry, is not sent, so no other model can
+ overturn the reply.
+ """
+ calls = _ACTIVE_JUDGE_CALLS.get()
+ if calls:
+ return (
+ None,
+ "LLM_JUDGE_RETRY_POLICY=strict accepts one completed reply per judge, so the judge's retry was not sent",
+ {"provider": provider, "model": calls[-1]["model"]},
+ )
+ errors = []
+ provenance = {"provider": provider, "model": requested_model}
+ for candidate_model in models[:_STRICT_JUDGE_MAX_MODELS]:
+ provenance = {"provider": provider, "model": candidate_model}
+ requests_left = _STRICT_JUDGE_REQUESTS_LEFT.set([_STRICT_JUDGE_REQUESTS_PER_MODEL])
+ try:
+ content, error = call_model(candidate_model, provenance)
+ except Exception as exc:
+ detail, move_on = _strict_judge_failure(exc)
+ errors.append(f"{candidate_model}: {detail}")
+ if not move_on:
+ # Keep the earlier models' errors, so the reason shows why they were passed over.
+ return None, _redact_configured_credentials(" | ".join(errors)), provenance
+ continue
+ finally:
+ _STRICT_JUDGE_REQUESTS_LEFT.reset(requests_left)
+ if error:
+ if errors:
+ error = " | ".join([*errors, f"{candidate_model}: {error}"])
+ return None, _redact_configured_credentials(error), provenance
+ if candidate_model != requested_model:
+ logger.warning("LLM judge model %s failed; using fallback model %s", requested_model, candidate_model)
+ _record_judge_call(provenance, requested_model, candidate_model)
+ return content, None, provenance
+ detail = "LLM judge model fallback exhausted: " + " | ".join(errors)
+ return None, _redact_configured_credentials(detail), provenance
+
+
def _call_public_llm_with_provenance(
prompt,
model=None,
@@ -2005,35 +2315,29 @@ def _call_public_llm_with_provenance(
provider = _public_provider()
if not provider:
return None, _public_provider_error(), {}
+ try:
+ # An invalid policy value fails closed before any request is sent.
+ _judge_fallback_policy()
+ strict = _judge_retry_policy() == "strict"
+ except ValueError as error:
+ return None, str(error), {}
requested_model = _selected_judge_model(model)
models = _fallback_models(requested_model) if allow_model_fallback else [requested_model]
+
+ def call_model(candidate_model, provenance):
+ return _call_judge_model(
+ prompt, provider, candidate_model, max_tokens, temperature, response_schema, schema_name, provenance
+ )
+
+ if strict:
+ return _call_strict_judge(provider, requested_model, models, call_model)
errors = []
last_provenance = {"provider": provider, "model": requested_model}
for candidate_model in models:
provenance = {"provider": provider, "model": candidate_model}
last_provenance = provenance
try:
- if provider == "anthropic":
- content, error = _call_anthropic(
- prompt,
- candidate_model,
- max_tokens,
- temperature,
- response_schema=response_schema,
- provenance=provenance,
- )
- elif provider == "bedrock":
- content, error = _call_bedrock(prompt, candidate_model, max_tokens, temperature, provenance=provenance)
- else:
- content, error = _call_openai_compatible(
- prompt,
- provider,
- candidate_model,
- max_tokens,
- temperature,
- response_schema=response_schema,
- schema_name=schema_name,
- )
+ content, error = call_model(candidate_model, provenance)
except _JudgeRefusedError as refusal:
# A classifier refusal is fallback-eligible like a missing model.
errors.append(f"{candidate_model}: {refusal}")
@@ -2167,6 +2471,22 @@ def _json_nesting_within_limit(text):
return True
+def _parse_whole_json_object(text):
+ """Return *text* parsed as one JSON object, or None when it holds anything else."""
+ if not text.startswith("{") or not _json_nesting_within_limit(text):
+ return None
+ try:
+ parsed = json.loads(
+ text,
+ object_pairs_hook=_reject_duplicate_object_pairs,
+ parse_constant=_reject_nonstandard_json_constant,
+ parse_float=_parse_finite_json_float,
+ )
+ except (json.JSONDecodeError, RecursionError, ValueError):
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
def extract_json(text):
"""Extract a JSON payload from LLM response text.
@@ -2174,11 +2494,14 @@ def extract_json(text):
container. Multiple complete documents are ambiguous, and an unfinished
earlier structural segment blocks promotion of a nested object. Top-level
arrays parse through unchanged; judge callers must dict-check the result
- themselves.
+ themselves. Under LLM_JUDGE_RETRY_POLICY=strict the whole reply, apart
+ from surrounding whitespace, must be one JSON object.
"""
text = (text or "").strip()
if not text or len(text) > _MAX_JSON_TEXT_CHARS:
return None
+ if _strict_judge_replies():
+ return _parse_whole_json_object(text)
documents = []
index = 0
@@ -2320,8 +2643,11 @@ def _salvage_behavior_results(text):
Reasoning judges that hit the output-token cap emit ``{"results": [...`` and
stop mid-entry (``finish_reason="length"``); every fully-formed ``{...}``
- entry before the cut is still valid JSON and can be scored.
+ entry before the cut is still valid JSON and can be scored. The strict
+ judge policy scores only complete replies, so nothing is salvaged under it.
"""
+ if _strict_judge_replies():
+ return []
text = text or ""
if len(text) > _MAX_JSON_TEXT_CHARS or not _json_nesting_within_limit(text):
return []
@@ -2587,6 +2913,8 @@ def _call_validated_json_judge(prompt, validate, call, extract, *, metric="judge
retried here: the transport already retried them within its own budget.
*salvage* may rebuild a usable reply from text that never parsed, such as a
reply cut off by the output-token cap; it is tried only after both attempts.
+ Under LLM_JUDGE_RETRY_POLICY=strict the first completed reply is final, so
+ an invalid one fails the judge without a retry or a salvage.
"""
call_kwargs.setdefault("max_tokens", STRUCTURED_JUDGE_MAX_TOKENS)
unparsed_replies = []
@@ -2618,6 +2946,12 @@ def _call_validated_json_judge(prompt, validate, call, extract, *, metric="judge
return None, f"LLM judge error: {error}", provenance
if problem is None:
return parsed, None, provenance
+ if _strict_judge_replies():
+ return (
+ None,
+ f"Judge response was unparseable or invalid: {problem}; LLM_JUDGE_RETRY_POLICY=strict sends no retry",
+ provenance,
+ )
parsed, error, provenance, problem = invoke(2, prompt + _judge_retry_feedback(problem))
if not error and problem is None:
@@ -2872,6 +3206,10 @@ def _ragas_goal_accuracy_enabled():
# The prompt judge can append metadata outside the original evidence.
if character_facts_enabled():
return False
+ # RAGAS sends its own requests, outside the strict policy's request limits,
+ # and an unknown policy value must fail the judge before any request.
+ if _strict_judge_replies() or not _judge_policies_valid():
+ return False
if _public_provider() != "openai" or _is_openai_reasoning_model(_selected_judge_model()):
return False
try:
diff --git a/tests/conftest.py b/tests/conftest.py
index f280c2a7..5c2573eb 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -41,6 +41,13 @@ def _isolate_operator_vertex_routing(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("SKILLEVALUATOR_ALLOWED_MCP_SECRETS", raising=False)
[email protected](autouse=True)
+def _isolate_operator_judge_policies(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep tests on the default judge policies even when the host shell opts in to others."""
+ monkeypatch.delenv("LLM_JUDGE_FALLBACK_POLICY", raising=False)
+ monkeypatch.delenv("LLM_JUDGE_RETRY_POLICY", raising=False)
+
+
# =============================================================================
# SKILLS FIXTURES
# =============================================================================
diff --git a/tests/test_harbor_runner_environment.py b/tests/test_harbor_runner_environment.py
index e438e5d1..b352da8c 100644
--- a/tests/test_harbor_runner_environment.py
+++ b/tests/test_harbor_runner_environment.py
@@ -282,7 +282,14 @@ def test_skill_config_cannot_control_evaluator_or_judge_routing(name: str) -> No
@pytest.mark.parametrize(
"name",
- ["LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL", "LLM_JUDGE_FALLBACK_MODELS", "SKILL_EVAL_JUDGE_CHARACTER_FACTS"],
+ [
+ "LLM_JUDGE_MODEL",
+ "SKILL_EVAL_JUDGE_MODEL",
+ "LLM_JUDGE_FALLBACK_MODELS",
+ "SKILL_EVAL_JUDGE_CHARACTER_FACTS",
+ "LLM_JUDGE_FALLBACK_POLICY",
+ "LLM_JUDGE_RETRY_POLICY",
+ ],
)
@pytest.mark.parametrize("provider_name", ["openai", "openai-compatible", "anthropic", "bedrock", "nv_build"])
@pytest.mark.parametrize(
diff --git a/tests/test_harbor_runtime_skill_isolation.py b/tests/test_harbor_runtime_skill_isolation.py
index c4a59347..fb603e11 100644
--- a/tests/test_harbor_runtime_skill_isolation.py
+++ b/tests/test_harbor_runtime_skill_isolation.py
@@ -409,7 +409,14 @@ def test_native_custom_only_preserves_authored_judge_controls_in_verifier_env(
@pytest.mark.parametrize("scope", ["task", "step"])
@pytest.mark.parametrize(
"name",
- ["LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL", "LLM_JUDGE_FALLBACK_MODELS", "SKILL_EVAL_JUDGE_CHARACTER_FACTS"],
+ [
+ "LLM_JUDGE_MODEL",
+ "SKILL_EVAL_JUDGE_MODEL",
+ "LLM_JUDGE_FALLBACK_MODELS",
+ "SKILL_EVAL_JUDGE_CHARACTER_FACTS",
+ "LLM_JUDGE_FALLBACK_POLICY",
+ "LLM_JUDGE_RETRY_POLICY",
+ ],
)
def test_native_standard_grading_rejects_task_owned_judge_controls(
tmp_path: Path,
@@ -448,6 +455,8 @@ def test_native_standard_grading_rejects_task_owned_judge_controls(
"LLM_JUDGE_MODEL",
"SKILL_EVAL_JUDGE_MODEL",
"LLM_JUDGE_FALLBACK_MODELS",
+ "LLM_JUDGE_FALLBACK_POLICY",
+ "LLM_JUDGE_RETRY_POLICY",
],
)
def test_native_standard_grading_allows_exact_operator_staged_control_placeholders(
@@ -492,6 +501,22 @@ def test_native_standard_grading_injects_operator_staged_judge_fallback(tmp_path
assert config.verifier.env["LLM_JUDGE_FALLBACK_MODELS"] == "${LLM_JUDGE_FALLBACK_MODELS}"
+def test_native_standard_grading_injects_operator_staged_judge_policies(tmp_path: Path) -> None:
+ _, target, _, _ = _write_projection_fixture(tmp_path)
+ _write_minimal_native_task(target)
+ names = ("LLM_JUDGE_FALLBACK_POLICY", "LLM_JUDGE_RETRY_POLICY")
+
+ [staged] = stage_native_harbor_tasks(
+ target,
+ tmp_path / "native-operator-policies",
+ grading_mode="default",
+ verifier_env={name: f"${{{name}}}" for name in names},
+ )
+
+ config = TaskConfig.model_validate_toml((staged / "task.toml").read_text(encoding="utf-8"))
+ assert {name: config.verifier.env[name] for name in names} == {name: f"${{{name}}}" for name in names}
+
+
@pytest.mark.parametrize(
"assignment",
[
diff --git a/tests/tier3/test_judge_policies.py b/tests/tier3/test_judge_policies.py
new file mode 100644
index 00000000..b647a962
--- /dev/null
+++ b/tests/tier3/test_judge_policies.py
@@ -0,0 +1,797 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Opt-in judge policies: LLM_JUDGE_FALLBACK_POLICY and LLM_JUDGE_RETRY_POLICY."""
+
+from __future__ import annotations
+
+import io
+import json
+import ssl
+import time
+import urllib.error
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from tests.conftest import load_harbor_eval_template
+
+from skillevaluator.provider_config import ProviderConfig
+from skillevaluator.tier3.harbor import runner
+from skillevaluator.tier3.harbor.adapter import _verifier_env_block
+
+PRIMARY = "family/primary"
+ALLOWLIST = "family/backup,family/last,other/forbidden"
+POLICY_VARS = ("LLM_JUDGE_FALLBACK_POLICY", "LLM_JUDGE_RETRY_POLICY")
+GOAL_REPLY = json.dumps({"user_goal": "g", "end_state": "e", "achieved": False, "reason": "missing"})
+
+
+class _Clock:
+ """Stand-in for the verifier's ``time`` module with a manual monotonic clock."""
+
+ def __init__(self):
+ self.now = 0.0
+ self.sleeps = []
+
+ def monotonic(self):
+ return self.now
+
+ def sleep(self, seconds):
+ self.sleeps.append(seconds)
+ self.now += seconds
+
+ def __getattr__(self, name):
+ return getattr(time, name)
+
+
+def verifier(monkeypatch):
+ module = load_harbor_eval_template("judge_policies_verifier")
+ for name in (
+ *POLICY_VARS,
+ "LLM_JUDGE_FALLBACK_MODELS",
+ "LLM_JUDGE_MODEL",
+ "SKILL_EVAL_JUDGE_MODEL",
+ "SKILL_EVAL_LLM_MODEL",
+ "SKILL_EVAL_JUDGE_CHARACTER_FACTS",
+ "SKILL_EVAL_LLM_JUDGE_BUDGET_SEC",
+ "SKILL_EVAL_LLM_MAX_RETRIES",
+ "SKILL_EVAL_LLM_RETRY_BASE_DELAY",
+ "SKILL_EVAL_LLM_RETRY_MAX_DELAY",
+ "SKILL_EVAL_LLM_CREDENTIAL_SOURCE",
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_BASE_URL",
+ "NVIDIA_API_KEY",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai-compatible")
+ monkeypatch.setenv("SKILL_EVAL_LLM_API_KEY", "judge-test-key")
+ monkeypatch.setenv("SKILL_EVAL_LLM_BASE_URL", "https://judge.example/v1")
+ monkeypatch.setattr(module, "time", _Clock())
+ return module
+
+
+def strict(monkeypatch):
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_POLICY", "replace")
+ monkeypatch.setenv("LLM_JUDGE_RETRY_POLICY", "strict")
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_MODELS", ALLOWLIST)
+ monkeypatch.setenv("LLM_JUDGE_MODEL", PRIMARY)
+
+
+def completion(content, **choice):
+ message = {"content": content}
+ if "refusal" in choice:
+ message["refusal"] = choice.pop("refusal")
+ return io.BytesIO(json.dumps({"choices": [{"message": message, **choice}]}).encode())
+
+
+def http_error(code=429, body=b'{"error":{"code":"capacity_exceeded"}}', headers=None):
+ return urllib.error.HTTPError("https://judge.example/v1", code, "test", headers or {}, io.BytesIO(body))
+
+
+def replay(verifier, monkeypatch, outcomes):
+ """Answer each judge request with the next outcome and return the requested models."""
+ requested = []
+ pending = iter(outcomes)
+
+ def open_request(request, timeout):
+ requested.append(json.loads(request.data)["model"])
+ outcome = next(pending)
+ if isinstance(outcome, BaseException):
+ raise outcome
+ return outcome
+
+ monkeypatch.setattr(verifier.urllib.request, "urlopen", open_request)
+ return requested
+
+
+def goal_judge(verifier):
+ return verifier._call_required_judge("goal_accuracy", verifier._judge_goal_accuracy_custom, "q", "truth", "e", "")
+
+
+# ---------------------------------------------------------------------------
+# Fallback policy
+# ---------------------------------------------------------------------------
+
+
+ ("policy", "answered_by"),
+ [("replace", "family/backup"), ("append", "us.anthropic.claude-opus-4-8")],
+)
+def test_refused_judge_is_answered_from_the_explicit_list_only_under_replace(
+ verifier, monkeypatch, policy, answered_by
+):
+ import boto3
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "bedrock")
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_POLICY", policy)
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_MODELS", "family/backup")
+ client = MagicMock()
+ client.converse.side_effect = [
+ {"stopReason": "content_filtered", "output": {"message": {"content": []}}},
+ {"stopReason": "end_turn", "output": {"message": {"content": [{"text": "judged"}]}}},
+ ]
+ monkeypatch.setattr(boto3, "client", lambda *_args, **_kwargs: client)
+
+ content, error, provenance = verifier._call_public_llm_with_provenance(
+ "prompt", model="us.anthropic.claude-opus-5-5"
+ )
+
+ assert (content, error) == ("judged", None)
+ assert provenance["model"] == answered_by
+ assert [call.kwargs["modelId"] for call in client.converse.call_args_list] == [
+ "us.anthropic.claude-opus-5-5",
+ answered_by,
+ ]
+
+
+def _anthropic_request(verifier, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "judge-test-key")
+ monkeypatch.delenv("SKILL_EVAL_LLM_BASE_URL")
+ sent = []
+
+ def open_request(request, timeout):
+ sent.append(request)
+ body = {"content": [{"type": "text", "text": "Done"}], "stop_reason": "end_turn"}
+ return io.BytesIO(json.dumps(body).encode())
+
+ monkeypatch.setattr(verifier.urllib.request, "urlopen", open_request)
+ assert verifier._call_anthropic("prompt", "claude-opus-5-5", 4096, 0.0) == ("Done", None)
+ return sent[0]
+
+
+ ("name", "value"), [("LLM_JUDGE_FALLBACK_POLICY", "replace"), ("LLM_JUDGE_RETRY_POLICY", "strict")]
+)
+def test_policy_turns_off_the_builtin_anthropic_refusal_fallback(verifier, monkeypatch, name, value):
+ monkeypatch.setenv(name, value)
+
+ request = _anthropic_request(verifier, monkeypatch)
+
+ assert "fallbacks" not in json.loads(request.data)
+ assert request.get_header("Anthropic-beta") is None
+
+
[email protected](("fallback_policy", "retry_policy"), [(None, None), (" APPEND ", "Legacy")])
+def test_default_policies_keep_the_builtin_anthropic_refusal_fallback(
+ verifier, monkeypatch, fallback_policy, retry_policy
+):
+ for name, value in zip(POLICY_VARS, (fallback_policy, retry_policy), strict=True):
+ if value is not None:
+ monkeypatch.setenv(name, value)
+
+ request = _anthropic_request(verifier, monkeypatch)
+
+ assert json.loads(request.data)["fallbacks"] == [{"model": "claude-opus-4-8"}]
+
+
+ ("name", "value"), [("LLM_JUDGE_FALLBACK_POLICY", "replace"), ("LLM_JUDGE_RETRY_POLICY", "strict")]
+)
+def test_policy_turns_off_the_builtin_bedrock_refusal_fallback(verifier, monkeypatch, name, value):
+ import boto3
+
+ monkeypatch.setenv(name, value)
+ client = MagicMock()
+ client.converse.side_effect = [
+ {"stopReason": "content_filtered", "output": {"message": {"content": []}}},
+ {"stopReason": "end_turn", "output": {"message": {"content": [{"text": "Done"}]}}},
+ ]
+ monkeypatch.setattr(boto3, "client", lambda *_args, **_kwargs: client)
+
+ with pytest.raises(verifier._JudgeRefusedError):
+ verifier._call_bedrock("prompt", "us.anthropic.claude-opus-5-5", 4096, 0.0)
+
+ assert [call.kwargs["modelId"] for call in client.converse.call_args_list] == ["us.anthropic.claude-opus-5-5"]
+
+
+# ---------------------------------------------------------------------------
+# Strict retry policy
+# ---------------------------------------------------------------------------
+
+
+def test_strict_retries_capacity_once_then_records_the_model_that_answered(verifier, monkeypatch):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(), http_error(), completion(GOAL_REPLY)])
+
+ result = goal_judge(verifier)
+
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+ assert result["score"] == 0.0
+ assert result["judge_model_used"] == "family/backup"
+ assert result["judge_fallback_used"] is True
+
+
+def test_strict_tries_at_most_three_models_twice_each(verifier, monkeypatch):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error() for _ in range(8)])
+
+ result = goal_judge(verifier)
+
+ assert requested == [PRIMARY] * 2 + ["family/backup"] * 2 + ["family/last"] * 2
+ assert result["score"] is None
+ assert result["status"] == "error"
+ assert "fallback exhausted" in result["reason"]
+
+
[email protected]("status", [408, 429, 500, 502, 503, 504])
+def test_strict_availability_moves_on_only_after_one_retry(verifier, monkeypatch, status):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(status), http_error(status), completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+def test_strict_connection_failure_moves_on_after_one_retry(verifier, monkeypatch):
+ strict(monkeypatch)
+ refused = urllib.error.URLError(ConnectionRefusedError("connection refused"))
+ requested = replay(verifier, monkeypatch, [refused, refused, completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+def test_strict_certificate_failure_ends_the_judge(verifier, monkeypatch):
+ strict(monkeypatch)
+ failure = urllib.error.URLError(ssl.SSLCertVerificationError("certificate verify failed"))
+ requested = replay(verifier, monkeypatch, [failure, completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and "certificate verify failed" in error
+ assert requested == [PRIMARY]
+
+
+def test_strict_model_access_denial_moves_to_the_explicit_list(verifier, monkeypatch):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(403, b"key_model_access_denied"), completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, "family/backup"]
+
+
+ ("code", "body"),
+ [
+ (400, b"content_filter"),
+ (401, b"unauthorized"),
+ (403, b"policy rejection"),
+ (409, b"conflict"),
+ (429, b'{"error":{"code":"insufficient_quota"}}'),
+ (429, b"key budget exhausted"),
+ (501, b"not implemented"),
+ (503, b"blocked by safety system"),
+ ],
+)
+def test_strict_rejection_is_not_retried_or_handed_on(verifier, monkeypatch, code, body):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(code, body), completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and f"HTTP {code}" in error
+ assert requested == [PRIMARY]
+
+
+def test_strict_stop_keeps_the_errors_of_earlier_models(verifier, monkeypatch):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(503), http_error(503), http_error(401, b"bad key")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None
+ assert error.startswith(f"{PRIMARY}: HTTP 503")
+ assert error.endswith("family/backup: HTTP 401: test - bad key")
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+def test_strict_reads_stop_words_only_at_the_start_of_an_error_page(verifier, monkeypatch):
+ strict(monkeypatch)
+ page = b"<html><title>Error 502</title>" + b" " * 600 + b"Performance and security by a proxy</html>"
+ requested = replay(verifier, monkeypatch, [http_error(502, page), http_error(502, page), completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+OPENAI_MODEL_NOT_FOUND = (
+ b'{"error":{"message":"The model `family/primary` does not exist or you do not have access to it.",'
+ b'"type":"invalid_request_error","param":null,"code":"model_not_found"}}'
+)
+
+
+ "body",
+ [
+ OPENAI_MODEL_NOT_FOUND,
+ b'{"error":{"message":"The model `family/primary` does not exist.","type":"invalid_request_error"}}',
+ b'{"type":"error","error":{"type":"not_found_error","message":"model: family/primary"}}',
+ ],
+)
+def test_strict_missing_model_moves_to_the_explicit_list_without_a_retry(verifier, monkeypatch, body):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(404, body), completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, "family/backup"]
+
+
+def test_strict_other_not_found_error_ends_the_judge(verifier, monkeypatch):
+ strict(monkeypatch)
+ body = b'{"type":"error","error":{"type":"not_found_error","message":"Not found"}}'
+ requested = replay(verifier, monkeypatch, [http_error(404, body), completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and "HTTP 404" in error
+ assert requested == [PRIMARY]
+
+
+def test_legacy_policy_keeps_its_model_error_rules(verifier, monkeypatch):
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_MODELS", ALLOWLIST)
+ requested = replay(verifier, monkeypatch, [http_error(404, OPENAI_MODEL_NOT_FOUND), completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt", model=PRIMARY)
+
+ assert content is None and "HTTP 404" in error
+ assert requested == [PRIMARY]
+
+
+def _bedrock_error(code, status, message):
+ error = RuntimeError(message)
+ error.response = {"Error": {"Code": code, "Message": message}, "ResponseMetadata": {"HTTPStatusCode": status}}
+ return error
+
+
+def _bedrock_client(monkeypatch, outcomes):
+ import boto3
+
+ client = MagicMock()
+ client.converse.side_effect = outcomes
+ monkeypatch.setattr(boto3, "client", lambda *_args, **_kwargs: client)
+ return client
+
+
+ ("code", "status", "message"),
+ [
+ ("AccessDeniedException", 403, "You don't have access to the model with the specified model ID."),
+ ("ResourceNotFoundException", 404, "Model not found."),
+ ("ValidationException", 400, "The provided model identifier is invalid."),
+ ],
+)
+def test_strict_bedrock_model_unavailable_moves_on_without_a_retry(verifier, monkeypatch, code, status, message):
+ strict(monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "bedrock")
+ answered = {"stopReason": "end_turn", "output": {"message": {"content": [{"text": "judged"}]}}}
+ client = _bedrock_client(monkeypatch, [_bedrock_error(code, status, message), answered])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert [call.kwargs["modelId"] for call in client.converse.call_args_list] == [PRIMARY, "family/backup"]
+
+
+def test_strict_bedrock_other_validation_error_ends_the_judge(verifier, monkeypatch):
+ strict(monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "bedrock")
+ invalid = _bedrock_error("ValidationException", 400, "maxTokens: must be at most 8192")
+ client = _bedrock_client(monkeypatch, [invalid, {"stopReason": "end_turn"}])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and "maxTokens" in error
+ assert [call.kwargs["modelId"] for call in client.converse.call_args_list] == [PRIMARY]
+
+
+def test_strict_bedrock_stop_keeps_the_errors_of_earlier_models(verifier, monkeypatch):
+ strict(monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "bedrock")
+ throttled = _bedrock_error("ThrottlingException", 429, "Too many requests")
+ invalid = _bedrock_error("ValidationException", 400, "maxTokens: must be at most 8192")
+ _bedrock_client(monkeypatch, [throttled, throttled, invalid])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None
+ assert error.startswith(f"{PRIMARY}: Public provider call failed: Too many requests | family/backup: ")
+ assert error.endswith("maxTokens: must be at most 8192")
+
+
+def test_strict_stop_words_in_an_echoed_model_id_do_not_end_the_judge(verifier, monkeypatch):
+ strict(monkeypatch)
+ monkeypatch.setenv("LLM_JUDGE_MODEL", "vendor/content-safety-judge")
+ missing = http_error(404, b'{"error":{"message":"invalid model: vendor/content-safety-judge"}}')
+ requested = replay(verifier, monkeypatch, [missing, completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == ["vendor/content-safety-judge", "family/backup"]
+
+
+def test_strict_stop_words_in_a_connection_error_do_not_end_the_judge(verifier, monkeypatch):
+ strict(monkeypatch)
+ tunnel = urllib.error.URLError(OSError("Tunnel connection failed: 503 security-proxy.example unavailable"))
+ requested = replay(verifier, monkeypatch, [tunnel, tunnel, completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+ "body",
+ [
+ b'{"error":{"code":"budget_exceeded","message":"Budget has been exceeded"}}',
+ b'{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low"}}',
+ b'{"error":{"code":"billing_hard_limit_reached","message":"Billing hard limit has been reached"}}',
+ b'{"error":{"code":"content_filter","message":"The prompt was filtered"}}',
+ b'{"detail":"Budget has been exceeded for this key"}',
+ b'{"error":{"status":429},"note":"insufficient_quota"}',
+ ],
+)
+def test_strict_structured_stop_errors_end_the_judge(verifier, monkeypatch, body):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [http_error(429, body), completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and "HTTP 429" in error
+ assert requested == [PRIMARY]
+
+
+ "reply",
+ [
+ completion("ignored", refusal="I can't help with that."),
+ completion("", finish_reason="content_filter"),
+ ],
+)
+def test_strict_refusal_never_switches_models(verifier, monkeypatch, reply):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [reply, completion("judged")])
+
+ content, error = verifier.call_public_llm("prompt")
+
+ assert content is None and "declined the request" in error
+ assert requested == [PRIMARY]
+
+
+def test_strict_empty_reply_is_final(verifier, monkeypatch):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [completion(None), completion(GOAL_REPLY)])
+
+ result = goal_judge(verifier)
+
+ assert result["status"] == "error"
+ assert "LLM_JUDGE_RETRY_POLICY=strict" in result["reason"]
+ assert requested == [PRIMARY]
+
+
+def test_strict_candidates_share_the_judge_time_budget(verifier, monkeypatch):
+ strict(monkeypatch)
+ clock = verifier.time
+ requested = []
+
+ def unavailable(request, timeout):
+ requested.append(json.loads(request.data)["model"])
+ clock.now += 100
+ raise http_error()
+
+ monkeypatch.setattr(verifier.urllib.request, "urlopen", unavailable)
+ token = verifier._ACTIVE_JUDGE_DEADLINE.set(110.0)
+ try:
+ content, error = verifier.call_public_llm("prompt")
+ finally:
+ verifier._ACTIVE_JUDGE_DEADLINE.reset(token)
+
+ assert content is None and "time budget exhausted" in error
+ assert requested == [PRIMARY, PRIMARY]
+
+
+def test_strict_retry_after_never_waits_past_the_judge_budget(verifier, monkeypatch):
+ strict(monkeypatch)
+ clock = verifier.time
+ requested = replay(verifier, monkeypatch, [http_error(headers={"Retry-After": "20"}), completion("judged")])
+ token = verifier._ACTIVE_JUDGE_DEADLINE.set(10.0)
+ try:
+ content, error = verifier.call_public_llm("prompt")
+ finally:
+ verifier._ACTIVE_JUDGE_DEADLINE.reset(token)
+
+ assert content is None and "time budget exhausted" in error
+ assert requested == [PRIMARY]
+ assert clock.sleeps == []
+
+
+def test_strict_retry_after_above_the_maximum_delay_moves_on_without_waiting(verifier, monkeypatch):
+ strict(monkeypatch)
+ clock = verifier.time
+ requested = replay(verifier, monkeypatch, [http_error(headers={"Retry-After": "600"}), completion("judged")])
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert requested == [PRIMARY, "family/backup"]
+ assert clock.sleeps == []
+
+
+def test_strict_schema_downgrade_counts_toward_the_request_limit(verifier, monkeypatch):
+ strict(monkeypatch)
+ schema_rejected = http_error(400, b'{"error":{"message":"response_format is not supported"}}')
+ requested = replay(verifier, monkeypatch, [http_error(), schema_rejected, completion("judged")])
+
+ assert verifier.call_public_llm("prompt", response_schema={"type": "object"}) == ("judged", None)
+ assert requested == [PRIMARY, PRIMARY, "family/backup"]
+
+
+ "reply",
+ [
+ "not JSON",
+ '{"achieved":"false"}',
+ '{"achieved":false,"reason":7}',
+ '{"achieved":true,"reason":"example"}\n{"achieved":false,"reason":"actual judgment"}',
+ '{"achieved":true,"reason":"example"} trailing prose',
+ 'I cannot judge this request. The requested schema is {"achieved":true,"reason":"example"}.',
+ 'Refused.\n```json\n{"achieved":true,"reason":"example"}\n```',
+ '```json\n{"achieved":true,"reason":"example"}\n```',
+ '{"achieved":false,"achieved":true,"reason":"contradictory"}',
+ '{"achieved":true,"reason":"example","invalid":NaN}',
+ ],
+)
+def test_strict_completed_reply_that_is_not_one_valid_object_is_final(verifier, monkeypatch, reply):
+ strict(monkeypatch)
+ requested = replay(verifier, monkeypatch, [completion(reply), completion('{"achieved":true}')])
+
+ result = goal_judge(verifier)
+
+ assert result["score"] is None
+ assert result["status"] == "error"
+ assert "LLM_JUDGE_RETRY_POLICY=strict sends no retry" in result["reason"]
+ assert requested == [PRIMARY]
+
+
[email protected]("achieved", [False, True])
+def test_strict_whole_object_keeps_the_completed_verdict(verifier, monkeypatch, achieved):
+ strict(monkeypatch)
+ reply = " \n" + json.dumps({"achieved": achieved, "reason": "actual judgment"}) + "\n "
+ requested = replay(verifier, monkeypatch, [completion(reply), completion('{"achieved":true}')])
+
+ result = goal_judge(verifier)
+
+ assert result["score"] == float(achieved)
+ assert result["reason"] == "actual judgment"
+ assert requested == [PRIMARY]
+
+
+def test_legacy_json_extraction_remains_permissive(verifier):
+ assert verifier.extract_json('explanation: {"achieved":true} trailing prose') == {"achieved": True}
+
+
+def test_strict_behavior_check_neither_retries_nor_salvages(verifier, monkeypatch):
+ strict(monkeypatch)
+ truncated = '{"results": [{"step": 1, "passed": true, "reason": "seen"}, {"step": 2, "pas'
+ requested = replay(verifier, monkeypatch, [completion(truncated), completion(truncated)])
+
+ result = verifier._call_required_judge(
+ "behavior_check", verifier.judge_behavior_check, "conversation", ["first", "second"]
+ )
+
+ assert result["score"] is None
+ assert result["status"] == "error"
+ assert "LLM_JUDGE_RETRY_POLICY=strict" in result["reason"]
+ assert requested == [PRIMARY]
+
+
+def test_strict_goal_judge_skips_ragas(verifier, monkeypatch):
+ strict(monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "judge-test-key")
+ monkeypatch.delenv("SKILL_EVAL_LLM_BASE_URL")
+ monkeypatch.setenv("LLM_JUDGE_MODEL", "gpt-4o")
+ monkeypatch.setattr(
+ verifier, "_judge_goal_accuracy_ragas", lambda *_args: pytest.fail("RAGAS sends its own judge requests")
+ )
+ requested = replay(verifier, monkeypatch, [completion(GOAL_REPLY)])
+
+ assert verifier.judge_goal_accuracy("q", "truth", "e")["score"] == 0.0
+ assert requested == ["gpt-4o"]
+
+
+def test_strict_bedrock_throttling_moves_on_after_one_retry(verifier, monkeypatch):
+ import boto3
+
+ strict(monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "bedrock")
+ throttled = RuntimeError("throttled")
+ throttled.response = {"Error": {"Code": "ThrottlingException"}, "ResponseMetadata": {"HTTPStatusCode": 429}}
+ client = MagicMock()
+ client.converse.side_effect = [
+ throttled,
+ throttled,
+ {"stopReason": "end_turn", "output": {"message": {"content": [{"text": "judged"}]}}},
+ ]
+ monkeypatch.setattr(boto3, "client", lambda *_args, **_kwargs: client)
+
+ assert verifier.call_public_llm("prompt") == ("judged", None)
+ assert [call.kwargs["modelId"] for call in client.converse.call_args_list] == [PRIMARY, PRIMARY, "family/backup"]
+
+
+ ("name", "value"), [("LLM_JUDGE_RETRY_POLICY", "typo"), ("LLM_JUDGE_FALLBACK_POLICY", "prepend")]
+)
+def test_invalid_policy_fails_closed_before_any_request(verifier, monkeypatch, name, value):
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(
+ verifier.urllib.request, "urlopen", lambda *_args, **_kwargs: pytest.fail("invalid policy sent a request")
+ )
+
+ content, error = verifier.call_public_llm("prompt")
+ result = goal_judge(verifier)
+
+ assert content is None and error.startswith(f"{name} must be ")
+ assert result["status"] == "error"
+ assert name in result["reason"]
+
+
+ ("name", "value"), [("LLM_JUDGE_FALLBACK_POLICY", "replce"), ("LLM_JUDGE_RETRY_POLICY", "strcit")]
+)
+def test_invalid_policy_keeps_the_ragas_goal_scorer_off(verifier, monkeypatch, name, value):
+ monkeypatch.setenv(name, value)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "judge-test-key")
+ monkeypatch.delenv("SKILL_EVAL_LLM_BASE_URL")
+ monkeypatch.setenv("LLM_JUDGE_MODEL", "gpt-4o")
+ monkeypatch.setattr(
+ verifier, "_judge_goal_accuracy_ragas", lambda *_args: pytest.fail("RAGAS sent its own judge request")
+ )
+ monkeypatch.setattr(
+ verifier.urllib.request, "urlopen", lambda *_args, **_kwargs: pytest.fail("invalid policy sent a request")
+ )
+
+ result = verifier._call_required_judge("goal_accuracy", verifier.judge_goal_accuracy, "q", "truth", "e", "")
+
+ assert verifier._ragas_goal_accuracy_enabled() is False
+ assert result["status"] == "error"
+ assert name in result["reason"]
+
+
+def test_default_policies_keep_legacy_retries_and_refusal_fallback(verifier, monkeypatch):
+ monkeypatch.setenv("LLM_JUDGE_FALLBACK_MODELS", ALLOWLIST)
+ requested = replay(verifier, monkeypatch, [completion("ignored", refusal="no"), *[http_error() for _ in range(4)]])
+
+ content, error = verifier.call_public_llm("prompt", model=PRIMARY)
+
+ assert content is None and "HTTP 429" in error
+ assert requested == [PRIMARY] + ["family/backup"] * 4
+
+
+# ---------------------------------------------------------------------------
+# Host forwarding
+# ---------------------------------------------------------------------------
+
+
+def test_task_verifier_env_forwards_the_judge_policies():
+ env = _verifier_env_block({"LLM_JUDGE_FALLBACK_POLICY": "replace", "LLM_JUDGE_RETRY_POLICY": "strict"})
+
+ assert 'LLM_JUDGE_FALLBACK_POLICY = "${LLM_JUDGE_FALLBACK_POLICY}"' in env
+ assert 'LLM_JUDGE_RETRY_POLICY = "${LLM_JUDGE_RETRY_POLICY}"' in env
+
+
+def test_host_judge_policies_reach_only_the_standard_verifier_job(monkeypatch):
+ monkeypatch.setattr(
+ runner.os, "environ", {"LLM_JUDGE_FALLBACK_POLICY": " replace ", "LLM_JUDGE_RETRY_POLICY": "Strict"}
+ )
+ provider = ProviderConfig(
+ provider="openai",
+ model="test-model",
+ api_key="provider-key",
+ base_url="https://provider.example/v1",
+ litellm_model="openai/test-model",
+ )
+
+ provider_env = runner._provider_environment(provider)
+
+ assert provider_env["LLM_JUDGE_FALLBACK_POLICY"] == "replace"
+ assert provider_env["LLM_JUDGE_RETRY_POLICY"] == "Strict"
+ assert runner._job_judge_verifier_env(provider_env, "default") == {
+ "LLM_JUDGE_FALLBACK_POLICY": "${LLM_JUDGE_FALLBACK_POLICY}",
+ "LLM_JUDGE_RETRY_POLICY": "${LLM_JUDGE_RETRY_POLICY}",
+ }
+ assert runner._job_judge_verifier_env(provider_env, "custom_only") == {}
+ configuration = runner._judge_model_config(provider, provider_env, "default")
+ assert configuration["fallback_policy"] == "replace"
+ assert configuration["retry_policy"] == "strict"
+
+
[email protected]("name", POLICY_VARS)
+def test_skill_runtime_env_cannot_set_a_judge_policy(name):
+ resolved, errors = runner._resolve_runtime_env({name: "legacy"}, env_mode="docker")
+
+ assert resolved == {}
+ assert errors and "host process" in errors[0]
+
+
+def test_unset_policies_are_not_recorded():
+ provider = SimpleNamespace(provider="openai", model="test-model")
+
+ configuration = runner._judge_model_config(provider, {}, "default")
+
+ assert "fallback_policy" not in configuration
+ assert "retry_policy" not in configuration
+
+
+ ("name", "value"), [("LLM_JUDGE_FALLBACK_POLICY", "replce"), ("LLM_JUDGE_RETRY_POLICY", "strcit")]
+)
+def test_unknown_policy_is_not_recorded_as_applied(name, value):
+ provider = SimpleNamespace(provider="openai", model="test-model")
+
+ configuration = runner._judge_model_config(provider, {name: value}, "default")
+
+ assert "fallback_policy" not in configuration
+ assert "retry_policy" not in configuration
+
+
+ ("name", "value", "expected"),
+ [
+ ("LLM_JUDGE_FALLBACK_POLICY", "replce", "LLM_JUDGE_FALLBACK_POLICY must be append or replace"),
+ ("LLM_JUDGE_RETRY_POLICY", "strcit", "LLM_JUDGE_RETRY_POLICY must be legacy or strict"),
+ ],
+)
+def test_unknown_policy_stops_the_run_before_any_trial(monkeypatch, tmp_path, name, value, expected):
+ monkeypatch.setenv(name, value)
+
+ result = _run_until_staging(monkeypatch, tmp_path)
+
+ assert result["error"] == [expected]
+
+
+def test_custom_only_run_ignores_the_judge_policies(monkeypatch, tmp_path):
+ monkeypatch.setenv("LLM_JUDGE_RETRY_POLICY", "strcit")
+
+ result = _run_until_staging(monkeypatch, tmp_path, grading_mode="custom_only")
+
+ assert not any("LLM_JUDGE_RETRY_POLICY" in error for error in result.get("error", []))
+
+
+def _run_until_staging(monkeypatch, tmp_path, **engine_kwargs):
+ """Run the Harbor engine with the provider, prerequisites, staging and trials stubbed out."""
+ skill = tmp_path / "demo"
+ (skill / "evals").mkdir(parents=True)
+ (skill / "evals" / "config.yml").write_text("schema_version: 1\n", encoding="utf-8")
+ monkeypatch.setattr(
+ runner,
+ "resolve_llm_provider",
+ lambda: ProviderConfig(
+ provider="openai",
+ model="test-model",
+ api_key="provider-key",
+ base_url="https://provider.example/v1",
+ litellm_model="openai/test-model",
+ ),
+ )
+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])
+ monkeypatch.setattr(runner, "generate_harbor_tasks", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr(runner, "_run_agent_pair", lambda **_kwargs: pytest.fail("trials started"))
+
+ return runner.run_harbor_eval(skill, ["codex"], output_dir=tmp_path / "results", env_mode="docker", **engine_kwargs)