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
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ jobs:
# Runs the same wrapper script against every tracked markdown file,
# so a PR that breaks a doc reference fails CI even if the contributor
# skipped `pre-commit install`. Single Python + single OS by design —
# markdown rendering is platform-independent and the 5x3 test matrix
# markdown rendering is platform-independent and the pytest matrix
# adds nothing here.
runs-on: ubuntu-latest
steps:
Expand Down
44 changes: 35 additions & 9 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,26 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
# Every supported Python on Linux; macOS and Windows on the oldest and
# newest only. No test is gated on a Python version, so each OS-specific
# test (the Windows-only cmd.exe branch, the POSIX-only
# symlink/bash/permission tests) still runs on every OS it targets.
# The ubuntu job names are the ruleset's required checks: keep the name
# template and all five ubuntu versions.
#
# `cov: true` marks the one job that runs the 100% coverage gate
# (addopts): ubuntu py3.14, where coverage's sys.monitoring core costs
# almost nothing. The rest pass --no-cov, which drops the overhead the
# ctrace core adds on 3.10-3.13.
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
os: [ubuntu-latest]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
include:
- { os: ubuntu-latest, python-version: "3.14", cov: true }
- { os: macos-latest, python-version: "3.10" }
- { os: macos-latest, python-version: "3.14" }
- { os: windows-latest, python-version: "3.10" }
- { os: windows-latest, python-version: "3.14" }
steps:
- uses: actions/checkout@v7

Expand All @@ -47,14 +64,23 @@ jobs:
cache-dependency-path: pyproject.toml

- name: Install dependencies
# The `treesitter` extra is installed across the whole 3-OS x 5-Python
# matrix so the import-edge layer (#354) is exercised on Linux, macOS,
# and Windows (its prebuilt wheels are validated on each here), and so
# the 100% coverage gate sees the tree-sitter code paths. The graceful-
# degradation path (extra absent) is covered deterministically in every
# run by the monkeypatched tests in tests/test_repo_map_imports.py, so a
# separate extra-free job isn't needed to prove it.
# The `treesitter` extra is installed on every job so the import-edge
# layer (#354) and its prebuilt wheels are exercised on each OS and
# Python version in the matrix, and so the coverage job sees the
# tree-sitter code paths. The graceful-degradation path (extra
# absent) is covered deterministically in every run by the
# monkeypatched tests in tests/test_repo_map_imports.py, so a separate
# extra-free job isn't needed to prove it.
run: python -m pip install -e ".[dev,vertex,treesitter]"

# pytest-xdist spreads the suite over the runner's cores; `--dist
# loadfile` keeps each module on one worker so module-scoped fixtures
# (the wheel build, the MCP server spawns) run once per module.
#
# SUMO_QA_REQUIRE_TREESITTER makes a tree-sitter import failure fail the
# job (tests/test_repo_map_imports.py) instead of silently skipping the
# tree-sitter tests on that OS and Python.
- name: Run pytest
run: python -m pytest --cov=src/sumo_qa --cov-fail-under=100 -q
env:
SUMO_QA_REQUIRE_TREESITTER: "1"
run: python -m pytest -n auto --dist loadfile ${{ !matrix.cov && '--no-cov' || '' }}
19 changes: 14 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -294,11 +294,19 @@ repos:
# `[tool.pytest.ini_options]`, so `import sumo_qa.*` resolves
# without the project itself needing to be pip-installed.
#
# `verbose: true` and a bare `pytest` (options come from addopts
# alone) keep pytest's "N passed" and coverage lines in the push
# output; the delivery skills quote them as the full local suite's
# evidence. tests/test_toolchain_pin_lockstep.py pins this argv.
entry: pytest
# `verbose: true` keeps pytest's "N passed" and coverage lines in the
# push output; the delivery skills quote them as the full local
# suite's evidence. Every option except the pytest-xdist ones comes
# from addopts. tests/test_toolchain_pin_lockstep.py pins this argv.
#
# The full suite runs on every push because the delivery skills use
# this hook as the one full local run with the 100% coverage gate,
# and CI cannot stand in for it before the push. pytest-xdist spreads
# it over one worker per core, capped at 4 (more workers are no
# faster here); `--dist loadfile` keeps each module on one worker so
# module-scoped fixtures (the wheel build, the MCP server spawns) run
# once per module, not once per worker.
entry: pytest -n auto --maxprocesses 4 --dist loadfile
verbose: true
language: python
additional_dependencies:
Expand All @@ -308,6 +316,7 @@ repos:
- "PyYAML>=6,<7"
- "pytest>=8.4,<10"
- "pytest-cov>=6,<8"
- "pytest-xdist==3.8.0"
# Build backend — tests/test_wheel_packaging.py builds the wheel via
# `pip wheel --no-build-isolation` to assert it ships py.typed.
- "hatchling>=1.25"
Expand Down
11 changes: 10 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
# Copyright 2026 Sumith Ramsookbhai. Licensed under Apache-2.0 (see LICENSE).
"""Repo-root conftest to make top-level packages (e.g. ``evaluation``) importable in tests.
"""Repo-root conftest for suite-wide test setup.

