Skip to content

Latest commit

 

History

History
388 lines (320 loc) · 20.4 KB

CONTRIBUTING.md

File metadata and controls

388 lines (320 loc) · 20.4 KB

Contributing to Trailmark

Setup

Requires Python >= 3.12, uv, Node.js/npm, a C compiler (cc), and Python development headers. CI tests Python 3.12 through 3.15.

npm ci
uv sync --locked --all-groups

npm ci installs the pinned Tree-sitter CLI used to generate the bundled Circom, Move, Rust, and Verus grammars. Its install script must be enabled; if your npm configuration disables scripts, run npm rebuild tree-sitter-cli --ignore-scripts=false before syncing. See docs/installation.md for how generated grammar sources are handled.

Running Checks

Run these checks before submitting changes:

# Lint and check formatting
uv run ruff check hatch_build.py src/ tests/
uv run ruff format --check hatch_build.py src/ tests/

# Type check
uv run --locked ty check

# Tests
uv run pytest -q tests/

# Check source-distribution guide selection and local-note exclusions
uv run --no-project --with hatchling python tests/sdist_smoke.py

Native-image tests require the binary extra and both GNU and LLVM tools. Set TRAILMARK_REQUIRE_BINARY_TOOLS=1 to fail on missing dependencies instead of skipping those tests; TRAILMARK_LLVM_OBJDUMP, TRAILMARK_LLVM_SYMBOLIZER, TRAILMARK_GNU_OBJDUMP, and TRAILMARK_GNU_SYMBOLIZER select explicit tools. The fixture manifest and regeneration commands live in tests/fixtures/binary/README.md.

python -m tests.smoke_binary_projects --help describes the optional pinned arm64 library checks. Supply local builds and checkouts; the harness neither downloads nor executes them. It compares executable coverage against llvm-readobj, symbol boundaries against llvm-nm, and direct calls against raw AArch64 instruction encodings. For a stripped image, --reference-image supplies unstripped symbols only after every executable byte matches. --compare-graph checks a graph exported by a separate process. Whole-tree source-function counts include inactive code and are regression floors, not build-specific source recall.

Performance Comparisons

Benchmark full directory analysis, including entrypoint discovery, with:

uv run --locked python -m tests.benchmark_analysis /path/to/corpus --language python --repeat 7

Use the same unchanged corpus, path, Python version, and dependencies in both checkouts, without concurrent tests or mutation workers. The runner warms up grammar loading, reports every timing and the median, and fingerprints the complete graph output with graph_sha256. Compare the fingerprints as well as the timings; a speedup should preserve or explicitly account for graph changes.

Mutation Testing

Trailmark uses a pinned pytest-gremlins runner to verify test suite quality. Always use the repository runner rather than invoking the plugin directly.

# Mutate the files under review and gate the results
uv run python -m tests.run_mutations --reviewed --workers=4
uv run python -m tests.mutation_gate

# Full repository campaign
uv run python -m tests.run_mutations --workers=4

--workers=4 already enables parallel execution. Reports are written to coverage/gremlins/. 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 32 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. One preparation job runs the selected suite once with neutral instrumentation and per-test coverage. The normal CI test jobs run the clean suite. Mutation jobs reuse its baseline receipt and coverage plan only when repository inputs, Python packages, native tool binaries, relevant environment settings, test collection, and runner configuration match. Missing, stale, or incomplete receipts fail the run. The outer pytest session collects tests and dispatches mutations without replaying the clean suite in each shard. The mutation shards then execute their assigned mutants. The final Mutation Testing check requires the baseline job and all 32 mutation shards to pass. Each mutation shard enforces the reviewed gate for its assigned inventory and uploads its own reports.

To reproduce one CI shard locally, pass the same one-based --shard=INDEX/TOTAL to both commands (omit --reviewed for a full repository shard):

uv run python -m tests.run_mutations --reviewed --workers=4 --shard=1/32
uv run python -m tests.mutation_gate --shard=1/32

