Skip to content

Latest commit

 

History

History
287 lines (230 loc) · 13.9 KB

CONTRIBUTING.md

File metadata and controls

287 lines (230 loc) · 13.9 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 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 check requires all eight shards to pass; reports are uploaded separately per shard.

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/8
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 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, 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. Source hashes and mutation fingerprints use a canonical AST representation so reviews remain valid across supported Python versions.

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. 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. The adapter uses private plugin APIs; its control tests must pass before upgrading the plugin.

Each mutant subprocess may run for 240 seconds so the full fallback suite 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. Each mutant keeps the full selected test suite: component unit tests run first, followed by the remaining tests, stopping at the first failure. Shared-helper mutants retain tests from every language. Tests stay in their existing files; tests/mutation_order.py defines the ordering, and unknown components keep collection order. Use --test-order=collection to 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.

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

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.