The ``[tool.pytest.ini_options].pythonpath`` setting in pyproject.toml only
includes ``src``, so packages that live at the repo root (like ``evaluation``)
are not importable by default. This conftest adds the repo root to sys.path
so tests can import them.

It also loads a Hypothesis profile with no per-example deadline. The 200ms
default measures wall-clock time, which a loaded pytest-xdist worker overruns
on correct code; the suite's property tests check behaviour, not speed.
"""

from __future__ import annotations

import sys
from pathlib import Path

from hypothesis import settings

_REPO_ROOT = Path(__file__).resolve().parent
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))

settings.register_profile("sumo-qa", deadline=None)
settings.load_profile("sumo-qa")
25 changes: 17 additions & 8 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ Once installed (above), you get them for free on every `git commit` / `git push`
| Trigger | What runs | Speed | Why |
|---|---|---|---|
| `git commit` | `ruff check --fix`, `ruff format`, trailing-whitespace / EOL / YAML / TOML / JSON / merge-conflict / large-file hooks | ~1s | Auto-fixes 95% of CI lint failures before the commit lands. |
| `git push` | the full `pytest` suite at 100% coverage, printing its counts; the mutmut gate (see [Mutation testing](#mutation-testing) for its triggers and scope); and every other hook without a commit-only stage, on the pushed files (the fixers among them can rewrite a file and stop the push) | minutes | Stops broken or under-tested commits reaching the remote. |
| `git push` | the full `pytest` suite at 100% coverage across pytest-xdist workers, printing its counts; the mutmut gate (see [Mutation testing](#mutation-testing) for its triggers and scope); and every other hook without a commit-only stage, on the pushed files (the fixers among them can rewrite a file and stop the push) | minutes | Stops broken or under-tested commits reaching the remote. |

The pytest hook runs in pre-commit's own isolated venv, built from the explicit `additional_dependencies` pins in `.pre-commit-config.yaml` (where a hook and `pyproject.toml` pin the same package, `tests/test_toolchain_pin_lockstep.py` keeps the two in lockstep), so it's not coupled to whichever `python` happens to be on your PATH. The first `git push` after install is slower while pre-commit builds that venv; later pushes reuse it.

Expand All @@ -138,7 +138,7 @@ pre-commit run --all-files --hook-stage pre-push # the push-stage hooks

**Skipping hooks** (rare): `git commit --no-verify` or `git push --no-verify`. CI will still catch anything you skipped, use this only for genuine emergencies.

Hooks are pinned in `.pre-commit-config.yaml` and mirror `.github/workflows/lint.yml` + `.github/workflows/test.yml`, so passing the hooks locally clears the ruff and pytest gates. One CI lint gate is intentionally not a hook, `mypy` (see [Type checking](#type-checking)): to keep `git push` fast; run `python -m mypy` before pushing to clear it too.
Hooks are pinned in `.pre-commit-config.yaml` and mirror `.github/workflows/lint.yml`, so passing them locally clears the ruff gates. The pytest hook runs the full suite with the 100% coverage gate on your one Python and OS; `.github/workflows/test.yml` runs it across the OS and Python matrix (with the coverage gate on one job), so CI can still fail on a platform the hook did not cover. One CI lint gate is intentionally not a hook, `mypy` (see [Type checking](#type-checking)): to keep `git push` fast; run `python -m mypy` before pushing to clear it too.

## Test suite

Expand Down Expand Up @@ -362,14 +362,23 @@ literal or built in a separate variable (`code = textwrap.dedent("...import
sumo_qa.knowledge_loaders..."); subprocess.run([sys.executable, "-c", code])`),
and whether `-m` targets the full package or any `sumo_qa.<sub>` submodule that
transitively imports a mutated module (e.g. `sumo_qa.server`, `sumo_qa.ingest`).
It also handles the `shell=True` single-string form
A `-c` body is dedented and parsed as Python, and each `sumo_qa` module it
imports (`from sumo_qa import conformance` counts as `sumo_qa.conformance`) is
flagged when a static walk of `src/`'s imports reaches a mutated module from it
(`sumo_qa.conformance` reaches `knowledge_loaders`); a body that does not parse,
such as an f-string fragment, falls back to matching the module named right
after `from` or `import`. Any string naming `sumo_qa.<mutated>` or containing
`import <mutated>` is also flagged outright, so dynamic imports
(`importlib.import_module("sumo_qa.rules")`, `__import__`, `exec`) are caught;
the price is that a body merely mentioning such a name is flagged too. It also
handles the `shell=True` single-string form
(`subprocess.run("python -m sumo_qa", shell=True)`): a one-string command is
shlex-tokenised so it is classified like the equivalent argv list, rather than
slipping past as one un-split token. The provably non-mutating CLI entry points
`sumo_qa.installer` / `sumo_qa.doctor` are exempt (across both the argv and
shell-string forms), so `-m sumo_qa.installer --help` style spawns stay
unflagged. Its classifications are pinned by real fixture meta-tests in
`tests/fixtures/mutmut_guard/`.
slipping past as one un-split token. No `sumo_qa.<sub>` entry point is exempt:
every one, `sumo_qa.installer` and `sumo_qa.doctor` included, reaches a mutated
module, so `-m sumo_qa.installer --help` style spawns are flagged in both the
argv and shell-string forms. Its classifications are pinned by real fixture
meta-tests in `tests/fixtures/mutmut_guard/`.

## Toolchain pin lockstep

Expand Down
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ dev = [
# -compatible link-checker ships. See .pre-commit-config.yaml.
"pytest>=8.4,<10",
"pytest-cov>=6,<8",
# Runs the suite across cores in the test.yml CI jobs and the pre-push
# pytest hook, which mirrors this pin (#787).
"pytest-xdist==3.8.0",
# Markdown link-existence gate: pre-commit + CI invoke
# `scripts/check_markdown_links.sh`, which wraps pytest-check-links.
# Catches the class of bug where a doc references a file that was
Expand Down Expand Up @@ -342,6 +345,9 @@ pytest_add_cli_args = [
# Spawns `python -m sumo_qa.cli` to pin `sumo-qa check`'s exact exit codes.
# Marker: `mutmut-subprocess-spawning`.
"--ignore=tests/test_cli_check_subprocess.py",
# Spawns `python -c` importing sumo_qa.conformance, which imports the mutated
# knowledge_loaders.py. Marker: `mutmut-subprocess-spawning`.
"--ignore=tests/test_conformance_redos_subprocess.py",
]
pytest_add_cli_args_test_selection = ["tests/"]
# mutmut only copies source_paths modules into mutants/src/sumo_qa/, leaving the
Expand Down
35 changes: 28 additions & 7 deletions src/sumo_qa/external_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,23 @@ def install_external_skill(
cwd = cwd or Path.cwd()
home = home or Path.home()
lock_base = cwd if scope == "project" else home
_read_lock(lock_base) # fail fast on an unreadable lock, before any fetch
# Fail fast on an unreadable lock, before any fetch. An existing lock is
# read only under its guard: on Windows an open read handle makes a
# concurrent install's os.replace onto it fail. With no lock file there is
# nothing to read, so nothing is created or waited on before the fetch.
lock_path = lock_base / _LOCK_RELPATH
# os.stat, not Path.exists: from Python 3.14 Path.exists returns False for
# a lock inside an unsearchable folder instead of raising.
try:
os.stat(lock_path)
lock_exists = True
except (FileNotFoundError, NotADirectoryError):
lock_exists = False
except OSError as exc:
raise ExternalSkillReadError(f"could not lock {lock_path}: {exc}") from exc
if lock_exists:
with _lock_guard(lock_base):
_read_lock(lock_base)
workdir, checkout, resolved_ref = _checkout_commit(remote_url, requested_ref, timeout)
try:
_check_checkout_links(checkout)
Expand Down Expand Up @@ -357,7 +373,11 @@ def _locate_verified(
if installed is not None:
path = Path(installed["path"])
body = _read_skill_body(path)
found = installed, path, body, _verify_provenance(path, lock_base, body)
# The lock is read only under its guard (see install).
# Unlocked there was no lock folder, so no lock; one that
# appears meanwhile discards this attempt for a locked one.
skills = _read_lock(lock_base)["skills"] if locked else {}
found = installed, path, body, _verify_provenance(path, lock_base, body, skills)
except (ExternalSkillError, OSError) as exc:
# An unlocked result, or its failure, raced an install: retry locked.
if locked or not lock_folder.is_dir():
Expand Down Expand Up @@ -971,9 +991,11 @@ def _merge_into_lock(base: Path, records: list[dict[str, Any]]) -> None:
) from exc


def _verify_provenance(skill_md: Path, lock_base: Path, body: bytes) -> dict[str, Any]:
def _verify_provenance(
skill_md: Path, lock_base: Path, body: bytes, skills: dict[str, Any]
) -> dict[str, Any]:
folder = skill_md.parent
key, record = _find_record(folder, lock_base)
key, record = _find_record(folder, lock_base, skills)
if record is _NO_RECORD:
return {"status": "unrecorded"}
resolved_ref = record.get("resolved_ref") if isinstance(record, dict) else None
Expand Down Expand Up @@ -1008,13 +1030,12 @@ def _verify_provenance(skill_md: Path, lock_base: Path, body: bytes) -> dict[str
return {"status": "verified", **record}


def _find_record(folder: Path, lock_base: Path) -> tuple[str, Any]:
"""The lock record for ``folder``, matched by the folder on disk.
def _find_record(folder: Path, lock_base: Path, skills: dict[str, Any]) -> tuple[str, Any]:
"""The lock record for ``folder`` in ``skills``, matched by the folder on disk.

Matching by path spelling alone would let a case or symlink variant of the
name miss the record and run the skill as unrecorded.
"""
skills = _read_lock(lock_base)["skills"]
key = os.path.relpath(folder, lock_base).replace(os.sep, "/")
if key in skills:
return key, skills[key]
Expand Down
3 changes: 1 addition & 2 deletions src/sumo_qa/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1581,8 +1581,7 @@ def _read_json_rpc_response(
def _terminate(proc: subprocess.Popen) -> None:
"""Best-effort process teardown.

Mirrors the cleanup in ``tests/test_e2e_mcp_initialize.py``: close stdin,
``terminate()``, wait briefly, ``kill()`` on stragglers. Tolerant of
Close stdin, ``terminate()``, wait briefly, ``kill()`` on stragglers. Tolerant of
already-exited processes and missing pipe handles.
"""
try:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_claude_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def _run_subprocess_hook(
input=json.dumps(payload),
capture_output=True,
text=True,
timeout=10,
timeout=60,
env=env,
)

Expand Down
57 changes: 57 additions & 0 deletions tests/test_conformance_redos_subprocess.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright 2026 Sumith Ramsookbhai. Licensed under Apache-2.0 (see LICENSE).
"""ReDoS guard for the conformance validator that runs its call in a child.

Kept apart from tests/test_conformance_transcript_validator.py so that module
stays inside the mutation gate.
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import pytest

# mutmut-subprocess-spawning: spawns ``python -c`` importing sumo_qa.conformance,
# which imports the mutated knowledge_loaders, so it MUST be excluded from the
# mutmut gate via [tool.mutmut].pytest_add_cli_args in pyproject.toml. Otherwise
# the subprocess imports trampoline-injected modules without MUTANT_UNDER_TEST
# and crashes.

# The linear matcher finishes in well under 100ms; exponential backtracking
# takes far longer, so the budget tolerates a loaded pytest-xdist worker.
_REDOS_BUDGET_SECONDS = 2.0


def test_blank_string_values_does_not_backtrack_exponentially() -> None:
"""A backslash must match only the escape branch of the quoted-string
pattern; when it could match either, an unterminated string of escapes
backtracks exponentially (CodeQL py/redos, #248)."""
from sumo_qa import conformance

span = '{"a' + "\\a" * 28
# The call runs in a child killed at 30s, so a regression fails fast
# instead of blocking the pytest-xdist worker while it backtracks. The
# child imports the same sumo_qa as this test: the pre-push hook's venv
# has it only on pytest's pythonpath, not installed.
import_root = str(Path(conformance.__file__).parents[1])
child = (
f"import sys, time; sys.path.insert(0, {import_root!r});"
"from sumo_qa.conformance import _blank_string_values;"
f"span = {span!r}; start = time.perf_counter();"
"assert _blank_string_values(span) == span;"
"print(time.perf_counter() - start)"
)
try:
proc = subprocess.run(
[sys.executable, "-c", child],
capture_output=True,
encoding="utf-8",
timeout=30,
)
except subprocess.TimeoutExpired:
pytest.fail("ReDoS: _blank_string_values did not finish in 30s")
assert proc.returncode == 0, proc.stderr
elapsed = float(proc.stdout)
assert elapsed < _REDOS_BUDGET_SECONDS, f"ReDoS: _blank_string_values took {elapsed:.1f}s"
Loading
Loading