Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,11 @@ All notable changes to SkillEvaluator are documented in this file.
`SKILLEVALUATOR_SKILLSPECTOR_PATH` although no override was set.
- The comments-only consumer template now grants its required read and PR-comment
permissions only to the comment job, with no workflow-wide token permissions.
- Ctrl-C during a reusable Tier 1 workflow run is no longer missed when it
arrives while a scan is starting. The runner waited for scan results with no
time limit, and on Linux the interrupt could be handled on a scan thread,
which did not wake that wait; the run then went on until a scan ended. The
runner now checks for the interrupt every 0.1 seconds.
- The behavior evidence gate no longer keeps a score for an expectation that
names an observed artifact but also asks for something only the final answer
could show. "Writes `report.py` and explains why each column was dropped" was
Expand Down
7 changes: 6 additions & 1 deletion ci/run_tier1.py
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,12 @@ def flush_logs(*, final: bool = False) -> None:
live.append(thread)
running += 1
while running:
batch = [events.get()]
try:
batch = [events.get(timeout=POLL_SECONDS)]
except queue.Empty:
# Ctrl-C is acted on in this thread, but its signal handler can run on a
# scan thread, and that does not interrupt a wait without a time limit.
continue
while True:
try:
batch.append(events.get_nowait())
Expand Down
45 changes: 43 additions & 2 deletions tests/ci/test_run_tier1.py
Original file line number Diff line number Diff line change
Expand Up @@ -1546,8 +1546,14 @@ def test_scan_timeout_also_ends_the_scanner_tools(tmp_path, monkeypatch):
path = scan_shim(tmp_path)
output = tmp_path / "out"
output.mkdir()
clock = types.SimpleNamespace(offset=0.0)
clock.monotonic = lambda: time.monotonic() + clock.offset
clock = types.SimpleNamespace(offset=0.0, read=threading.Event())

def monotonic():
now = time.monotonic() + clock.offset
clock.read.set()
return now

clock.monotonic = monotonic
monkeypatch.setattr(runner, "time", clock)
outcome = {}

Expand All @@ -1568,6 +1574,10 @@ def scan():
thread.start()
pids = survivors = scan_pids(output, time.monotonic() + WAIT)
try:
# The scan sets its time limit after it starts the evaluator, which can write its
# PIDs first. Move the clock only once the scan has read it, or the limit moves too.
clock.read.clear()
assert clock.read.wait(WAIT), "the scan did not read the clock"
clock.offset = WAIT
thread.join(WAIT)
assert not thread.is_alive() and "error" in outcome
Expand Down Expand Up @@ -1719,6 +1729,37 @@ def test_second_ctrl_c_does_not_leave_the_runner_waiting(tmp_path):
kill_quietly(survivors)


@pytest.mark.skipif(not hasattr(signal, "pthread_kill"), reason="sends a signal to one thread")
def test_ctrl_c_handled_on_a_scan_thread_still_ends_the_run(tmp_path, monkeypatch):
# Python acts on Ctrl-C in the main thread, but the system can run the signal handler on
# another one. Linux hands a waiting SIGINT to a thread that unblocks signals, as a scan
# thread does when it starts an evaluator. That does not wake a main thread that waits
# for scan events without a time limit, so the run would go on until a scan ended.
workspace = tmp_path / "workspace"
skill(workspace, "skills/a")
waits, aborted = threading.Semaphore(0), []

class Events(runner.queue.SimpleQueue):
def get(self, *args, **kwargs):
waits.release()
return super().get(*args, **kwargs)

def run_scan(argv, *, abort, **options):
# A busy main thread acts on any signal, and this scan's start event ends its first
# wait when that wait has no time limit. Signal once it has started a second wait.
for _ in range(2):
waits.acquire(timeout=WAIT)
signal.pthread_kill(threading.get_ident(), signal.SIGINT)
aborted.append(abort.wait(WAIT))
return CompletedProcess(argv, 1)

monkeypatch.setattr(runner, "queue", types.SimpleNamespace(SimpleQueue=Events, Empty=runner.queue.Empty))
monkeypatch.setattr(runner, "run_scan", run_scan)
with pytest.raises(KeyboardInterrupt):
runner.run(workspace, tmp_path / "reports", {})
assert aborted == [True]


