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
17 changes: 12 additions & 5 deletions .github/workflows/mutation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ jobs:
shard: [1, 2, 3, 4, 5, 6, 7, 8]
env:
MUTATION_SHARD: ${{ matrix.shard }}/8
TRAILMARK_REQUIRE_BINARY_TOOLS: "1"
TRAILMARK_LLVM_OBJDUMP: /usr/bin/llvm-objdump
TRAILMARK_LLVM_SYMBOLIZER: /usr/bin/llvm-symbolizer
TRAILMARK_LLVM_READOBJ: /usr/bin/llvm-readobj
TRAILMARK_GNU_OBJDUMP: /usr/bin/objdump
TRAILMARK_GNU_SYMBOLIZER: /usr/bin/addr2line
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand All @@ -37,19 +43,20 @@ jobs:
with:
python-version: "3.13"

- run: sudo apt-get update && sudo apt-get install -y llvm binutils-multiarch
- run: npm ci
- run: uv sync --locked --all-groups
- run: uv sync --locked --all-groups --extra binary

- name: Run reviewed mutation scope
if: github.event_name == 'pull_request'
run: uv run --locked python -m tests.run_mutations --reviewed --workers=4 --shard="$MUTATION_SHARD"
run: uv run --locked --extra binary python -m tests.run_mutations --reviewed --workers=4 --shard="$MUTATION_SHARD"

- name: Run full mutation campaign
if: github.event_name != 'pull_request'
run: uv run --locked python -m tests.run_mutations --workers=4 --shard="$MUTATION_SHARD"
run: uv run --locked --extra binary python -m tests.run_mutations --workers=4 --shard="$MUTATION_SHARD"

- name: Enforce reviewed Rust and Verus baseline
run: uv run --locked python -m tests.mutation_gate --shard="$MUTATION_SHARD"
- name: Enforce reviewed mutation baseline
run: uv run --locked --extra binary python -m tests.mutation_gate --shard="$MUTATION_SHARD"

- name: Record revision
if: always()
Expand Down
23 changes: 17 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,14 @@ uv run python -m tests.run_mutations --workers=4

`--workers=4` already enables parallel execution. Reports are written to
`coverage/gremlins/`.

CI runs eight mutation shards concurrently, each with four workers. Each file's
Confirmed execution outcomes are streamed to `coverage/gremlins/progress.jsonl`
for investigation during long campaigns. This journal can be incomplete; only
the completed reports and `run.json` establish results for the gate.

CI runs eight mutation shards concurrently, each with four workers. Mutation
jobs install the `binary` extra and GNU and LLVM tools, and set
`TRAILMARK_REQUIRE_BINARY_TOOLS=1` so missing native-image dependencies fail
instead of silently skipping their tests. Each file's
mutants are dealt round-robin across the shards, retaining the full selected test
suite for every mutant. Every shard checks the clean and instrumented baselines
and gates its exact share of the source inventory. The final `Mutation Testing`
Expand All @@ -100,11 +106,11 @@ uv run python -m tests.mutation_gate --shard=1/8

Omitting `--shard` runs and gates the complete campaign as before.

**Scope and gate.** Pull requests mutate the Rust/Verus files named in
`tests/mutation_baseline.json` and gate new and changed functions there. Full
**Scope and gate.** Pull requests mutate the reviewed files named in
`tests/mutation_baseline.json`. Full
repository campaigns run on pushes to main and through the mutation workflow's
manual trigger. Unchanged legacy functions are identified by source hashes and
enter the gate automatically when edited. The gate rejects unreviewed
manual trigger. The reviewed scope gates all functions in those files, including
unchanged legacy functions. The gate rejects unreviewed
survivors, missing tests or results, errors, and timeouts. An exception
requires a reason and a fingerprint of the function and mutation; changing
that function requires reviewing its exceptions again.
Expand Down Expand Up @@ -135,6 +141,11 @@ compare against pytest's original order.

Private helpers use their component test names without the leading underscore;
Python decorator helpers start with `test_python_decorator_bindings.py`.
Snapshot and binary model mutants start with `test_snapshots.py` and
`test_binary_models.py`, respectively, before falling back to general model tests.
Snapshot mutants also prioritize binary and proxy round trips. Callable-reference
mutants prioritize binding-boundary and PHP callable tests; shared parser mutants
prioritize directory-linking regressions after their utility tests.

