Contributing to Polypus¶
Thanks for your interest in Polypus! This guide covers environment setup, the
test suite, and how changes get merged. It applies to human and AI-assisted
contributions alike. Two companion documents complete the picture:
docs/ENGINEERING.md (code-level invariants and Rust style) and
docs/CONTRACTS.md (the inter-layer contracts).
Setting up¶
Same project, three names —
pip install polypus-quantum·import polypus·cargo add polypus. The PyPI namepolypusis taken, so the distribution ispolypus-quantum; the import name and the Rust crate both staypolypus.
The interactive installer handles dependencies, the wheel build and the test suite:
bash install.sh # guided
bash install.sh --yes # non-interactive (CI)
Development route — an editable install of both packages (polypus and the
polypus_python helpers, which live side by side under python/):
pip install -r requirements-dev.txt
maturin develop --release
Edits to any .py file under python/ take effect on the next import, with no
rebuild. After a Rust change, run maturin develop --release again; it rebuilds
the extension incrementally and drops it in place next to
python/polypus/__init__.py (git-ignored). Keep --release, matching the
wheel CI tests: several Python tests time real simulations.
Wheel route — what install.sh, CI and users get (one wheel carries both the
polypus extension and the polypus_python helpers):
pip install -r requirements-dev.txt
maturin build --release --out dist
pip install --force-reinstall dist/polypus_quantum-*.whl
--force-reinstall makes pip replace an already-installed wheel that has the
same version after a rebuild; it also replaces an editable install.
just wheel builds and installs the wheel as CI does (see
Running the checks).
Toolchain: the Minimum Supported Rust Version is declared as
rust-version in the workspace Cargo.toml — that field is where it is
decided (Cargo enforces it and Clippy picks it up automatically); the
justfile's msrv, which the msrv job checks with, must name the same
version, and tests/docs/test_ci_recipes.py fails when it does not. The
workspace uses the MSRV-aware resolver (resolver = "3"), so cargo update
avoids dependency releases that need a newer Rust than rust-version; the
msrv CI job still builds with --locked and catches anything that slips
through. The qmio feature has a higher minimum, Rust 1.89 (zeromq 0.7), which the
same job checks. Dependabot does not honour rust-version
(dependabot-core#5423),
so .github/dependabot.yml ignores uuid >=1.27, which needs Rust 1.89. Remove
that ignore when rust-version is raised to 1.89 or later (#276, #278). If
another dependency starts to need a newer Rust, add an ignore for it the same
way.
Running the checks¶
Every check of .github/workflows/ci.yml is a recipe of the root
justfile, and
ci.yml calls those recipes instead of repeating their commands, so the two
cannot drift apart (a test, tests/docs/test_ci_recipes.py, fails when a
ci.yml step runs a command of its own, or changes what a recipe runs through
an environment variable, $GITHUB_ENV, $GITHUB_PATH, a shell setting or an
unreviewed action). The checks of hygiene.yml and
docs.yml have recipes too (just hygiene, just docs-site), although those
workflows run their own commands. Install
just once; CI pins the version in ci.yml
(JUST_VERSION):
cargo install --locked just --version 1.57.0
Then, from the repository root:
just ci # everything CI checks that one machine can reproduce
just ci-all # that, plus the MSRV, dependency-floor, packaging, semver, fuzz and Miri jobs
just --list # every recipe: `just fmt`, `just clippy`, `just test-rust`, `just pytest -k qml`, …
The recipes use the Rust that rust-toolchain.toml pins, which rustup selects
in this checkout (rustup toolchain install installs it); the ones on another
toolchain (msrv, minimal-versions, fuzz, miri) install the version the
justfile names. just ci builds the wheel and installs it in the active Python
environment (just wheel), then runs the Python suite, the typing stubs, the
Aer conformance battery and the tutorial notebooks against it. It expects the
tools CI installs: requirements-dev.txt and requirements-docs.txt, plus
cargo-deny, cargo-machete, LLVM's llvm-as, and for the notebooks nbconvert,
ipykernel, matplotlib and the CPU build of PyTorch (several tutorials train
through polypus.torch); ci-all adds cargo-semver-checks and cargo-fuzz. Their versions are
in ci.yml. just hygiene analyses commits, not uncommitted changes, so commit
first (see Repository hygiene); just minimal-versions
rewrites Cargo.lock and restores it afterwards.
What one machine cannot reproduce is the matrix: CI builds the wheel on Linux,
macOS and Windows and runs the README Bell example and a few Python test files
on it there (build-extension, just pytest-portable), tests polypus-sim
and polypus-circuit on macOS and Windows (test-portable,
just test-portable), runs the Python suite on the floor and latest supported
Python and on the Qiskit of the OpenQASM 3 fixtures, and runs it once more
with every dependency at its declared floor on a fresh Python 3.10 (the
python-floors job, whose steps show how). just pytest uses the Python of
the active environment.
Optional git hooks run the formatting checks before each commit:
pip install pre-commit, then pre-commit install once per clone
(.pre-commit-config.yaml: just fmt, just ruff, and nbstripout on
tutorials/).
A few tests skip when what they need is missing. CI provides it and sets a
variable that turns those skips into failures: POLYPUS_REQUIRE_LLVM_AS=1
for the QIR tests that run llvm-as (Rust and Python), POLYPUS_REQUIRE_AER=1
for the Aer conformance battery, and POLYPUS_REQUIRE_FIXTURES_QISKIT=1 in the
leg that installs the Qiskit tests/python/qasm3_fixtures.py names, for the
pinned OpenQASM 3 fixtures (contract C-10). The other legs use the latest
Qiskit, where those fixture tests skip. The latest-Python leg installs pinned
Optuna, Nevergrad and pycma and sets POLYPUS_REQUIRE_EXTERNAL_LIBRARIES=1,
so the tests of polypus.ask_tell that train through them run there
(contract C-5); elsewhere they skip unless you install them. It also
installs the CPU wheel of PyTorch, pinned, and sets POLYPUS_REQUIRE_TORCH=1,
so the tests of polypus.torch (tests/python/test_torch_quantum_layer.py
and the PyTorch cases of test_typing_stubs.py) run there (contract C-11);
the examples job installs the same PyTorch on both its legs, since it runs
examples/qml_torch_hybrid.py, and so does Sonar's coverage job, so that
polypus/torch.py is covered. Those pins are the floors of the pip extras of
the same names in pyproject.toml, which a test checks: bump a pin and its
floor together.
Every Python leg also sets POLYPUS_ALLOWED_SKIPS to the tests it may skip,
separated by spaces: a file (test_cunqa_real.py) or a class or test in it
(test_determinism_baseline.py::TestSameBuildStrict; a test covers its
parametrized cases). Any other skip fails the run and is listed at its end
(tests/python/skip_guard.py), as is an entry that matched no skip, which
does not fail it. A test that needs something a leg lacks either gets it
installed there or goes on that leg's list in .github/workflows/ci.yml.
Four jobs use another toolchain, the one the justfile names: msrv checks
the workspace with the MSRV (rust-version in Cargo.toml);
rust-minimal-versions resolves the dependency floors with a dated nightly
(and builds with the pinned Rust); fuzz and miri fuzz the OpenQASM
importers and run Miri over polypus-sim's unsafe kernels on that nightly.
A green run is a precondition for opening a PR, not something to fix afterwards.
Note: CI tests with
--workspaceinstead of listing crates one by one — a hand-maintained crate list silently goes stale every time a crate is added or split (it already happened once). The one deliberate exception is the all-features pass over the pure-Rust crates (pure_cratesin the justfile):--workspace --all-featureswould enableextension-module, which breaks building the test targets.
Performance claims have their own bar: before claiming a speed-up, back it
with the scripts in benchmarks/ (run_benchmarks.py,
bench_native_vs_qiskit.py, bench_batching.py) and include the numbers in
the PR description.
Building the docs¶
pip install -r requirements-docs.txt
mkdocs serve
mkdocs build --strict is the check CI runs: any broken link or page missing
from the nav fails it. The hook in docs/_hooks/repo_files.py turns links to
files outside docs/ into GitHub URLs; its tests run with pytest tests/docs.
Repository hygiene¶
.github/workflows/hygiene.yml runs .github/scripts/hygiene.py (standard
library only, Python ≥ 3.10) on every pull request and push to main. It
rejects:
- internal notes and local tool configuration that
.gitignorealready excludes, and any file added although a versioned.gitignoreignores it; - infrastructure data and credentials on added lines and in the messages of the analysed commits: cluster file-system paths, login-node and internal host names, private IPv4 addresses, private-key headers and GitHub tokens;
- notebooks under
tutorials/with outputs or execution counts; - blobs larger than 1 MiB;
- a
CITATION.cffversion different fromCargo.toml, or not an earlier release whenCargo.tomlisX.Y.Z-dev(contract C-6); - a change to
CHANGELOG.mdwhileCargo.tomlisX.Y.Z-dev: entries go inchangelog.d/(see Changelog entries); - submodules.
Run it before pushing:
python .github/scripts/hygiene.py --base origin/main
It analyses commits — the net diff between the merge base and HEAD —
not uncommitted changes, so commit first. Renamed files are analysed as new
files. Exit code 0 means clean, 1 violations, 2 a configuration or execution
error. The output names the file, line and rule, never the matched text.
A notebook with outputs is fixed with nbstripout <notebook>, then commit the
result; nbstripout --install once per clone prevents it.
Legitimate exceptions go in .github/hygiene-allow.txt, one per line as
RULE<TAB>PATTERN<TAB># reason: one rule, the narrowest path or glob, and a
reason. Forbidden names, notebooks, versions, CHANGELOG.md edits, submodules
and commit messages admit none: merge commits keep every message in the
history of main, so reword the commit instead (git commit --amend or
git rebase -i).
Changes to the allow list, the script, the workflow or the policy-relevant
.gitignore files need explicit human review.
Maintainers also run private patterns, stored as a repository secret, on each
push to main; pull requests never receive that secret, so a green PR means
the public rules passed. A post-merge finding cannot undo the publication.
The check covers the net diff only, not every intermediate commit nor the
existing history, and does not replace checking your own changes before
pushing.
Code quality dashboard¶
.github/workflows/sonar.yml sends the code to SonarQube Cloud on every pull
request and push to main (configuration in sonar-project.properties):
Rust coverage from cargo llvm-cov over the test (Rust) passes and over the
pytest suite, which runs against a wheel built with the same instrumentation,
the clippy report, and Python coverage of python/ from that pytest run. The
instrumented wheel simulates several times slower, so that run sets
POLYPUS_TEST_TIME_SCALE=10, which stretches the deadlines and timeouts of the
Ctrl+C tests in tests/python/test_interrupt.py by that factor; ci.yml runs
them with the bounds as written. The subprocess worker template
(crates/polypus-subprocess-backend/python/worker_template.py) is left out of
the coverage figures: it runs as a separate process spawned by the Rust
integration tests, which no tool instruments. So are the diagnostic binaries
under crates/*/src/bin/, which are run by hand. Sonar still analyses both
for issues. On pull requests the SonarQube Cloud scan job waits for the
quality gate and fails with it; pushes to main only report, and merge-queue
runs skip the workflow (the gate already ran on the PR). Without the
SONAR_TOKEN secret (pull requests from forks) the reports are still built
but not uploaded, and the job passes without a gate. Python coverage locally,
with the wheel installed:
python -m coverage run -m pytest tests/python && python -m coverage combine && python -m coverage report
Both coverage jobs also write their Rust line coverage per crate in the
job summary of the run (.github/scripts/coverage_summary.py), with or
without the token: the rust job for the test (Rust) passes, the python
job for the Rust the pytest suite reaches (the bindings above all). The
reports themselves are the run's sonar-rust and sonar-python artifacts,
kept 14 days. Neither job has a coverage threshold. The same table locally,
from a report of your own:
cargo llvm-cov --workspace --lcov --output-path lcov.info # needs cargo-llvm-cov
python .github/scripts/coverage_summary.py lcov.info
Mutation testing¶
Line coverage says which code the tests run, not whether they would notice it
change. .github/workflows/mutation.yml runs
cargo-mutants every Sunday over polypus-circuit,
polypus-sim, polypus-physics, polypus-optimizers, polypus-observable
and polypus-backend, with every feature: it makes small changes to the code
(a + into a -, a function body into a constant) and runs the crate's tests
against each. A mutant the tests fail on is caught; one they pass on is
missed, a behaviour no test checks. One job runs each crate, except the two
slowest, which are split into round-robin shards so that no job comes near the
runner's 6 h limit: polypus-circuit in two and polypus-sim in three
(--shard K/N --sharding round-robin, every N-th mutant). Each job writes its
caught, missed, timed-out and unviable mutants and the score, caught / (caught
+ missed), in its summary, and keeps missed.txt and outcomes.json as the
mutants-<crate>-<K>of<N> artifact for 30 days. The scheduled run then
comments one row per crate, its shards added up, on the issue titled
mutation: weekly score, which the workflow creates (or reopens) itself; a
crate one of whose shards did not run is listed as not run, with the reason.
It is report-only: missed mutants fail nothing, but cargo-mutants failing to
run (the unmutated tests failing, the step timing out) fails its job. A manual
run (workflow_dispatch) reports in the summaries only, unless its comment
input is set.
Every test process runs with a 6 GiB address-space cap (prlimit --as,
through cargo's target runner), because some mutants turn a loop into one that
allocates until the timeout, and two at once can exhaust the runner's 16 GB.
Such a mutant aborts on a failed allocation when it reaches the cap, and its
test fails: it counts as caught (one still under the cap when the timeout hits
counts as a timeout, as before). The unmutated tests of every crate pass well
under the cap.
To reproduce a crate's run, or to check that a new test catches a mutant,
install the version the workflow pins and run it on that crate (it copies the
tree to a temporary directory; mutants.out/ is ignored by git):
cargo install cargo-mutants --locked --version 27.1.0
cargo mutants --package polypus-observable --all-features # the whole crate
cargo mutants --package polypus-observable --all-features --list # its mutants, without running them
cargo mutants --package polypus-observable --all-features --file crates/polypus-observable/src/qubo.rs --re 'from_matrix'
cargo mutants --package polypus-sim --all-features --shard 1/3 --sharding round-robin # one CI job's shard
# As the CI job runs it, with the same cap on each test process (x86-64 Linux, util-linux's prlimit;
# on another target the variable name changes, and without the right one the cap is silently not applied):
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="prlimit --as=6442450944" \
cargo mutants --package polypus-sim --all-features --jobs 2 --shard 1/3 --sharding round-robin
Kill a missed mutant with a test of the behaviour it changes, not by excluding it; a mutant that no test can observe (an equivalent one) is worth a line in the PR, not an exclusion.
Lint policy¶
clippy.toml only tunes lint thresholds/behaviour. Lint levels are set in the
[workspace.lints] table of the root Cargo.toml, which every member crate
inherits with [lints] workspace = true (a new crate must add it too), and CI
runs clippy with -D warnings on top. The table denies:
clippy::all, so a Clippy finding fails a localcargo clippyas well as CI;unsafe_code:unsafeis allowed only at the sitesENGINEERING.md§5 authorises, each with its own block-scoped#[allow(unsafe_code)]. A newunsafeanywhere else does not compile until it has a benchmark, a// SAFETY:comment and maintainer sign-off, and its ownallow;clippy::undocumented_unsafe_blocks: everyunsafeblock, including the authorised ones, needs its// SAFETY:comment.
missing_docs is not in the table, because with -D warnings a workspace-wide
warn would fail every crate that still has undocumented public items. A crate
turns it on with #![warn(missing_docs)] in its lib.rs once it is fully
documented, and must then stay that way.
The workspace boundaries of ENGINEERING.md §2 (pyo3 only in the crates
allowed to touch Python) are enforced by cargo deny check, through the bans
section of deny.toml: it names the only crates that may depend directly on
pyo3 and on every crate that links it (pyo3-ffi, numpy and the
PyO3-touching workspace crates; nothing may depend on polypus).
Do not sprinkle #[allow(...)] to silence CI; if a lint is wrong for the whole
workspace, change the policy in one place and say why in the PR.
Commit messages¶
We use Conventional Commits:
fix(cunqa): align disconnect kwargs with contract C-1,
feat(circuit): add cp to the QASM importer, test(seam): mock CUNQA contract.
The type+scope prefix feeds the changelog; the subject line explains the
intent, not the action ("Update" tells a reviewer nothing).
Changelog entries¶
A user-visible change adds one file to changelog.d/
instead of editing CHANGELOG.md; the release pull request
assembles the files into CHANGELOG.md with
towncrier. Pull requests that all edited
CHANGELOG.md used to conflict with each other on the same lines. The
hygiene check rejects a CHANGELOG.md edit while Cargo.toml carries an
X.Y.Z-dev version.
- Name:
<issue>.<type>.md(504.added.md), or+<short-slug>.<type>.mdwhen there is no issue. A second entry of the same issue and type is504.added.1.md. - Type:
added,changed,deprecated,removed,fixedordocumentation, the###subsection the entry goes under. - Content: one entry, as it should read in the changelog, without the
leading
-. Keep the issue reference in the text, as in(#504), and mark breaking changes BREAKING at the start. - Preview the next release section:
pipx run --spec towncrier==26.9.0 towncrier build --draft --version next. A misnamed file fails that command, and the same check in CI. Within a section, entries are ordered by issue number, not by file suffix.
Pull requests¶
All changes land through a PR against main — the branch is protected: at
least one approving review from someone other than the author, CI green, and
the merge queue (see Merging).
The PR template asks for three declarations that we take seriously:
- Scope — which module(s) the change targets.
- Collateral files — every touched file outside that scope, each with a one-line justification. Unexplained collateral changes are the single most common source of regressions in this project.
- Contracts — whether the change touches anything listed in
docs/CONTRACTS.md. If it does, the same PR must update the contract document and its enforcing test. No seam change without a seam test.
Keep PRs small and single-purpose. If your work naturally produced unrelated improvements, split them out — small PRs get reviewed in hours, mixed ones sit for days.
Merging¶
main uses GitHub's merge queue. A PR does not need to be up to date with
main: once it is approved and green, press Merge when ready (or run
gh pr merge <N> --merge). The queue tests the PR on top of main and of the
PRs queued ahead of it, runs the required checks on that commit, and merges it
with a merge commit if they pass. Do not press Update branch just to
refresh CI; rebase only to resolve a conflict.
If the queue removes your PR, open the failed merge_group run:
- A real failure, usually a clash with a PR merged ahead of yours: fix it on your branch and queue again.
- A failure that does not reproduce: open an issue for the flaky test, quarantine it in the same or a follow-up PR, and queue again. A flaky test ejects every PR behind it, so it is not left in place.
Admins can bypass the queue; that is for emergencies only (the queue itself
is broken, or main must be fixed now).
Adding things that have a defined shape¶
- A gate: six places (OpenQASM 2.0 export and import, OpenQASM 3 export,
simulator, QIR export, Python bindings and their
.pyistub), the OpenQASM 3 importer ifstdgates.incnames the gate, plus a row in the vocabulary equivalence test — see contract C-2. - A backend/provider: one
BackendConfigvariant + oneQuantumBackendimpl + a contract entry + a seam test. Algorithms must not change. - An optimizer: implement
OptimizeragainstEvaluationOracle; respect contract C-5 (validated preconditions,best_fitness == f(best_params)). - A crate: inherit the workspace metadata (
version.workspace = true,edition.workspace = true,license.workspace = true, …), add it to[workspace] membersand — if other crates consume it — to[workspace.dependencies]. If it is pure Rust, also add it to CI's all-features test list (see the note above). Pure crates must not depend onpyo3— seedocs/ENGINEERING.md§2.
Reporting bugs and security issues¶
Use the issue tracker for bugs and feature requests. For anything with
security impact, do not open a public issue — follow
SECURITY.md instead.
License¶
Polypus is licensed under the European Union Public Licence (EUPL),
version 1.2 — see the LICENSE and NOTICE files and the license field in
the workspace Cargo.toml. By submitting a contribution you agree that it is
your own work (or you have the right to submit it) and that it is provided
under the project license.
Versioning and releases¶
Single source of truth: the workspace Cargo.toml version (SemVer). Release
tags must match it exactly (vX.Y.Z), and every release updates
CHANGELOG.md. Between releases main carries the next
patch version with a -dev suffix (0.8.1-dev after 0.8.0).
A pull request that breaks the public API of a crate published on crates.io
also raises the workspace version to the next minor (0.9.0-dev while the
version is 0.x), with cargo set-version --workspace and the backend
templates' lockfiles refreshed as in docs/RELEASING.md;
the semver CI job (cargo-semver-checks against the last published version)
fails otherwise.
Mark the change BREAKING in its changelog fragment. The release checklist lives
in docs/RELEASING.md.
AI-assisted development¶
AI-generated contributions are welcome and held to the same bar: they arrive with their tests, they respect the scope/collateral discipline above, and the author remains responsible for the diff.
Practical guidance for assistant sessions (Claude Code, Cursor, etc.):
- Include this file,
docs/CONTRACTS.mdanddocs/ENGINEERING.mdin the session context — all three are written for exactly that purpose. - Team members: the internal
CLAUDE.md(private repo, never committed here) mirrors the verification commands above; keep the two in sync when this section changes. - Before proposing a diff, run the same checks CI runs (see "Running the checks"). An assistant-produced PR with red CI is treated like any other red PR: it waits.