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
8 changes: 6 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,12 @@ pytest subprocesses and import handling, including fixtures, parametrized tests,
package metadata, and instrumentation in spawned child processes. Trailmark
checks the clean baseline and each distinct instrumented test ordering before
mutating, skips the redundant coverage pre-scan, preserves exact parameter IDs,
and rejects skipped instrumentation. Performance regressions should use
deterministic work bounds rather than wall-clock thresholds in the mutation suite.
and rejects skipped instrumentation. Tests use deterministic work bounds rather
than wall-clock thresholds. The test suite has no elapsed-time assertions,
pytest timeout markers, or test subprocess deadlines. Hypothesis deadlines and
its generation-speed health check are disabled. Test product timeout behavior
with a simulated clock and process; keep optional wall-clock measurements in
`tests/benchmark_analysis.py` or `tests/smoke_binary_projects.py`.
The adapter uses private plugin APIs; its control tests must pass before upgrading
the plugin.

Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ dev = [
"pytest>=9.2.0",
"pytest-cov>=7.1.0",
"ruff>=0.17.6,<1.0",
"pytest-timeout>=2.4,<3",
"ty>=0.0.107,<0.1",
]

Expand Down
2 changes: 1 addition & 1 deletion tests/binary_oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def offset(self, address: int) -> int:


def _run(command: list[str]) -> str:
return subprocess.run(command, check=True, capture_output=True, text=True, timeout=30).stdout # noqa: S603
return subprocess.run(command, check=True, capture_output=True, text=True).stdout # noqa: S603


def _field(body: str, name: str) -> int:
Expand Down
14 changes: 4 additions & 10 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
import os

import pytest
from hypothesis import HealthCheck, settings

settings.register_profile("trailmark", deadline=None, suppress_health_check=[HealthCheck.too_slow])
settings.load_profile("trailmark")


def pytest_sessionstart(session: pytest.Session) -> None:
Expand All @@ -15,13 +19,3 @@ def pytest_sessionstart(session: pytest.Session) -> None:
or "PYTEST_GREMLINS_SOURCES_FILE" in os.environ
):
raise pytest.UsageError("Snapshot updates are disabled in CI and mutation testing")


@pytest.fixture(scope="session")
def compiled_verus() -> None:
"""Compile outside tests that bound parser traversal time."""
from tree_sitter import Language

from trailmark.tree_sitter_custom.verus import language

Language(language())
36 changes: 36 additions & 0 deletions tests/parse_work.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Deterministic Python work counts for parser scaling regressions."""

import sys
from collections.abc import Callable
from pathlib import Path
from types import FrameType

from trailmark.models import CodeGraph
from trailmark.parse import parse_file

type _Trace = Callable[[FrameType, str, object], _Trace | None]


def parse_work(path: Path) -> tuple[CodeGraph, int]:
"""Count parser line events, including code instrumented in temporary files.