**Focusing a campaign.** Pass `--targets` with comma-separated source paths,
followed by the relevant test files.
Expand Down
2 changes: 2 additions & 0 deletions docs/entrypoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ currently bounded to the forms described below.
Their descriptions identify the convention without assigning a framework.
- Python and PHP callable arguments and collection values retain references,
including supported aliases, imports and statically qualified members.
PHP `namespace\` prefixes resolve first-class function and method references
in the current namespace.
PHP partial application records `partial_application` references separately
from the call edges made by explicit inline invocation or a pipe stage.
Dynamic member dispatch stays unresolved. Other frontends keep their existing
Expand Down
2 changes: 2 additions & 0 deletions docs/parser-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ with the enclosing function; initialization traversal defers their bodies.
Local classes retain separate method owners. Variadic
parameters retain names and annotations; `self` and `cls` are omitted only as
actual method receivers, and retained in free functions and static methods.
Callable-reference discovery respects parameter shadowing, including annotated
`*args` and `**kwargs`, without treating annotation names as local bindings.

Python module nodes own calls in top-level statements and explicit top-level
decorator calls. Calls in function and method bodies keep their callable owner.
Expand Down
6 changes: 5 additions & 1 deletion docs/python-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ Roots are ordered: a canonical file belongs to the first root that selects it.
An explicitly selected root bypasses its parents' exclusions. Multiple roots
prefix node IDs with `root_name::` to preserve source identity. Include and
exclude globs are relative to each root; explicit includes override exclusions.
`*` and `?` match within a path segment; `**` spans directories. A matched
`*` and `?` match within a path segment; each `**` can span zero or more
directories, including consecutive globstar segments. Wildcards also match
newline characters in POSIX filenames. A matched
directory excludes its descendants, including when a specific include keeps
traversal open. Both `build` and `build/` exclude that directory.
Directory symlinks are not followed, file symlinks cannot escape a root, and
Expand Down Expand Up @@ -365,6 +367,8 @@ accepts that JSON string or its decoded dictionary. Loading validates the format
schema, exporter version, typed fields, evidence identities, and graph references
before building the index. Dangling relationships are permitted only with a matching
explicit inventory. Incompatible or malformed snapshots raise `ValueError`.
Binary, proxy, and synthetic nodes may retain the line range `(0, 0)` for
unknown source locations. Source-node locations use positive line numbers.

```python
from pathlib import Path
Expand Down
11 changes: 2 additions & 9 deletions src/trailmark/_path_glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,7 @@ def compile_path_glob(pattern: str, *, suffix: bool = False) -> re.Pattern[str]:
while i < n:
c = pattern[i]
if c == "*" and i + 1 < n and pattern[i + 1] == "*":
# `/**/` expands to `(?:/.*)?/` — zero or more segments.
if i > 0 and pattern[i - 1] == "/" and i + 2 < n and pattern[i + 2] == "/":
# Rewrite the trailing `/` of the preceding segment as
# part of the globstar expansion.
out[-1] = "(?:/.*)?/"
i += 3
continue
# Leading `**/` or trailing `/**`.
# `**/` consumes zero or more complete path segments.
if i + 2 < n and pattern[i + 2] == "/":
out.append("(?:.*/)?")
i += 3
Expand All @@ -49,4 +42,4 @@ def compile_path_glob(pattern: str, *, suffix: bool = False) -> re.Pattern[str]:
else:
out.append(c)
i += 1
return re.compile((r"(?:^|/)" if suffix else r"\A") + "".join(out) + r"\Z")
return re.compile((r"(?:^|/)" if suffix else r"\A") + "".join(out) + r"\Z", re.DOTALL)
27 changes: 14 additions & 13 deletions src/trailmark/analysis/_callable_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ class _Target:
"""A graph node, a Python module path, or a callable without a node.

A default instance is an opaque value: bound, but not known to be callable.
Graph-node callability comes from the index; ``callable`` marks targets
whose declarations are unavailable.
"""

node_id: str | None = None
Expand Down Expand Up @@ -345,7 +347,9 @@ def _edge(self, occurrence: _Occurrence, target: str, dispatch: bool) -> None:
"tuple",
"list",
"list_splat_pattern",
"dictionary_splat_pattern",
"list_splat",
"typed_parameter",
"parenthesized_expression",
"expression_list",
"as_pattern_target",
Expand Down Expand Up @@ -446,11 +450,8 @@ def _parameter_names(node: Node) -> list[str]:
parameters = node.child_by_field_name("parameters")
names = []
for child in parameters.named_children if parameters is not None else []:
name = child if child.type == "identifier" else child.child_by_field_name("name")
if name is None:
name = next((c for c in child.named_children if c.type == "identifier"), None)
if name is not None:
names.append(_text(name))
target = child.child_by_field_name("name")
names.extend(_target_names(target if target is not None else child))
return names