def test_each_report_is_released_once_its_result_is_logged(tmp_path, monkeypatch):
# Reports can be 32 MiB each; 100 of them must not stay in memory.
workspace = tmp_path / "workspace"
Expand Down
91 changes: 76 additions & 15 deletions tests/test_harbor_local_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import logging
import os
import re
import selectors
import shlex
import signal
import socket
Expand Down Expand Up @@ -161,6 +162,57 @@ def _initialized_local_environment(
)


def _assert_process_exits(pid: int, *, timeout: float = 5.0) -> None:
"""Assert that a process signalled by cleanup leaves the process table.

Cleanup returns once its group probe finds no live member. On macOS that
probe reports EPERM while a SIGKILLed descendant is still finishing its
exit, and until then ``kill(pid, 0)`` still succeeds for that PID. A single
immediate probe races that teardown, so allow bounded exit completion.

This polls without yielding to the event loop, so cleanup cannot run in the
meantime: a descendant it never signalled is still alive at the deadline.
"""
deadline = time.monotonic() + timeout
while True:
try:
os.kill(pid, 0)
except ProcessLookupError:
return
assert time.monotonic() < deadline, "a descendant survived process-group cleanup"
time.sleep(0.01)


class _ManualClockSelector(selectors.DefaultSelector):
"""Advance a manual clock by each requested wait instead of sleeping."""

def __init__(self) -> None:
super().__init__()
self.now = 0.0

def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
if timeout is None:
return super().select(None)
self.now += max(timeout, 0.0)
return super().select(0)


class _ManualClockEventLoop(asyncio.SelectorEventLoop):
"""Event loop whose timers elapse on a manual clock instead of the host's.

Time advances only by the delay the loop asked to wait for, so a bound on
timer-driven code counts the timeouts that code requested and not how long
a loaded host descheduled the loop.
"""

def __init__(self) -> None:
self._manual_clock = _ManualClockSelector()
super().__init__(self._manual_clock)

def time(self) -> float:
return self._manual_clock.now


def _provider(name: str, *, api_key: str = "k", base_url: str | None = None) -> ProviderConfig:
return ProviderConfig(provider=name, model="m", api_key=api_key, base_url=base_url, litellm_model="m", region=None)

Expand Down Expand Up @@ -282,8 +334,7 @@ async def exercise() -> None:
assert processes[0].returncode is not None
assert child_pid_path.is_file()
child_pid = int(child_pid_path.read_text(encoding="ascii"))
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
_assert_process_exits(child_pid)
assert len("".join(callback_chunks).encode()) <= 8
assert overflow_value not in "".join(callback_chunks)
assert overflow_value not in str(caught.value)
Expand Down Expand Up @@ -2840,8 +2891,7 @@ async def exercise() -> object:
)
assert secret not in callback_stdout
child_pid = int(child_pid_path.read_text(encoding="ascii"))
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
_assert_process_exits(child_pid)


@pytest.mark.skipif(os.name != "posix", reason=_NATIVE_WINDOWS_LOCAL_REASON)
Expand Down Expand Up @@ -3184,7 +3234,9 @@ def test_exec_cancellation_terminates_background_descendants(tmp_path: Path) ->
# An interrupted sleep must not itself count as a surviving child.
"(printf ready > cancel-child-ready; sleep 30 && "
"printf survived > cancel-child-survived) & "
"printf '%s' \"$!\" > cancel-child-pid; wait"
# Existence signals readiness, so publish only the complete PID.
"printf '%s' \"$!\" > cancel-child-pid.tmp && "
"mv cancel-child-pid.tmp cancel-child-pid; wait"
)
environment._local_command_guardrail_reason = lambda *_args: "" # type: ignore[method-assign]

Expand Down Expand Up @@ -3275,8 +3327,7 @@ async def exercise() -> int:

assert callback_chunks
assert secret not in "".join(callback_chunks)
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
_assert_process_exits(child_pid)