Omitting --shard runs and gates the complete campaign as before. Local campaigns prepare their own coverage and baselines by default. For shared preparation, run --baseline-shard=1/1 with the same targets, tests, and test-order setting. Copy coverage/gremlins/baseline-1-of-1.json and coverage/gremlins/coverage-plan.json together into a directory and pass --baselines=PATH to mutation runs. Preparation executes no mutants and creates no gate report; evidence is written only after successful validation. Keep these files within the same trusted campaign.

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. The reviewed scope gates all functions in those files, including unchanged legacy functions. The gate rejects unreviewed survivors and incomplete mutation inventories in that scope. Across the entire campaign, errors, timeouts, pardons, and missing tests fail the gate, including outside the reviewed scope. An exception requires a reason and a fingerprint of the function and mutation; changing that function requires reviewing its exceptions again. Source hashes and mutation fingerprints use a canonical AST representation so reviews remain valid across supported Python versions. PRs that change the mutation runner, its controls, the mutation workflow, or Python dependency configuration run the full campaign before merging.

How the runner works. The runner pins pytest-gremlins 1.14.3 and uses its pytest subprocesses and import handling, including fixtures, parametrized tests, package metadata, and instrumentation in spawned child processes. Coverage-driven test selection runs only tests observed to execute the mutated line, with shared fixture setup and teardown attributed to every consumer. Tests that run unknown child processes or replace Python tracing are retained for every mutant. Known native GNU/LLVM tools, C compilers, and the fixed git -C ROOT rev-parse HEAD provenance query are recognized through fingerprints of their executable contents. Other Git commands and Python or script wrappers remain opaque. Import-time and unmapped locations use the entire selected test pool.

After mutant execution, ordinary test failures receive a neutral failure-prefix check. The control collects the same selected tests, executes only through the test that failed, and includes fixture teardown. Matching complete-pool orders reuse the passing baseline. For each remaining selected collection, one successful longest prefix also validates its shorter failure prefixes. These controls use the same worker budget after the mutant pool closes. A failing neutral prefix invalidates the campaign before scores are accepted. Survivors require no extra test executions. The gate verifies each reported test selection against the saved plan. The runner preserves exact parameter IDs 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. Mutation campaigns also use deterministic Hypothesis examples with its example database disabled, so coverage collection and mutant execution use the same generated inputs. 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.

Collection-time SystemExit counts as a kill only when its traceback includes an instrumented application source and the unmutated test selection loads successfully. Harness failures and unrelated internal errors remain errors.

Each mutant subprocess may run for 240 seconds so the complete fallback pool can finish with four workers competing for CI resources. A timeout is not counted as a kill unless the unmutated confirmation run establishes sufficient headroom; inconclusive outcomes still fail the gate.

Test ordering. Within a coverage-selected subset, component unit tests run first, stopping at the first failure. Shared-helper mutants retain tests from every language that covers the mutation. Complete-pool fallbacks keep collection order so they can reuse the shared neutral baseline. Tests stay in their existing files; tests/mutation_order.py defines the ordering, and unknown components keep collection order. Use --test-order=collection to keep pytest's original order within each subset. Use --test-selection=full to run every selected test against every mutant as a reference. Full mode validates its distinct complete orders; --baseline-shard=INDEX/TOTAL can split those checks.

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, when those files are selected, followed by any selected 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. Use --test-group=full when those tests have no mutation_fast marker.

Snapshot updates (TRAILMARK_UPDATE_SNAPSHOTS=1) are disabled during CI and mutation runs; do not enable them there.

Mutation test pools

Mutation campaigns use the fast pool by default. It marks existing tests with pytest.mark.mutation_fast; tests stay in their original modules and ordinary CI continues to run every test. Select it explicitly with --test-group=fast, or use --test-group=full to run mutations against the full pool.

uv run pytest -q -m mutation_fast tests/
uv run python -m tests.run_mutations --workers=4 --report-dir=coverage/fast
uv run python -m tests.mutation_gate --report-dir=coverage/fast

# Full-pool comparison using the same coverage selection as routine mutation runs.
uv run python -m tests.run_mutations --test-group=full --workers=4 --report-dir=coverage/full
uv run python -m tests.compare_mutations coverage/full coverage/fast --allow-coverage-reference