Expand Down Expand Up @@ -564,7 +565,7 @@ def member(self, target: _Target, name: str, depth: int) -> set[_Target]:
return self.module_member(target.module, name, depth)
if target.node_id is not None and self.index.kind(target.node_id) in _CLASS_KINDS:
methods = self.index.members(target.node_id, name)
return {_Target(node_id=m, callable=True) for m in methods} or {_OPAQUE}
return {_Target(node_id=m) for m in methods} or {_OPAQUE}
return {_OPAQUE}

def module_member(self, dotted: str, name: str, depth: int) -> set[_Target]:
Expand Down Expand Up @@ -738,7 +739,7 @@ def _definition(self, site: Node) -> _Target:
unit = self.index.unit_at(self.path, site)
if unit is None:
return _UNKNOWN_CALLABLE if site.type == "function_definition" else _OPAQUE
return _Target(node_id=unit, callable=self.index.is_callable(unit))
return _Target(node_id=unit)

def _alias(self, site: Node, depth: int) -> set[_Target]:
left = site.child_by_field_name("left")
Expand Down Expand Up @@ -805,7 +806,7 @@ def _receiver(self, parts: list[Node]) -> set[_Target] | None:
if not names or names[0] != _text(head) or len(local) != 1:
return None
methods = self.index.members(class_id, _text(attribute))
return {_Target(node_id=m, callable=True, dispatch=True) for m in methods} or {_OPAQUE}
return {_Target(node_id=m, dispatch=True) for m in methods} or {_OPAQUE}

def _method_of(self, node: Node) -> tuple[Node | None, str | None]:
current = node.parent
Expand Down Expand Up @@ -1040,7 +1041,7 @@ def _string(self, node: Node) -> None:
targets = self._methods(self.classes.get(_php_key(name), []), method, dispatch=False)
else:
ids = self.functions.get(_php_key(name), [])
targets = {_Target(node_id=i, callable=True) for i in ids}
targets = {_Target(node_id=i) for i in ids}
if targets:
self._record(node, "string", targets, context)

Expand Down Expand Up @@ -1069,7 +1070,7 @@ def _function_ids(self, name: str, node: Node) -> list[str]:

def _methods(self, classes: list[str], method: str, *, dispatch: bool) -> set[_Target]:
return {
_Target(node_id=m, callable=True, dispatch=dispatch)
_Target(node_id=m, dispatch=dispatch)
for class_id in classes
for m in self.index.members(class_id, method, fold=True)
}
Expand All @@ -1084,7 +1085,7 @@ def _enclosing_class(self, node: Node) -> str | None:

def _scope_classes(self, scope: Node, node: Node) -> tuple[list[str], bool] | None:
"""Classes named by a scope (``Type``, ``self``, ``static``, ``parent``)."""
if scope.type in {"name", "qualified_name"}:
if scope.type in {"name", "qualified_name", "relative_name"}:
return self.classes.get(_php_key(self._class_name(_text(scope), node)), []), False
if scope.type != "relative_scope":
return None
Expand All @@ -1099,10 +1100,10 @@ def _acquired(self, node: Node) -> set[_Target]:
name = _text(node.child_by_field_name("name"))
if node.type == "function_call_expression":
function = node.child_by_field_name("function")
if function is None or function.type not in {"name", "qualified_name"}:
if function is None or function.type not in {"name", "qualified_name", "relative_name"}:
return {_UNKNOWN_CALLABLE}
ids = self._function_ids(_text(function), node)
return {_Target(node_id=i, callable=True) for i in ids} or {_UNKNOWN_CALLABLE}
return {_Target(node_id=i) for i in ids} or {_UNKNOWN_CALLABLE}
if node.type == "scoped_call_expression":
scope = node.child_by_field_name("scope")
found = self._scope_classes(scope, node) if scope is not None else None
Expand Down
79 changes: 46 additions & 33 deletions src/trailmark/models/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from trailmark import __version__
from trailmark.models.exceptions import ExceptionEvent
from trailmark.models.graph import CodeGraph
from trailmark.models.nodes import NodeOrigin, SourceLocation
from trailmark.models.nodes import CodeUnit, NodeOrigin, SourceLocation