@pytest.mark.skipif(os.name != "posix", reason=_NATIVE_WINDOWS_LOCAL_REASON)
Expand Down Expand Up @@ -3308,8 +3359,8 @@ async def exercise() -> int:
assert child_pid_path.exists()
assert not environment._active_processes
child_pid = int(child_pid_path.read_text(encoding="ascii"))
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
# The final callback is still blocked, so containment came first.
_assert_process_exits(child_pid)
task.cancel()
if repeat_cancellation:
await asyncio.sleep(0)
Expand All @@ -3321,8 +3372,7 @@ async def exercise() -> int:
child_pid: int | None = None
try:
child_pid = asyncio.run(exercise())
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
_assert_process_exits(child_pid)
finally:
if child_pid is None and child_pid_path.exists():
child_pid = int(child_pid_path.read_text(encoding="ascii"))
Expand All @@ -3340,17 +3390,27 @@ def test_cancellation_during_timeout_reap_preserves_cancellation_and_containment
environment = _initialized_local_environment(tmp_path)
environment._local_command_guardrail_reason = lambda *_args: "" # type: ignore[method-assign]
child_pid_path = environment._workspace / "timeout-reap-cancel-child-pid"
child_pid_tmp_path = child_pid_path.with_name(f"{child_pid_path.name}.tmp")
reap_entered = asyncio.Event()
original_terminate = environment._terminate_process_tree
command = (
"(trap '' TERM; exec >/dev/null 2>&1; sleep 30) & "
f"printf '%s' \"$!\" > {shlex.quote(child_pid_path.name)}; wait"
# Existence signals readiness, so publish only the complete PID.
f"printf '%s' \"$!\" > {shlex.quote(child_pid_tmp_path.name)} && "
f"mv {shlex.quote(child_pid_tmp_path.name)} {shlex.quote(child_pid_path.name)}; wait"
)

async def observed_terminate(
proc: asyncio.subprocess.Process,
communication: asyncio.Task[tuple[bytes, bytes]] | None = None,
) -> tuple[bytes, bytes]:
# The exec timeout can expire before a loaded host has started the
# descendant. Hold the reap until its PID is published, so that the
# cancellation always interrupts the reap of a live descendant.
for _ in range(400):
if child_pid_path.exists():
break
await asyncio.sleep(0.01)
reap_entered.set()
return await original_terminate(proc, communication)

Expand Down Expand Up @@ -3383,8 +3443,7 @@ async def exercise() -> tuple[BaseException | None, int, bool]:
outcome, child_pid, retained = asyncio.run(exercise())
assert isinstance(outcome, asyncio.CancelledError)
assert not retained
with pytest.raises(ProcessLookupError):
os.kill(child_pid, 0)
_assert_process_exits(child_pid)
finally:
if child_pid is None and child_pid_path.exists():
child_pid = int(child_pid_path.read_text(encoding="ascii"))
Expand Down Expand Up @@ -3664,7 +3723,9 @@ class FakeProcess:
await cleanup
return finished_within_bound, communication.cancelled()

assert asyncio.run(run_cleanup()) == (True, True)
# On the manual clock the 0.1s bound counts only the waits that cleanup
# asked for, not the time a loaded host keeps the event loop descheduled.
assert asyncio.run(run_cleanup(), loop_factory=_ManualClockEventLoop) == (True, True)