# Unfiltered reference: test pool and coverage selection are independent controls.
uv run python -m tests.run_mutations --test-group=full --test-selection=full --test-order=collection --report-dir=coverage/reference
uv run python -m tests.compare_mutations coverage/reference coverage/fast

# Optional controlled benchmark: three serialized repetitions per configuration.
# Configure the native tool paths listed above before starting this long benchmark.
uv run python -m tests.benchmark_mutations --workers=4 --repeat=3 --output-dir=coverage/pool-benchmark

Report directories must be distinct for independent campaigns; put them under ignored coverage/ or outside the checkout. Comparisons require the exact source checkout that produced the reports. They reconstruct the complete mutation inventory, validate disjoint shard coverage and matching inputs, reject inconclusive outcomes, and report each outcome difference rather than comparing percentages alone. The benchmark includes clean baselines, instrumented coverage preparation, collection, mutation execution, confirmations, and report validation. It includes plain unsharded pytest-gremlins only as a measurement reference; normal mutation work must use the repository runner. Result caching is disabled in these comparisons.

The seed pool comes from the v0.9.1 campaign's recorded failing-test witnesses. These witnesses are candidates, not evidence that each test kills independently. Keep integration tests and collection import witnesses that provide unique kills. When an audit loses a kill, restore the relevant existing test to the marked pool or add a small behavioral regression, then rerun the comparison. Do not expand equivalent-mutant exceptions or narrow the mutated application to repair parity. Timing measurements belong in the benchmark, never in correctness assertions.

Pull requests run one mutation campaign, using the fast pool. mutation-audit.yml runs weekly on Monday at 06:00 UTC and on its manual trigger. Each audit compares the fast pool with an unfiltered full-pool reference. Run that manual audit against each release candidate as well. Each pool uses 32 mutation shards and its own matching baseline. Restore every lost kill before accepting a failed audit. Coverage-selected references require the explicit --allow-coverage-reference comparison flag; the default comparison requires an unfiltered full-pool reference.

Audit artifacts

Keep implementations, minimized behavioral regressions, and concise decisions in Git. Keep raw investigation reports, probe output, coverage inventories, mutation reports, and copied source snapshots outside the checkout (for example, ../trailmark-artifacts/) or in the ignored docs/audits/, pr-audits/, and coverage/gremlins/ directories. Do not stage those directories with git add -f. The roadmap summarizes the release-readiness audit; preserve full evidence separately and turn individual findings into focused fixes and tests.

Architecture

Trailmark has a parse layer followed by a three-layer analysis stack:

  1. Parse API (src/trailmark/parse.py) -- public entry point for parsing files or directories into a raw CodeGraph. Lazily imports the appropriate language parser. Used directly for parse-only workflows and internally by QueryEngine.
  2. CodeGraph (src/trailmark/models/graph.py) -- mutable data container holding nodes, edges, annotations, and entrypoints.
  3. GraphStore (src/trailmark/storage/graph_store.py) -- wraps CodeGraph in a rustworkx PyDiGraph with bidirectional ID/index mappings. Validates node existence before mutations.
  4. QueryEngine (src/trailmark/query/api.py) -- high-level facade that resolves names, delegates to GraphStore, and returns plain dicts.

Formal and Lean adapters share declaration indexes, import-visibility traversal, and tiered unique lookup. Each adapter keeps its language's binding, visibility, and execution rules. Pending references use private typed parse state on CodeGraph; directory merges preserve that state until the frontend finalizes its edges. The state is excluded from graph JSON. Frontends that resolve types record their source files there so later merges cannot rebind raw type names.

Bundled grammars use one native C binding and discover their scanner/header inputs through bundled_grammar(). Keep language provenance in each grammar's notice or wrapper, and include every compiled input in the cache identity.

Conventions

  • Missing-node queries return empty values where practical. Factories and invalid-input paths may raise ValueError or exit via the CLI.
  • QueryEngine returns dicts, GraphStore returns model objects.
  • Helper functions like _unit_to_dict(), _edge_to_dict(), _annotation_to_dict() live at module level alongside their class.
  • Frozen dataclasses for immutable data (CodeUnit, CodeEdge, Annotation). CodeGraph is mutable (not frozen).
  • No relative imports. Use absolute imports from trailmark.*.