This measures Python traversal work; native grammar execution is excluded.
"""
work = 0

def count(frame: FrameType, event: str, argument: object) -> _Trace:
nonlocal work
if event == "line":
work += 1
return count

def select(frame: FrameType, event: str, argument: object) -> _Trace | None:
return count if frame.f_globals.get("__name__", "").startswith("trailmark.") else None

previous = sys.gettrace()
try:
sys.settrace(select)
graph = parse_file(str(path))
finally:
sys.settrace(previous)
return graph, work
92 changes: 71 additions & 21 deletions tests/test_binary_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
from __future__ import annotations

import json
import sys
import time
from dataclasses import FrozenInstanceError, replace
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock

import pytest

from trailmark.analysis.native_binary import _restore_functions
from trailmark.analysis.native_binary import _restore_functions, tools
from trailmark.analysis.native_binary.decoder import _tail_calls
from trailmark.analysis.native_binary.formats import Function, Image, Span, Target
from trailmark.analysis.native_binary.mapping import SourceResolver
Expand Down Expand Up @@ -428,27 +428,79 @@ def test_import_options_reject_mutable_or_unsupported_configuration() -> None:
BinaryImportOptions(limits=None) # ty: ignore[invalid-argument-type]


def test_host_tool_output_budget_counts_both_pipes() -> None:
def _host_process(monkeypatch: pytest.MonkeyPatch) -> tuple[Mock, MagicMock]:
"""Model ready pipes and process cleanup without waiting for a real child."""
process = Mock(stdout=Mock(), stderr=Mock(), returncode=None)
process.poll.side_effect = lambda: process.returncode

def wait(timeout: float | None = None) -> int:
process.returncode = -9
return -9

process.wait.side_effect = wait
selector = MagicMock()
selector.__enter__.return_value = selector
selector.get_map.return_value = True
monkeypatch.setattr(tools.subprocess, "Popen", Mock(return_value=process))
monkeypatch.setattr(tools.selectors, "DefaultSelector", lambda: selector)
monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic=lambda: 0.0))
return process, selector


def test_host_tool_output_budget_counts_both_pipes(monkeypatch: pytest.MonkeyPatch) -> None:
process, selector = _host_process(monkeypatch)
keys = [
SimpleNamespace(fd=1, fileobj=process.stdout, data="stdout"),
SimpleNamespace(fd=2, fileobj=process.stderr, data="stderr"),
]
selector.select.side_effect = [[(key, 1) for key in keys]]
output = {1: b"a" * 100, 2: b"b" * 100}

def read(fd: int, size: int) -> bytes:
chunk, output[fd] = output[fd][:size], output[fd][size:]
return chunk

monkeypatch.setattr(tools.os, "read", read)
limits = BinaryLimits(max_output_bytes=128)
result = run_tool(
[sys.executable, "-c", "import os; os.write(1,b'a'*100); os.write(2,b'b'*100)"],
limits,
time.monotonic() + 5,
)
result = run_tool(["tool"], limits, 5.0)
assert result.diagnostic is not None
assert result.diagnostic.code == "output_limit"
assert len(result.stdout) + len(result.stderr) == 128
assert (result.stdout, result.stderr) == (b"a" * 100, b"b" * 28)
process.kill.assert_called_once()


def test_host_tool_timeout_terminates_the_process() -> None:
result = run_tool(
[sys.executable, "-c", "import time; time.sleep(20)"],
BinaryLimits(tool_timeout=0.05),
time.monotonic() + 5,
)
@pytest.mark.parametrize("stage", ["pipes", "wait"])
def test_host_tool_timeout_terminates_the_process(
monkeypatch: pytest.MonkeyPatch, stage: str
) -> None:
process, selector = _host_process(monkeypatch)
if stage == "pipes":
clock = iter((0.0, 0.0, 1.0, 1.0))
monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic=lambda: next(clock)))
else:
selector.get_map.side_effect = [True, False]
selector.select.return_value = [
(SimpleNamespace(fd=1, fileobj=process.stdout, data="stdout"), 1),
(SimpleNamespace(fd=2, fileobj=process.stderr, data="stderr"), 1),
]
monkeypatch.setattr(tools.os, "read", lambda *_: b"")

def timed_wait(timeout: float | None = None) -> int:
if timeout is not None:
raise tools.subprocess.TimeoutExpired("tool", timeout)
process.returncode = -9
return -9

process.wait.side_effect = timed_wait
result = run_tool(["tool"], BinaryLimits(tool_timeout=0.05), 5.0)
assert result.diagnostic is not None
assert result.diagnostic.code == "timeout"
assert result.returncode != 0
assert result.returncode == -9
process.kill.assert_called_once()
assert process.wait.call_count == (1 if stage == "pipes" else 2)
process.stdout.close.assert_called_once()
process.stderr.close.assert_called_once()
assert selector.select.call_count == (0 if stage == "pipes" else 1)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -524,8 +576,6 @@ def test_empty_store_queries_need_no_native_dependency() -> None:
def test_automatic_tools_prefer_compatible_llvm_even_named_objdump(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from trailmark.analysis.native_binary import tools

tools_by_name = {
"llvm-objdump": tools.Tool("/llvm", "llvm", "LLVM", " x86 - 32-bit X86\n"),
"objdump": tools.Tool("/apple", "llvm", "Apple LLVM", " systemz - SystemZ\n"),
Expand All @@ -536,7 +586,7 @@ def test_automatic_tools_prefer_compatible_llvm_even_named_objdump(
monkeypatch.setattr(
tools, "run_tool", lambda *_: tools.ToolResult(b"elf64-s390\n s390:64-bit\n", b"", 0)
)
deadline = time.monotonic() + 10
deadline = 100.0
assert tools.select_objdump(BinaryImportOptions(), deadline, "s390x", "ELF").path == "/apple"
assert (
tools.select_objdump(BinaryImportOptions(backend="gnu"), deadline, "s390x", "ELF").path
Expand Down Expand Up @@ -573,4 +623,4 @@ def test_fifo_input_is_rejected_without_waiting(tmp_path: Path) -> None:
fifo = tmp_path / "fifo"
os.mkfifo(fifo)
with pytest.raises(ValueError, match="regular file"):
snapshot(fifo, tmp_path / "copy", time.monotonic() + 1)
snapshot(fifo, tmp_path / "copy", float("inf"))
1 change: 0 additions & 1 deletion tests/test_c_lookup_controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ def test_cyclic_repeated_guarded_includes_do_not_expand_the_lookup_work(tmp_path
capture_output=True,
text=True,
check=True,
timeout=10,
)
assert json.loads(result.stdout) == {
"functions": ["sample:action", "sample:helper"],
Expand Down
1 change: 0 additions & 1 deletion tests/test_c_macro_budgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ def test_whitespace_runs_in_many_declaration_macros_are_bounded(tmp_path: Path)
capture_output=True,
text=True,
check=True,
timeout=10,
)
assert json.loads(result.stdout) == {
"functions": sorted(["sample:helper", *(f"sample:action{i}" for i in range(60))]),
Expand Down
1 change: 0 additions & 1 deletion tests/test_c_spliced_trivia.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,6 @@ def test_unclosed_spliced_literal_reports_diagnostics_without_hanging(
[sys.executable, "-c", script, str(path)],
capture_output=True,
text=True,
timeout=10,
check=False,
)
assert result.returncode == 0, result.stderr
1 change: 0 additions & 1 deletion tests/test_c_unclosed_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ def test_many_unclosed_comment_openers_are_scanned_without_hanging() -> None:
[sys.executable, "-c", script],
capture_output=True,
text=True,
timeout=10,
check=False,
)
assert result.returncode == 0, result.stderr
Expand Down
4 changes: 1 addition & 3 deletions tests/test_cpp_declaration_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,7 @@ def test_standalone_template_prefix_preserves_method_owner(tmp_path: Path) -> No
def test_repeated_comments_without_template_do_not_stall(tmp_path: Path, suffix: str) -> None:
path = tmp_path / "sample.cpp"
path.write_text("#define API\nAPI\n" + "/**/" * 40 + "\n" + suffix)
# Keep the adversarial input isolated so an exponential-time regression
# fails promptly rather than hanging the entire parser suite.
# Isolate the native parser while checking the adversarial input's graph.
subprocess.run( # noqa: S603 -- Fixed interpreter and code; only a test path varies.
[
sys.executable,
Expand All @@ -222,7 +221,6 @@ def test_repeated_comments_without_template_do_not_stall(tmp_path: Path, suffix:
check=True,
capture_output=True,
text=True,
timeout=10,
)


Expand Down
1 change: 0 additions & 1 deletion tests/test_dafny_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,6 @@ def test_deep_generic_lookahead_is_bounded_in_native_scanner(tmp_path: Path) ->
],
check=True,
capture_output=True,
timeout=30,
)


Expand Down
2 changes: 1 addition & 1 deletion tests/test_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ def pyproject_data() -> dict[str, object]:
("CONTRIBUTING.md", "requires all eight shards to pass"),
("CONTRIBUTING.md", "inconclusive outcomes still fail the gate"),
("CONTRIBUTING.md", "pins pytest-gremlins 1.14.3"),
("CONTRIBUTING.md", "deterministic work bounds rather than wall-clock thresholds"),
("CONTRIBUTING.md", "pytest timeout markers, or test subprocess deadlines"),
# CLI output streams
("docs/cli.md", "`trailmark augment --json`"),
("docs/cli.md", "JSON to stdout"),
Expand Down
2 changes: 0 additions & 2 deletions tests/test_exception_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ def test_php_runtime_exposes_implicit_failure_paths_absent_from_direct_throw_met
capture_output=True,
text=True,
check=True,
timeout=10,
)
if int(version.stdout) < 70400:
pytest.skip("Throwing from __toString and __unserialize require PHP 7.4+")
Expand All @@ -33,7 +32,6 @@ def test_php_runtime_exposes_implicit_failure_paths_absent_from_direct_throw_met
capture_output=True,
text=True,
check=True,
timeout=10,
)
observed = json.loads(result.stdout)
assert observed["state"] == "changed"
Expand Down
1 change: 0 additions & 1 deletion tests/test_lean_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ def _targets(graph: CodeGraph, owner: str, kind: EdgeKind = EdgeKind.REFERENCES)
return [e.target_id for e in graph.edges if e.source_id == owner and e.kind == kind]


@pytest.mark.timeout(10)
@pytest.mark.parametrize("body", [" + ".join(["x"] * 3000), "[" + ", ".join(["x"] * 8000) + "]"])
def test_deep_and_wide_terms_keep_every_occurrence(tmp_path: Path, body: str) -> None:
graph = _parse(tmp_path, f"def x := 1\ndef big := {body}\n")
Expand Down
7 changes: 2 additions & 5 deletions tests/test_mutation_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def test_sharded_campaigns_match_complete_campaign(tmp_path: Path) -> None:
capture_output=True,
text=True,
check=False,
timeout=120,
)
assert result.returncode == 0, result.stdout + result.stderr
report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text())
Expand Down Expand Up @@ -232,9 +231,9 @@ def test_checked_only_in_child(tmp_path):
child = context.Process(target=evaluate, args=(queue,))
child.start()
try:
answer = queue.get(timeout=10)
child.join(timeout=10)
child.join()
assert child.exitcode == 0
answer = queue.get()
assert answer is True
finally:
if child.is_alive():
Expand All @@ -249,7 +248,6 @@ def test_checked_only_in_child(tmp_path):
capture_output=True,
text=True,
check=False,
timeout=120,
)
assert result.returncode == 0, result.stdout + result.stderr
report = json.loads((tmp_path / "coverage/gremlins/gremlins.json").read_text())
Expand Down Expand Up @@ -295,7 +293,6 @@ def test_runner_rejects_skipped_instrumentation(
capture_output=True,
text=True,
check=False,
timeout=120,
)
assert result.returncode != 0
assert "Mutation instrumentation skipped files" in result.stdout + result.stderr
Expand Down
1 change: 0 additions & 1 deletion tests/test_native_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,6 @@ def test_exception_metadata_does_not_imply_recovered_exception_dispatch(tmp_path
],
capture_output=True,
check=True,
timeout=60,
)
binary = lief_module().parse(str(image))
assert binary is not None
Expand Down
2 changes: 0 additions & 2 deletions tests/test_native_stability.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ def test_large_file_parses_in_subprocess(
[sys.executable, "-X", "faulthandler", "-c", script],
capture_output=True,
text=True,
timeout=30,
check=False,
)
assert result.returncode == 0, result.stderr
Expand All @@ -71,7 +70,6 @@ def test_point_coordinates_survive_repeated_reads_in_subprocess() -> None:
[sys.executable, "-X", "faulthandler", "-c", script],
capture_output=True,
text=True,
timeout=30,
check=False,
)
assert result.returncode == 0, result.stderr
1 change: 0 additions & 1 deletion tests/test_proxy_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,5 @@ def test_containment_cycles_without_a_callable_owner_terminate() -> None:
capture_output=True,
text=True,
check=True,
timeout=10,
)
assert result.stdout == "done\n"
Loading
Loading