def test_stop_reaps_all_tracked_processes(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
Expand Down
35 changes: 33 additions & 2 deletions tests/test_harbor_secure_docker_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from skillevaluator.tier3.harbor.runner import build_harbor_run_command
from skillevaluator.tier3.harbor.secure_docker_environment import (
_REDACTION_SENTINEL_CANDIDATES,
_SENSITIVE_ENV_NAME_RE,
NVIDIA_BUILD_STDIN_SENTINEL,
SECURE_DOCKER_ENV_IMPORT_PATH,
SkillEvaluatorDockerEnvironment,
Expand All @@ -51,6 +52,7 @@
)
from skillevaluator.tier3.harbor.sensitive_stdin import NVIDIA_BUILD_KEY_STDIN_ENV
from skillevaluator.tier3.harbor.stream_redaction import CommandOutputLimitError
from skillevaluator.tier3.output_provenance import OUTPUT_PROVENANCE_KEY_ENV

_SENTINEL = "sentinel-never-visible-in-argv-or-files"

Expand Down Expand Up @@ -96,6 +98,17 @@ def _initialized_secure_docker_environment(
)


def _isolate_host_sensitive_environment(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep the sidecar Compose check away from sensitive-named variables of the host shell."""
# The check protects the value of every sensitive-named host variable, whatever its
# length, so an ambient ``SOME_SESSION=1`` would decide whether a fixture value such as
# ``127.0.0.1`` is retained. Call this before setting the variables the test controls.
for name in list(os.environ):
# conftest points the provenance key at tmp_path; leave that isolation in place.
if name != OUTPUT_PROVENANCE_KEY_ENV and _SENSITIVE_ENV_NAME_RE.search(name):
monkeypatch.delenv(name)


class _BufferedComposeProcess:
pid = 8841

Expand Down Expand Up @@ -897,6 +910,22 @@ async def heartbeat() -> None:
assert asyncio.run(exercise()) < 1.0


def _single_secret_scan_seconds(text: str) -> float:
"""Return how long this interpreter takes to redact ``text`` with one secret.

Coverage tracing slows the pure-Python scan several times over. Nested-secret
time bounds therefore fall back to a multiple of this linear baseline: tracing
scales both alike, while a scan that grows with the nested secrets does not.

Linear matching of the 1,000 nested secrets used below costs about two of these
scans (the extra is mostly building the trie), so ten leaves room for noise.
Walking every nested match at each position costs more than twenty.
"""
started = time.perf_counter()
_redact(text, {"a" * 8})
return time.perf_counter() - started


def test_streaming_redactor_nested_terminal_matching_work_is_linear() -> None:
secrets = {"a" * length for length in range(8, 1008)}
text = "a" * 20_000
Expand All @@ -905,7 +934,7 @@ def test_streaming_redactor_nested_terminal_matching_work_is_linear() -> None:

output = redactor.feed(text) + redactor.finish()
elapsed = time.perf_counter() - started
assert elapsed < 1.0
assert elapsed < 1.0 or elapsed < 10 * _single_secret_scan_seconds(text)
assert output == _collision_safe_redaction_marker(secrets)
assert redactor.match_work_count <= 10 * len(text)

Expand Down Expand Up @@ -989,7 +1018,7 @@ async def heartbeat() -> None:

expected = _collision_safe_redaction_marker({"a" * length for length in range(8, 1008)})
assert "".join(callback_chunks) == result.stdout == expected
assert maximum_gap < 1.0
assert maximum_gap < 1.0 or maximum_gap < 10 * _single_secret_scan_seconds("a" * 20_000)


def _reference_union_redaction(text: str, secrets: set[str]) -> str:
Expand Down Expand Up @@ -2682,6 +2711,7 @@ def test_sidecar_retains_only_structurally_required_nonsecret_compose_task_value
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_isolate_host_sensitive_environment(monkeypatch)
environment = _initialized_secure_docker_environment(tmp_path)
compose_path = environment.environment_dir / "docker-compose.yaml"
compose_path.write_text(
Expand Down Expand Up @@ -2946,6 +2976,7 @@ def test_sidecar_retains_structurally_required_nonsecret_host_compose_value(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_isolate_host_sensitive_environment(monkeypatch)
environment = _initialized_secure_docker_environment(tmp_path)
compose_path = environment.environment_dir / "docker-compose.yaml"
compose_path.write_text(
Expand Down
12 changes: 7 additions & 5 deletions tests/test_model_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ def fake_urlopen(_request, **_kwargs):


def test_catalog_body_trickle_cannot_extend_the_wall_clock_deadline() -> None:
payload = json.dumps({"data": [{"id": "slow-model"}]}).encode()
# 400 bytes, one every 25ms: a client that waits for the whole body needs 10 seconds.
payload = json.dumps({"data": [{"id": "slow-model"}]}).encode().ljust(400)

class SlowBodyHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
Expand Down Expand Up @@ -248,10 +249,11 @@ def log_message(self, *_args) -> None:
server.shutdown()
thread.join(timeout=2)

# The old single response.read() waited for the complete slow body (~0.9s).
# Allow ample scheduler jitter while still proving the configured deadline is
# wall-clock bounded rather than reset by each arriving byte.
assert elapsed < 0.5
# The old single response.read() waited for the complete slow body (10s here),
# because every arriving byte reset the socket timeout. The bound stays far from
# both that and the 0.15s deadline: a stalled CI runner has needed 0.86s, and
# must not look like a body that extended the deadline.
assert elapsed < 5.0


def test_catalog_dns_resolution_cannot_extend_the_wall_clock_deadline(monkeypatch) -> None:
Expand Down
Loading
Loading