Adding a New Language Parser

  1. Create src/trailmark/parsers/<lang>/parser.py implementing the LanguageParser protocol from src/trailmark/parsers/base.py.
  2. Register the parser in _PARSER_MAP and its file extensions in _LANGUAGE_EXTENSIONS, both in src/trailmark/parse.py.
  3. Add tests in tests/test_<lang>_parser.py.
  4. Add a row to the language table in README.md, including the --language key.
  5. If the language has entrypoint conventions, add a detector in src/trailmark/analysis/entrypoints.py and a row to the framework table in docs/entrypoints.md. Note behavior that needs explanation in docs/languages.md.

Documentation

README.md is the landing page and the PyPI description. Reference material lives in docs/:

File Covers
docs/cli.md Subcommands, flags, output formats
docs/python-api.md QueryEngine and trailmark.parse
docs/graph-model.md Node/edge kinds, IDs, proxies, directory parsing, linking
docs/entrypoints.md Detection layers and .trailmark/entrypoints.toml
docs/links.md .trailmark/links.toml
docs/augmenting.md SARIF, weAudit, binary imports, annotations, preanalysis
docs/binaries.md Native linked images, address ranges, disassembly, debug identities
docs/call-resolution.md Resolution diagnostics and limits
docs/languages.md Per-language behavior
docs/parser-coverage.md Callable ownership, identity changes, grammar limits
docs/exceptions.md Exception evidence, frontend capability matrix, security audit limits
docs/roadmap.md Release-readiness priorities and archived audit provenance
docs/skills-compatibility.md Skills integration gates and release preflight
docs/installation.md Grammars, offline installs, Nix, checkouts
docs/entrypoint-patterns.md Patterns for writing new entrypoint detectors

tests/test_docs.py keeps these files in sync with the code. It checks that every CLI subcommand, public QueryEngine method, language, and enum value is documented, runs the README example, verifies relative links and anchors, and pins specific statements of behavior to the guide that documents them. When behavior changes, update the guide and the matching test in the same change.

Links in README.md use absolute https://github.com/trailofbits/trailmark/blob/main/... URLs so they work on PyPI; links between files in docs/ are relative.

Preparing a release

Prepare changes on a release/vX.Y.Z branch. Keep the version in pyproject.toml and src/trailmark/__init__.py consistent, and consolidate the changelog into user-facing additions, behavior changes, fixes, and upgrade notes. Date the release heading as ## X.Y.Z (YYYY-MM-DD) before publishing.

Run the checks above, then build into a fresh directory and validate the artifacts (replace vX.Y.Z with the intended tag):

uv build --out-dir dist/release
uv run python tests/release_preflight.py --tag vX.Y.Z --dist dist/release

The directory must contain exactly one wheel and one sdist. Preflight compares the intended tag, package and runtime versions, dated changelog heading, wheel metadata, and root sdist PKG-INFO. It does not create a tag or publish a release.

Install each artifact in its own environment and run the frontend smoke checks:

uv venv --python 3.15 /tmp/trailmark-release-wheel
uv pip install --python /tmp/trailmark-release-wheel dist/release/*.whl
/tmp/trailmark-release-wheel/bin/python tests/package_smoke.py tests/fixtures/kat
uv venv --python 3.15 /tmp/trailmark-release-sdist
uv pip install --python /tmp/trailmark-release-sdist dist/release/*.tar.gz
/tmp/trailmark-release-sdist/bin/python tests/package_smoke.py tests/fixtures/kat

Check that PyPI metadata lists the tested Python versions and documentation URL, and that both artifacts contain the bundled grammar sources and license notices. CI repeats package checks on Linux and macOS using Python 3.13 and 3.15.

After the release branch is reviewed and merged, a maintainer creates the tag and publishes the GitHub release. That publication triggers the PyPI workflow, which repeats preflight and installed-wheel checks before publishing the artifacts.