Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,8 @@ All notable changes to SkillEvaluator are documented in this file.

### Fixed

- Bound declarative output-pattern checks with isolated Python regex workers and a shared time budget, so pathological patterns remain unscored without stalling other checks or changing regex semantics.

- GitLab JUnit collection includes nested skill folders in catalog reports.
- API caller now percent-encodes scalar OpenAPI path values as individual segments and rejects `.` and `..` values with a JSON input error.
- Direct Tier 1 validates the target, selected checks and LLM configuration before
Expand Down
61 changes: 56 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,12 @@

from __future__ import annotations

import json
import re
import subprocess
import sys
from pathlib import Path
from time import monotonic
from typing import Any

if __package__:
Expand All @@ -30,6 +34,54 @@
"output_contains",
)

_PATTERN_TIMEOUT_SECONDS = 1.0
_PATTERN_BUDGET_SECONDS = 5.0
_PATTERN_WORKER = """
import json
import re
import sys

pattern, text = json.load(sys.stdin)
try:
matched = re.search(pattern, text) is not None
except (re.error, RecursionError, OverflowError) as exc:
print("error:" + str(exc))
else:
print("match" if matched else "no_match")
"""


def _output_pattern_matches(pattern: str, text: str, budget: list[float]) -> tuple[bool | None, str | None]:
"""Keep Python re semantics while bounding a pattern's compilation and matching."""
timeout = min(_PATTERN_TIMEOUT_SECONDS, budget[0])
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
if timeout <= 0:
return None, "the regular expression time budget was exhausted"
started = monotonic()
try:
result = subprocess.run(
[sys.executable, "-I", "-c", _PATTERN_WORKER],
input=json.dumps([pattern, text]),
capture_output=True,
encoding="utf-8",
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return None, "the regular expression timed out"
except OSError:
return None, "the regular expression worker could not be started"
finally:
budget[0] -= max(0.0, monotonic() - started)
if result.returncode != 0:
return None, "the regular expression worker failed"
if result.stdout == "match\n":
return True, None
if result.stdout == "no_match\n":
return False, None
if result.stdout.startswith("error:"):
return None, "it is not a valid regular expression: " + result.stdout.removeprefix("error:").strip()
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 +233,7 @@ def evaluate_declarative_checks(
results = []
if not isinstance(checks, list):
return results
pattern_budget = [_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 +298,9 @@ 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)
if problem is not None:
reason = f"Could not check output pattern because {problem}"
else:
reason = (
f"Final response matches /{expected}/"
Expand Down
70 changes: 68 additions & 2 deletions tests/tier3/test_declarative_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# SPDX-License-Identifier: Apache-2.0

import importlib.util
import json
import subprocess
import sys
from pathlib import Path

import pytest
Expand Down Expand Up @@ -128,6 +131,68 @@ def test_final_response_checks_match_contains_and_regex():
assert _evaluate({"type": "output_matches", "pattern": r"Report \d+"}, response="No report")["passed"] is False


@pytest.mark.parametrize(
("pattern", "response", "expected"),
[
(r"^\w+$", "e\u0301", False),
(r"^\w+$", "a\u200d", False),
(r"^\s$", "\x1c", True),
(r"^(a)\1$", "aa", True),
(r"^(a)\1$", "ab", False),
(r"(?<=a)b", "ab", True),
(r"(?i:ready)", "READY", True),
(r"^ready$", "ready\n", True),
],
)
def test_output_patterns_keep_python_regex_semantics(pattern, response, expected):
result = _evaluate({"type": "output_matches", "pattern": pattern}, response=response)
assert result["passed"] is expected


def test_backtracking_pattern_has_a_shared_deadline_and_other_checks_continue():
script = """
import json
from skillevaluator.tier3.eval_core import declarative_checks as checks
checks._PATTERN_TIMEOUT_SECONDS = 0.05
checks._PATTERN_BUDGET_SECONDS = 0.05
results = checks.evaluate_declarative_checks(
[
{"type": "output_matches", "pattern": "^(a|aa)+$"},
{"type": "output_matches", "pattern": "a"},
{"type": "output_contains", "text": "!"},
],
tool_calls=[], final_response="a" * 100 + "!", workspace_roots=[],
)
print(json.dumps(results))
"""
# The outer bound also prevents an unfixed implementation from hanging the suite.
completed = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=True, timeout=5)
timed_out, exhausted, literal = json.loads(completed.stdout)
assert timed_out["passed"] is None
assert "timed out" in timed_out["reason"]
assert exhausted["passed"] is None
assert "budget was exhausted" in exhausted["reason"]
assert literal["passed"] is True


def test_deep_pattern_compilation_is_not_checked_instead_of_aborting_evaluation():
result = _evaluate({"type": "output_matches", "pattern": "(" * 2000}, response="ready")
assert result["passed"] is None
assert "not a valid regular expression" in result["reason"]


def test_pattern_worker_failure_cannot_become_a_match(monkeypatch):
from skillevaluator.tier3.eval_core import declarative_checks

def unavailable_worker(*args, **kwargs):
raise OSError("worker unavailable")

monkeypatch.setattr(declarative_checks.subprocess, "run", unavailable_worker)
result = _evaluate({"type": "output_matches", "pattern": "ready"}, response="ready")
assert result["passed"] is None
assert "worker could not be started" in result["reason"]


def test_runtime_invalid_regex_and_unknown_check_are_not_checked():
invalid_regex = _evaluate({"type": "output_matches", "pattern": "["}, response="ready")
unknown = _evaluate({"type": "made_up", "value": "x"})
Expand Down Expand Up @@ -313,11 +378,12 @@ def test_standalone_bundle_stages_and_imports_the_shared_helper(tmp_path: Path,
spec.loader.exec_module(staged)

result = staged.evaluate_declarative_checks(
[{"type": "output_contains", "text": "ready"}],
[{"type": "output_contains", "text": "ready"}, {"type": "output_matches", "pattern": r"ready\s$"}],
tool_calls=[],
final_response="ready",
final_response="ready\x1c",
workspace_roots=[],
)

assert helper_path.is_file()
assert result[0]["passed"] is True
assert result[1]["passed"] is True
Loading