Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ All notable changes to SkillEvaluator are documented in this file.
release binary.
- Malformed optional trajectory `final_metrics` leave condition usage unavailable
and no longer abort fresh or reused Tier 3 result collection.
- Bound declarative output-pattern checks with isolated Python regex workers and a shared
matching budget, preserving Python regex semantics and later checks. Interpreter
startup and JSON transfer have a separate startup allowance and do not consume
the matching budget; invalid patterns remain unscored across output encodings.
Pattern timeouts and exhausted matching budgets count as failed checks, so
slow failing patterns cannot increase the behavior score. Operators can
configure the per-pattern deadline and shared budget through the existing
verifier environment.
- Rebuilding validation results after severity overrides or scanner finding
deduplication no longer repeatedly scans accumulated independent diagnostics;
diagnostic order, duplicate-warning options and summary counts are preserved.
Expand Down
23 changes: 23 additions & 0 deletions docs/environment-variables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,29 @@ execution environments are covered in
| `SKILLEVALUATOR_GKE_AUTOPILOT` | auto-detected | Explicitly set `1`/`true` or `0`/`false` (or pass `--ek autopilot=<bool>`) to control GKE Autopilot ephemeral-storage adjustment (`10Gi` → `10176Mi` on non-accelerator `main` containers so adding the `64Mi` probe container stays within Autopilot's `10Gi` general-purpose pod ceiling) when node listing or `gcloud` inspection is unavailable. |
| `SKILLEVALUATOR_VERTEX_ADC_JOB_TIMEOUT_SEC` | `3300` seconds | Maximum wall-clock timeout per Harbor subprocess invocation when using short-lived Google Application Default Credentials (ADC) with a Vertex AI OpenAPI endpoint, capped to the remaining token lifetime minus a 60-second safety margin. |

### Output-pattern check limits

These variables apply to runtime `output_matches` checks in the unreleased
checkout. Set them in the host environment that runs `skillevaluator`; Tier 3
forwards them through the generated Harbor task's verifier environment.

| Variable | Default | Effect |
| --- | --- | --- |
| `SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC` | `1` second | Time allowed for one pattern's compilation and matching after its worker is ready, bounded by the remaining shared budget. |
| `SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC` | `5` seconds | Shared compilation and matching budget for all output patterns in one case. |

Both settings accept positive finite seconds. Empty, non-numeric, non-finite,
zero, or negative values use the default. Very large finite values are capped
at the platform's supported wait limit. Raise both settings when a legitimate
pattern needs more time than the shared budget permits.

A timed-out pattern or a check reached after the shared budget is exhausted
counts as failed and remains in the `behavior_check` denominator. Later literal
checks continue. Invalid-pattern errors reported by a worker and worker startup
failures remain not checked. Interpreter startup and input transfer have a separate 10-second
allowance and do not consume the matching budget; these settings do not change
the overall Harbor verifier timeout.

### Harbor process environment

SkillEvaluator starts every Harbor process in an empty, evaluator-owned working
Expand Down
10 changes: 10 additions & 0 deletions docs/eval-datasets.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,16 @@ Unknown check types and invalid fields are dataset-validation errors. On a
without-skill baseline, checks for scripts inside the evaluated skill are not
checked because that skill is not installed.

In the unreleased checkout, runtime `output_matches` checks use isolated Python
workers with a default 1-second limit per pattern and a shared 5-second matching
budget per case. A timeout or an exhausted matching budget counts as a failed
check and stays in the `behavior_check` denominator. Invalid-pattern errors
reported by a worker and worker startup failures remain not checked. Later
literal checks still run. Set
`SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC` and `SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC`
in the host environment to allow slower legitimate patterns; both accept
positive finite seconds. See [Output-pattern check limits](/skills/skillevaluator/environment-variables#output-pattern-check-limits).

For an exact final-response format, use an anchored `output_matches` check
and keep semantic requirements in `expected_behavior` (or `assertions`). For
example, this legacy entry checks numeric-only output without judging it:
Expand Down
136 changes: 131 additions & 5 deletions src/skillevaluator/tier3/eval_core/declarative_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@

from __future__ import annotations

import json
import os
import re
import subprocess
import sys
from math import isfinite
from pathlib import Path
from queue import Empty, Queue
from threading import TIMEOUT_MAX, Thread
from typing import Any

if __package__:
Expand All @@ -30,6 +37,121 @@
"output_contains",
)

_PATTERN_TIMEOUT_SECONDS = 1.0
_PATTERN_BUDGET_SECONDS = 5.0
_PATTERN_STARTUP_TIMEOUT_SECONDS = 10.0
_PATTERN_WORKER = """
import json
import re
import sys
from time import monotonic

pattern, text = json.load(sys.stdin)
print(json.dumps(["ready"]), flush=True)
started = monotonic()
try:
matched = re.search(pattern, text) is not None
except (re.error, RecursionError, OverflowError) as exc:
kind, detail = "error", str(exc)
else:
kind, detail = "match" if matched else "no_match", None
elapsed = monotonic() - started
print(json.dumps([kind, detail, elapsed]), flush=True)
"""


def _pattern_worker_messages(worker: subprocess.Popen[str], payload: str, messages: Queue[str | None]) -> None:
try:
with worker.stdin:
worker.stdin.write(payload)
for line in worker.stdout:
messages.put(line)
except (OSError, UnicodeError, ValueError):
pass
finally:
messages.put(None)


def _pattern_limit(name: str, default: float) -> float:
try:
value = float(os.environ.get(name, ""))
except ValueError:
return default
if not isfinite(value) or value <= 0:
return default
# Queue.get uses a platform lock timeout, which can overflow even for a
# finite Python float. Keep every configured wait within its supported range.
return min(value, TIMEOUT_MAX)


def _output_pattern_matches(
pattern: str, text: str, budget: list[float], timeout_seconds: float
) -> tuple[bool | None, str | None]:
"""Keep Python re semantics while bounding a pattern's compilation and matching."""
timeout = min(timeout_seconds, budget[0])
if timeout <= 0:
return False, "the regular expression time budget was exhausted"
if not sys.executable:
return None, "the regular expression worker could not be started"
timeout_reason = (
"the regular expression time budget was exhausted"
if budget[0] < timeout_seconds
else "the regular expression timed out"
)
try:
with subprocess.Popen(
[sys.executable, "-I", "-c", _PATTERN_WORKER],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="ascii",
) as worker:
messages: Queue[str | None] = Queue()
reader = Thread(target=_pattern_worker_messages, args=(worker, json.dumps([pattern, text]), messages))
try:
reader.start()
try:
ready = messages.get(timeout=_PATTERN_STARTUP_TIMEOUT_SECONDS)
except Empty:
return None, "the regular expression worker did not become ready"
if ready != '["ready"]\n':
return None, "the regular expression worker returned an invalid result"
try:
output = messages.get(timeout=timeout)
except Empty:
budget[0] -= timeout
return False, timeout_reason
try:
worker.wait(timeout=_PATTERN_STARTUP_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
return None, "the regular expression worker failed"
if worker.returncode != 0:
return None, "the regular expression worker failed"
finally:
if worker.poll() is None:
worker.kill()
worker.wait()
if reader.ident is not None:
reader.join()
except (OSError, RuntimeError):
return None, "the regular expression worker could not be started"
try:
kind, detail, elapsed = json.loads(output) if output is not None else []
if type(elapsed) not in (int, float) or not isfinite(elapsed) or elapsed < 0:
raise ValueError("invalid worker duration")
except (ValueError, TypeError, OverflowError):
return None, "the regular expression worker returned an invalid result"
budget[0] -= elapsed
if elapsed > timeout:
return False, timeout_reason
if kind == "match" and detail is None:
return True, None
if kind == "no_match" and detail is None:
return False, None
if kind == "error" and isinstance(detail, str):
return None, "it is not a valid regular expression: " + detail
return None, "the regular expression worker returned an invalid result"


def validate_declarative_checks(value: object) -> list[str]:
if not isinstance(value, list):
Expand Down Expand Up @@ -181,6 +303,8 @@ def evaluate_declarative_checks(
results = []
if not isinstance(checks, list):
return results
pattern_timeout = _pattern_limit("SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC", _PATTERN_TIMEOUT_SECONDS)
pattern_budget = [_pattern_limit("SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC", _PATTERN_BUDGET_SECONDS)]
for check in checks:
if not isinstance(check, dict):
results.append({"type": None, "passed": None, "reason": "Declarative check must be an object"})
Expand Down Expand Up @@ -245,11 +369,13 @@ def evaluate_declarative_checks(
)
elif check_type == "output_matches":
expected = check.get("pattern", "")
try:
passed = re.search(str(expected), final_response) is not None
except re.error as exc:
passed = None
reason = f"Could not check output pattern because it is not a valid regular expression: {exc}"
passed, problem = _output_pattern_matches(str(expected), final_response, pattern_budget, pattern_timeout)
if problem is not None:
reason = (
f"Output pattern failed because {problem}"
if passed is False
else f"Could not check output pattern because {problem}"
)
else:
reason = (
f"Final response matches /{expected}/"
Expand Down
2 changes: 2 additions & 0 deletions src/skillevaluator/tier3/harbor/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,8 @@
"SKILL_EVAL_BEHAVIOR_CHECK_BUDGET",
"SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT",
"SKILL_EVAL_GOAL_ACCURACY_BUDGET",
"SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC",
"SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC",
}
)
_VERIFIER_RETRY_ENV_VARS = frozenset(
Expand Down
12 changes: 10 additions & 2 deletions tests/test_harbor_runner_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ def test_provider_environment_forwards_each_host_judge_model_override(
"SKILL_EVAL_LLM_MAX_RETRIES",
"SKILL_EVAL_LLM_RETRY_BASE_DELAY",
"SKILL_EVAL_LLM_RETRY_MAX_DELAY",
"SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC",
"SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC",
],
)
@pytest.mark.parametrize("provider_name", ["openai", "openai-compatible", "anthropic", "bedrock", "nv_build"])
Expand All @@ -334,14 +336,14 @@ def test_provider_environment_forwards_each_host_judge_model_override(
(" ", None),
],
)
def test_provider_environment_forwards_each_host_retry_override(
def test_provider_environment_forwards_each_host_retry_or_pattern_limit_override(
monkeypatch: pytest.MonkeyPatch,
name: str,
provider_name: str,
configured: str,
expected: str | None,
) -> None:
"""Verify _provider_environment forwards stripped host retry settings and omits blank values."""
"""Forward stripped host retry and pattern limits, omitting blank values."""
monkeypatch.setattr(runner.os, "environ", {name: configured})

environment = runner._provider_environment(_provider(provider_name))
Expand All @@ -361,6 +363,8 @@ def test_resolve_agent_runtime_plan_retains_retry_settings_in_subprocess_env(
"SKILL_EVAL_LLM_MAX_RETRIES": "0",
"SKILL_EVAL_LLM_RETRY_BASE_DELAY": "0.1",
"SKILL_EVAL_LLM_RETRY_MAX_DELAY": "0.5",
"SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC": "3.0",
"SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC": "8.0",
},
)

Expand All @@ -376,7 +380,11 @@ def test_resolve_agent_runtime_plan_retains_retry_settings_in_subprocess_env(
assert subprocess_env["SKILL_EVAL_LLM_MAX_RETRIES"] == "0"
assert subprocess_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "0.1"
assert subprocess_env["SKILL_EVAL_LLM_RETRY_MAX_DELAY"] == "0.5"
assert subprocess_env["SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC"] == "3.0"
assert subprocess_env["SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC"] == "8.0"
assert "SKILL_EVAL_LLM_MAX_RETRIES" not in plans["codex"].staged_env
assert "SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC" not in plans["codex"].staged_env
assert "SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC" not in plans["codex"].staged_env


@pytest.mark.parametrize("source_name", ["LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"])
Expand Down
8 changes: 6 additions & 2 deletions tests/test_tier3_public_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -2801,14 +2801,16 @@ def test_generate_harbor_tasks_dual_arm_suffix(tmp_path: Path) -> None:
)


def test_write_task_toml_forwards_retry_env(tmp_path: Path) -> None:
"""Verify that _write_task_toml stages LLM retry variables into [verifier.env]."""
def test_write_task_toml_forwards_retry_and_pattern_limits_env(tmp_path: Path) -> None:
"""Stage evaluator retry and pattern limits through the verifier environment."""
case_dir = tmp_path / "case"
case_dir.mkdir()
runtime_env = {
"SKILL_EVAL_LLM_MAX_RETRIES": "5",
"SKILL_EVAL_LLM_RETRY_BASE_DELAY": "2.0",
"SKILL_EVAL_LLM_RETRY_MAX_DELAY": "40.0",
"SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC": "3.0",
"SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC": "8.0",
"UNRELATED_CUSTOM_VAR": "secret",
}
_write_task_toml(
Expand All @@ -2822,6 +2824,8 @@ def test_write_task_toml_forwards_retry_env(tmp_path: Path) -> None:
assert verifier_env["SKILL_EVAL_LLM_MAX_RETRIES"] == "${SKILL_EVAL_LLM_MAX_RETRIES}"
assert verifier_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "${SKILL_EVAL_LLM_RETRY_BASE_DELAY}"
assert verifier_env["SKILL_EVAL_LLM_RETRY_MAX_DELAY"] == "${SKILL_EVAL_LLM_RETRY_MAX_DELAY}"
assert verifier_env["SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC"] == "${SKILL_EVAL_OUTPUT_PATTERN_TIMEOUT_SEC}"
assert verifier_env["SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC"] == "${SKILL_EVAL_OUTPUT_PATTERN_BUDGET_SEC}"
assert "UNRELATED_CUSTOM_VAR" not in verifier_env


Expand Down
Loading
Loading