_FORMAT = "trailmark.analysis"
_VERSION = 1
Expand Down Expand Up @@ -61,23 +61,29 @@ def _hints(expected: type) -> dict[str, Any]:


@overload
def _decode[T](value: object, expected: type[T], path: str) -> T: ...
def _decode[T](
value: object, expected: type[T], path: str, *, node_origin: str | None = None
) -> T: ...


@overload
def _decode(value: object, expected: object, path: str) -> object: ...
def _decode(
value: object, expected: object, path: str, *, node_origin: str | None = None
) -> object: ...


def _decode(value: object, expected: object, path: str) -> object:
def _decode(
value: object, expected: object, path: str, *, node_origin: str | None = None
) -> object:
if isinstance(expected, TypeAliasType):
return _decode(value, expected.__value__, path)
return _decode(value, expected.__value__, path, node_origin=node_origin)
if expected in {Any, object}:
return _encode(value)
origin, arguments = get_origin(expected), get_args(expected)
if origin in {types.UnionType, Union}:
for choice in arguments:
try:
return _decode(value, choice, path)
return _decode(value, choice, path, node_origin=node_origin)
except ValueError:
pass
raise ValueError(f"{path}: value does not match {expected}")
Expand Down Expand Up @@ -114,22 +120,41 @@ def _decode(value: object, expected: object, path: str) -> object:
raise ValueError(f"{path}: missing or unknown {expected.__name__} fields")
hints = _hints(expected)
result = expected(
**{key: _decode(item, hints[key], f"{path}.{key}") for key, item in value.items()}
**{
key: _decode(
item,
hints[key],
f"{path}.{key}",
node_origin=value["origin"]
if expected is CodeUnit and key == "location"
else None,
)
for key, item in value.items()
}
)
if isinstance(result, SourceLocation) and (
result.start_line < 1
or result.end_line < result.start_line
or any(
column is not None and column < 0 for column in (result.start_col, result.end_col)
)
or (
result.start_line == result.end_line
and result.start_col is not None
and result.end_col is not None
and result.end_col < result.start_col
if isinstance(result, SourceLocation):
minimum_line = (
0
if node_origin
in {NodeOrigin.BINARY.value, NodeOrigin.PROXY.value, NodeOrigin.SYNTHETIC.value}
and result.start_line == result.end_line == 0
else 1
)
):
raise ValueError(f"{path}: invalid source location")
if (
result.start_line < minimum_line
or result.end_line < result.start_line
or any(
column is not None and column < 0
for column in (result.start_col, result.end_col)
)
or (
result.start_line == result.end_line
and result.start_col is not None
and result.end_col is not None
and result.end_col < result.start_col
)
):
raise ValueError(f"{path}: invalid source location")
return result
if type(value) is expected and (not isinstance(value, float) or math.isfinite(value)):
return value
Expand Down Expand Up @@ -176,21 +201,12 @@ def dump_snapshot(
source_revision: str | None,
tool_revision: str | None,
) -> dict[str, object]:
provenance = deepcopy(graph._snapshot_provenance) # noqa: SLF001
provenance: dict[str, object] = deepcopy(graph._snapshot_provenance) # noqa: SLF001
if not provenance:
root = Path(graph.root_path)
provenance = {
"source_revision": source_revision
or _git_revision(root.parent if root.is_file() else root),
"source_sha256": _source_digest(graph),
"unfingerprinted_sources": sorted(
{
unit.location.file_path
for unit in graph.nodes.values()
if unit.origin == NodeOrigin.SOURCE
}
- graph.source_digests.keys()
),
"tool_revision": tool_revision or _git_revision(Path(__file__).resolve().parents[3]),
"tool_sha256": _tool_digest(),
}
Expand Down Expand Up @@ -298,9 +314,6 @@ def _validate_graph(graph: CodeGraph) -> None:
for key, unit in graph.nodes.items():
if key != unit.id:
raise ValueError("Snapshot node key does not match its ID")
location = unit.location
if location.start_line < 1 or location.end_line < location.start_line:
raise ValueError("Invalid source location")
for name in ("annotations", "entrypoints"):
if set(getattr(graph, name)) - graph.nodes.keys():
raise ValueError(f"Unknown node in {name}")
Expand Down
Loading
Loading