From 79f28b7a8fa32b8536566c15f7be0a63f671414e Mon Sep 17 00:00:00 2001 From: Paururo <50167687+Paururo@users.noreply.github.com> Date: Sat, 22 Aug 2026 08:53:45 +0200 Subject: [PATCH 1/2] Bring over the automations from get_MNV Dependabot with the shape get_MNV settled on, after its first attempt opened one pull request per dependency and led with majors: monthly, grouped, majors kept apart, and the routine group merging itself once CI passes. fuzz/ is deliberately left out. It is a separate workspace that CI never builds, so a bump there would merge on the strength of a green run that never compiled it. The labeler, with globs for this project rather than get_MNV's: parser, distances, cli, tests, ci, packaging, documentation. Twelve labels created to go with it. CodeQL over rust and the workflows themselves, which is not a curiosity: those queries know about unsafe uses of pull_request_target, and the labeler runs on exactly that trigger. Dependency review to refuse a new dependency with a known advisory, which is the half Dependabot does not cover. Issue forms, a pull request template, and the community health files. The stale sweep is the one scheduled workflow, the same exception you asked for in get_MNV: a maintenance sweep has nothing to hang off except time. Which is also why crossvalidate.yml lost its weekly cron in this commit. I put it there and should not have: it builds and tests, and a build-or-test job on a timer is the thing you asked not to have. Mutation testing, scoped to the library. It was run first rather than added blind: 478 mutants, 397 caught. The survivors in main.rs are argument handling and warning text, so the scope excludes it; the ten in the library are documented one by one in .cargo/mutants.toml, including the two that looked like real gaps and turned out not to be. One of them took a probe to settle: skip_whitespace_bytes looks dead, and making it panic if it ever skipped anything proved it is not, because a malformed quote leaves whitespace the stripper could not see. --- .cargo/mutants.toml | 72 +++++++++++ .github/CODE_OF_CONDUCT.md | 128 ++++++++++++++++++++ .github/CONTRIBUTING.md | 61 ++++++++++ .github/ISSUE_TEMPLATE/bug_report.yml | 104 ++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 22 ++++ .github/ISSUE_TEMPLATE/feature_request.yml | 38 ++++++ .github/SECURITY.md | 34 ++++++ .github/dependabot.yml | 83 +++++++++++++ .github/labeler.yml | 60 +++++++++ .github/pull_request_template.md | 34 ++++++ .github/workflows/codeql.yml | 62 ++++++++++ .github/workflows/crossvalidate.yml | 9 +- .github/workflows/dependabot-auto-merge.yml | 90 ++++++++++++++ .github/workflows/dependency-review.yml | 35 ++++++ .github/workflows/labeler.yml | 38 ++++++ .github/workflows/mutants.yml | 94 ++++++++++++++ .github/workflows/stale.yml | 73 +++++++++++ .gitignore | 7 ++ src/lca.rs | 50 ++++++++ 19 files changed, 1091 insertions(+), 3 deletions(-) create mode 100644 .cargo/mutants.toml create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/SECURITY.md create mode 100644 .github/dependabot.yml create mode 100644 .github/labeler.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/codeql.yml create mode 100644 .github/workflows/dependabot-auto-merge.yml create mode 100644 .github/workflows/dependency-review.yml create mode 100644 .github/workflows/labeler.yml create mode 100644 .github/workflows/mutants.yml create mode 100644 .github/workflows/stale.yml diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 0000000..55e992d --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1,72 @@ +# Mutation testing configuration. +# +# `cargo mutants` changes the source (flips a comparison, replaces a function +# body with a default) and reports whether the test suite notices. A surviving +# mutant is a piece of logic no test distinguishes: either a test is missing, or +# the logic does not do anything, and both are worth knowing. +# +# It is advisory. A surviving mutant is a question, not a defect, and it never +# fails CI. + +# The library: everything that decides what a distance is. `src/main.rs` is +# outside this on purpose. It is argument handling, warning text and output +# plumbing, and most of its mutants are equivalent: the batch and buffer size +# constants change how fast the run is and not what it prints, and the warning +# conditions change wording. The integration tests cover its behaviour +# end-to-end, which is the right granularity for a command line. +# +# The one part of main.rs worth mutating is `write_fixed_fast`, and it does not +# need this: it is checked directly against the standard formatter over 200,000 +# random values, along the rounding boundaries at every precision, and on +# subnormals and signed zero. A mutation of it fails that immediately. +examine_globs = [ + "src/lib.rs", + "src/parser.rs", + "src/lca.rs", + "src/midpoint.rs", + "src/tree.rs", +] + +# Generated trees for the randomised checks, not logic anything depends on. +exclude_globs = ["src/testutil.rs"] + +# The unit tests finish in well under a second, so anything still running after +# a minute is a mutant that made the code loop rather than one under test. There +# are twenty of those in the parser, which is what a mutated `pos += 1` in a +# byte scanner does, and they are reported as timeouts rather than survivors. +timeout_multiplier = 5.0 +minimum_test_timeout = 60 + +# Ten mutants survive in this scope as of the run that wrote this file, out of +# roughly 250. They fall into three groups, named rather than chased: +# +# - Four are equivalent, in the sense that the mutated code is still correct: +# `depth_top[u] < depth_top[v]` in `mrca` becoming `<=` only changes which of +# two equally deep nodes is swapped; `dist_u > best_dist` in `farthest_from` +# becoming `>=` picks a different tie among equally distant leaves, and both +# are valid diameter endpoints; and `path.len() - 1` in `midpoint_root` +# becoming `+` or `/` is unreachable, because the loop always returns from +# inside before it runs off the end. +# +# - One is the `+ 1` in `levels`, and it took a while to accept. Two attempts +# were made to kill it, with a ladder and with two deep chains, and both +# passed with the level removed. The reason is that the second phase of `mrca` +# is a greedy descent that accumulates jumps rather than taking one: it can +# climb 2^levels - 1 in total, which is at least n - 1, which is at least the +# depth of any tree with n nodes. `ceil(log2 n)` levels is therefore already +# sufficient and the `+ 1` is margin. It stays, because margin on the +# structure the whole tool depends on is worth eight bytes a node. +# +# - Three are in `skip_whitespace_bytes`, which looks dead: the whitespace +# outside quoted labels is already gone by the time the parser runs. It is not +# dead. Making it panic if it ever skipped anything, and running the suite, +# found an input from the torture test that reaches it, because a malformed +# quote leaves whitespace inside what the stripper took for a quoted region. +# No unit test reaches it, which is what the mutants are reporting. +# +# - The last two only change which error message an invalid tree gets, in +# `parse_newick` and `parse_label_bytes`. Both inputs are rejected either way. +# +# `test_lifting_table_is_deep_enough_for_a_ladder` in src/lca.rs came out of +# this run: it does not kill a mutant, but nothing else put a tree that deep +# through the LCA path at all. diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..04b3659 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +paula.ruiz.rodriguez@csic.es. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..8b57899 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing + +Issues and pull requests are welcome at +[PathoGenOmics-Lab/distree](https://github.com/PathoGenOmics-Lab/distree). + +The fullest version of this is on the documentation site, under +[Contributing](https://pathogenomics-lab.github.io/distree/about/contributing/). +What follows is the short form. + +## Reporting a problem + +The most useful bug report is one somebody else can run: the exact command, the +version, a tree that still shows it, and what you expected against what you got. + +The dangerous failures here are the quiet ones. A matrix that is wrong looks +exactly like a matrix that is right, so a report saying "these distances +disagree with `ape::cophenetic` and here are both" is worth more than a stack +trace. + +If the tree carries anything identifiable, do not attach it. Tip labels can be +replaced with `S1`, `S2` and so on without changing the behaviour. + +## Building and checking + +```bash +cargo build --release +cargo test +cargo test --release +cargo clippy --all-targets -- -D warnings +``` + +CI runs all four on every push and every pull request. A change that fails any +of them will not go in. + +Two deeper checks are run on purpose rather than on every push: + +```bash +# Against ape, over 250 generated trees. Needs R with ape and phangorn. +Rscript scripts/crossvalidate.R 250 target/release/distree + +# Coverage-guided fuzzing. Needs a nightly toolchain. +cargo +nightly fuzz run parse_newick fuzz/seeds +``` + +## Conventions the code follows + +- **Refuse rather than guess.** If the input is ambiguous or truncated, error + with the position. A matrix that looks right and is not costs more than a + failed run. +- **Warnings go to stderr**, never into the matrix, so a piped run stays clean. +- **Keep the tree traversals iterative.** The parser, the flattener, the LCA + build and `RawNode`'s `Drop` are all loops with explicit stacks, because a + ladder-shaped tree hundreds of thousands of levels deep is a real input. +- **Do not put work in the serial write loop.** Whatever a worker can do to its + own row, it should, including formatting the numbers. +- **Output is byte-identical unless the change is about the output.** If it + changes, say so in the pull request: it is a change to everyone's files. + +## Code of conduct + +By taking part you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..53229d4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,104 @@ +name: Bug report +description: distree crashed, refused a tree it should accept, or produced numbers that are wrong +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to report this. + + The failures worth reporting here are not only the loud ones. A run that + finishes and returns a matrix that looks entirely reasonable and is + wrong is the more expensive kind, and the harder one to notice, so a + report saying "these distances disagree with `ape::cophenetic` and here + are both" is worth more than a stack trace. + + If distree **refused** your tree, check + [Input](https://pathogenomics-lab.github.io/distree/guide/input/) first: + several things it used to accept are now rejected on purpose, because + accepting them produced a wrong matrix rather than an error. + + - type: input + id: version + attributes: + label: Version + description: The output of `distree --version`. + placeholder: distree 1.0.1 + validations: + required: true + + - type: dropdown + id: install + attributes: + label: How it was installed + options: + - Bioconda (conda install -c bioconda distree) + - Binary from the Releases page + - Built from source (cargo build --release) + - Other + validations: + required: true + + - type: dropdown + id: os + attributes: + label: Operating system + options: + - Linux (x86-64) + - Linux (arm64) + - macOS (Apple silicon) + - macOS (Intel) + - Other + validations: + required: true + + - type: textarea + id: command + attributes: + label: The command + description: The whole thing, with every flag. + placeholder: distree tree.nwk --midpoint --lmm -p 8 -o varcovar.tsv + render: shell + validations: + required: true + + - type: textarea + id: expected + attributes: + label: What you expected, and what you got + description: >- + If the numbers are wrong rather than absent, say how you know: the tool + you compared against, the pair of tips that disagrees, and both values. + validations: + required: true + + - type: textarea + id: output + attributes: + label: What it printed + description: Everything on stderr, including any warnings before the error. + render: shell + + - type: textarea + id: tree + attributes: + label: The tree + description: >- + The smaller the better. A tree with the labels replaced by S1, S2, ... + usually still reproduces the problem, and a generated tree of the same + shape often does too. + + + **Do not attach anything identifiable.** Sample names in a Newick file + are data like any other. + render: text + + - type: checkboxes + id: checks + attributes: + label: Before submitting + options: + - label: I am on the latest release, or I have said above why not. + required: true + - label: The tree above reproduces it, or I have said why I cannot share one. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..17d5fe1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,22 @@ +# Blank issues stay available. The forms cover the reports that arrive most +# often, but a small tool gets questions that fit no form, and having nowhere to +# put them is worse than an unstructured issue. +# +# There is no Q&A link here because Discussions are not enabled on this +# repository. If they are turned on, add one: an answer in Q&A gets marked as the +# answer and the next person finds it, while an answer in an issue is seen once. +blank_issues_enabled: true + +contact_links: + - name: Documentation + url: https://pathogenomics-lab.github.io/distree/ + about: The CLI reference, the output formats, and what the three distance modes mean. + - name: Tutorial + url: https://pathogenomics-lab.github.io/distree/tutorial/ + about: A worked outbreak investigation, from the tree to transmission clusters. + - name: What distree accepts and rejects + url: https://pathogenomics-lab.github.io/distree/guide/input/ + about: Worth a look first if it refused your tree. + - name: Report a security vulnerability + url: https://github.com/PathoGenOmics-Lab/distree/security/advisories/new + about: Please report vulnerabilities privately rather than in a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..7ab4662 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,38 @@ +name: Feature request +description: Something distree should do and does not +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + distree works on the tree you give it: it does not build one, does not + read an alignment, and does not cluster the matrix. Requests that stay + inside that are the ones most likely to happen. + + - type: textarea + id: problem + attributes: + label: What you are trying to do + description: >- + The analysis, not the feature. What the tool should let you do is much + easier to judge than a flag on its own, and there is often a way to do + it already. + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: What you have in mind + description: A flag, an output format, a mode. A sketch of the command line helps. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: How you are doing it now + description: >- + The workaround, if there is one, and where it falls down. "I pipe it + through awk and it breaks on labels with spaces" says more than a + paragraph of rationale. diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..d713c43 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,34 @@ +# Security policy + +## Supported versions + +The latest release. distree is a single binary with no network access and no +server component, so "supported" here means fixes go into the next release +rather than into a maintenance branch. + +## Reporting a vulnerability + +Report it privately, through +[GitHub's advisory form](https://github.com/PathoGenOmics-Lab/distree/security/advisories/new), +rather than in a public issue. + +What is in scope is narrower than it looks for a tool of this shape, and worth +naming. distree reads a Newick file and writes a matrix. It opens no sockets, +runs no subprocesses, and executes nothing from its input. The realistic +concerns are: + +- A crafted tree that makes it read or write out of bounds. The parser is + hand-written and scans bytes, so this is the one worth looking hardest at. It + is fuzzed for exactly this, in `tests/torture.rs` on every push and with + `cargo fuzz` for longer runs. +- A crafted tree that makes it allocate without bound, or loop forever. +- A path handling bug in `-o` or `--taxa`. + +A tree that produces a *wrong matrix* is a correctness bug rather than a +security one, and belongs in a normal issue where it can be discussed openly. +It is still the most valuable kind of report this project gets. + +## What to expect + +An acknowledgement within a week. If it is confirmed, a fix and a release, with +credit in the advisory unless you would rather not have it. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9b23b46 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,83 @@ +# Dependency updates. +# +# Shaped after get_MNV's, which was itself a second attempt: the first opened one +# pull request per dependency and led with major bumps, and all of them were +# closed unread. The updates were not the problem, the shape was. So: +# +# * monthly, not weekly +# * grouped, so one pull request carries a whole ecosystem's routine bumps +# * majors kept apart, in their own pull request, because those change APIs +# and want a person +# +# The minor and patch group merges itself once CI passes; see +# .github/workflows/dependabot-auto-merge.yml. The major group never does. +# +# `schedule` here is Dependabot's own timer, not a cron in GitHub Actions: no +# workflow in this repository runs on a schedule. +# +# Security updates are a separate mechanism, enabled in the repository settings +# and unaffected by any of this: a vulnerable dependency gets its own pull +# request the day the advisory lands, major or not. + +version: 2 + +updates: + # The crate itself. Four dependencies, so the routine group is usually one or + # two lines, which is the point. + - package-ecosystem: cargo + directory: "/" + schedule: + interval: monthly + open-pull-requests-limit: 3 + labels: ["dependencies", "rust"] + commit-message: + prefix: "cargo" + groups: + cargo-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + cargo-major: + patterns: ["*"] + update-types: ["major"] + + # The documentation site's build dependencies, in requirements-docs.txt. + - package-ecosystem: pip + directory: "/" + schedule: + interval: monthly + open-pull-requests-limit: 2 + labels: ["dependencies", "documentation"] + commit-message: + prefix: "docs" + groups: + docs-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + docs-major: + patterns: ["*"] + update-types: ["major"] + + # The actions the workflows pin. These go stale silently: a deprecated runner + # image or a Node version dropped from an action is only noticed when a job + # starts warning, or fails. + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: monthly + open-pull-requests-limit: 2 + labels: ["dependencies", "github-actions"] + commit-message: + prefix: "actions" + groups: + actions-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + actions-major: + patterns: ["*"] + update-types: ["major"] + +# fuzz/ is deliberately not listed. It is a separate workspace that resolves its +# own versions, it needs a nightly toolchain, and CI never builds it. A bump +# there would be merged on the strength of a green run that never compiled the +# thing being bumped, which is worse than not bumping it. Update it by hand when +# a fuzzing session is actually planned. diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000..e3f387b --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,60 @@ +# Which part of the project a pull request touches, worked out from the files it +# changes. The labels exist so the issue and pull request lists can answer "what +# is going on in the parser"; applying them by hand is how they stop being +# applied. +# +# The issue forms label their own issues, so this only has to cover pull +# requests. +# +# Format is actions/labeler v5, which is not v4's: a bare list of globs under the +# label name silently matches nothing. + +parser: + - changed-files: + - any-glob-to-any-file: + - "src/parser.rs" + +distances: + - changed-files: + - any-glob-to-any-file: + - "src/lib.rs" + - "src/lca.rs" + - "src/midpoint.rs" + - "src/tree.rs" + +cli: + - changed-files: + - any-glob-to-any-file: + - "src/main.rs" + +documentation: + - changed-files: + - any-glob-to-any-file: + - "docs/**" + - "mkdocs.yml" + - "README.md" + - "requirements-docs.txt" + +tests: + - changed-files: + - any-glob-to-any-file: + - "tests/**" + - "fuzz/**" + - "scripts/crossvalidate.R" + - "src/testutil.rs" + +packaging: + - changed-files: + - any-glob-to-any-file: + - ".github/workflows/release.yml" + - "Cargo.toml" + - "CITATION.cff" + +# Everything under .github, not a list of the files there. Naming them one by one +# leaves this file itself uncovered, so the pull request adding a rule arrives +# with no label, which is a small thing that says exactly how the list would age. +ci: + - changed-files: + - any-glob-to-any-file: + - ".github/**" + - "scripts/**" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..627aa63 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,34 @@ + + +## What this changes + + + +## Why + + + +## How it was verified + + + +## Checklist + +- [ ] `cargo test` passes, in debug and release. +- [ ] `cargo clippy --all-targets -- -D warnings` is clean. +- [ ] New behaviour has a test, or I have said above why it does not. +- [ ] Documentation under `docs/` is updated if the change is user-visible. +- [ ] If the output changed, I have said so: byte-identical output is the + default expectation, and a change to it is a change to everyone's files. diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..6df8971 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,62 @@ +name: CodeQL + +# Static analysis over the code. Nothing here looked at it this way before: +# clippy checks the shape of a line and the test suites check the answer, while +# these queries follow a value across functions and files and ask where an +# unchecked one arrives somewhere it matters. +# +# Two languages, which is all of them: +# +# rust the parser, the tree structures and the CLI +# actions the workflows themselves, including this one +# +# That second one is not a curiosity. These queries know about unsafe uses of +# `pull_request_target`, which is the trigger `labeler.yml` runs on, and about +# script injection through untrusted context values. Reasoning that a workflow is +# safe is exactly the kind of reasoning worth having checked by something that is +# not the person who wrote it. +# +# On pushes to main and on pull requests, with no schedule. GitHub's own default +# setup adds a weekly run; this does not, in keeping with every other workflow +# here except the issue sweep, which has nothing but time to hang off. +# +# `build-mode: none` reads the source without compiling it, which is what makes +# this take a minute rather than a full release build. + +on: + push: + branches: [main] + pull_request: + +# A newer push makes an older analysis irrelevant, the same as CI. +concurrency: + group: codeql-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + security-events: write + contents: read + actions: read + +jobs: + analyze: + name: Analyse ${{ matrix.language }} + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + language: [rust, actions] + steps: + - uses: actions/checkout@v4 + + - name: Initialise CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + build-mode: none + + - name: Analyse + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/crossvalidate.yml b/.github/workflows/crossvalidate.yml index 5af4e56..80a3a40 100644 --- a/.github/workflows/crossvalidate.yml +++ b/.github/workflows/crossvalidate.yml @@ -3,11 +3,14 @@ name: Cross-validate against ape # The committed fixtures in tests/fixtures/ let `cargo test` check six trees # against ape everywhere, with no R needed. This job runs the same comparison # over 250 freshly generated trees, which is the deeper check but needs an R -# toolchain, so it runs weekly and on demand rather than on every push. +# toolchain, so it is run on purpose rather than on every push. +# +# By hand only, no schedule. A build-or-test job on a timer spends minutes every +# week and reports failures nobody asked for, and nobody is watching when it +# goes wrong. Run it before a release, or after touching anything the distances +# depend on. on: - schedule: - - cron: "0 6 * * 1" workflow_dispatch: inputs: trees: diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 0000000..da18e90 --- /dev/null +++ b/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,90 @@ +name: Dependabot auto-merge + +# Merges Dependabot's routine updates once CI has passed, and never touches a +# major one. +# +# The point of the split is that a minor or patch bump that survives the whole +# suite (96 tests in debug and release, clippy over every target, the ape +# fixtures, the mutation and fuzz corpora, and a strict docs build) has already +# been examined more carefully than a person would examine it by eye, while a +# major bump changes APIs and wants a person to look. +# +# Triggered by the pull request itself, not by a schedule. + +on: pull_request + +permissions: + contents: write + pull-requests: write + +jobs: + auto-merge: + name: Merge routine updates once CI is green + runs-on: ubuntu-latest + timeout-minutes: 10 + if: github.event.pull_request.user.login == 'dependabot[bot]' + steps: + - name: Read what this pull request updates + id: metadata + uses: dependabot/fetch-metadata@v3 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + + # The rule, decided once. + # + # It used to be written twice, once negated for the step that explains + # itself, and the two halves drifted the moment the first was edited: a + # grouped patch matched the merge step and the "left alone" step at the + # same time, so it would have merged and announced that it had not. One + # step decides, the other two read the answer. + # + # Named rather than excluded: merge when the pull request says in so many + # words that it is a patch or a minor, or when it is a `-routine` group, + # which the configuration already restricts to those two. + # + # Asking instead whether the update was "not major" let one through. A pip + # requirement bump, `pillow ~=11.0` to `~=12.3`, reports no update type at + # all, and an empty string is not equal to major, so the rule said yes to + # a major on its first day. Anything this cannot positively identify still + # waits for a person. + # + # The update-type test once applied only to ungrouped pull requests, + # because it was unclear what a grouped one reports. It reports "the + # highest semver change being made by this PR", so a group carrying one + # major is a major here. That is what lets the coupled npm families in + # dependabot.yml hold patches and majors alike without a major slipping + # through on the back of a patch. + - name: Decide whether this one may merge itself + id: decide + env: + GROUP: ${{ steps.metadata.outputs.dependency-group }} + UPDATE_TYPE: ${{ steps.metadata.outputs.update-type }} + run: | + set -euo pipefail + may_merge=false + case "$GROUP" in + *-routine) may_merge=true ;; + esac + case "$UPDATE_TYPE" in + version-update:semver-patch|version-update:semver-minor) may_merge=true ;; + esac + # Printed because a decision nobody can read is a decision nobody can + # correct: this line is what a later surprise gets diagnosed from. + echo "group='${GROUP}' update-type='${UPDATE_TYPE}' -> may-merge=${may_merge}" + echo "may-merge=${may_merge}" >> "$GITHUB_OUTPUT" + + - name: Queue the merge + if: steps.decide.outputs.may-merge == 'true' + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Say why this one was left alone + if: steps.decide.outputs.may-merge != 'true' + run: | + gh pr comment "$PR_URL" --body \ + "Left for review. Only a \`-routine\` group, or an update that identifies itself as patch or minor, merges on its own once CI passes. This one is a major update or does not say which it is." + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..ed83421 --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,35 @@ +name: Dependency review + +# Stops a pull request that would bring in a dependency with a known +# vulnerability, which is the half of the problem Dependabot does not cover. +# Dependabot tells you about a vulnerable dependency you already have; this +# refuses the one you are about to add, while refusing it is still free. +# +# It compares the dependency graph of the base against the head, so it only ever +# has an opinion about what the pull request itself introduces. Everything +# already in the tree is a separate conversation. +# +# `moderate` rather than the default `low`: a low severity advisory on a +# transitive build dependency is worth reading and is not worth blocking a merge +# on, and a gate that blocks for things nobody acts on stops being read. + +on: pull_request + +permissions: + contents: read + # For the summary comment it leaves when it refuses one. + pull-requests: write + +jobs: + review: + name: No new dependency with a known vulnerability + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/dependency-review-action@v4 + with: + fail-on-severity: moderate + # Only when it has something to say. A summary on every pull request + # is a summary nobody reads by the third one. + comment-summary-in-pr: on-failure diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000..e4ec502 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,38 @@ +name: Label pull requests + +# Puts the part-of-the-project labels on a pull request from the files it +# changes, so the labels are there when someone wants to filter by them. +# Configuration lives in .github/labeler.yml. +# +# `pull_request_target` rather than `pull_request` because a pull request from a +# fork gets a read-only token on `pull_request`, and labelling needs write. It +# runs the workflow from the base branch and never checks out or executes the +# pull request's code, which is what makes that safe here: this job reads the +# list of changed filenames and writes labels, and touches nothing from the +# branch it is labelling. +# +# It cannot label the pull request that introduces it, for the same reason: the +# workflow that runs is the one on the base branch, which does not have this +# file yet. + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +permissions: + contents: read + pull-requests: write + +jobs: + label: + name: Apply labels from the files changed + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/labeler@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + # Off on purpose. With it on, the action removes any configured label + # the files no longer justify, including one a person put there + # deliberately. + sync-labels: false diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml new file mode 100644 index 0000000..24ea3d3 --- /dev/null +++ b/.github/workflows/mutants.yml @@ -0,0 +1,94 @@ +name: Mutation testing (advisory) + +# `cargo mutants` changes the source (flips a comparison, replaces a function +# body with a default) and reports whether the test suite notices. A surviving +# mutant is a piece of logic no test distinguishes: either a test is missing, or +# the logic does nothing, and both are worth knowing. +# +# It is run by hand rather than on every push, because it builds and tests once +# per mutant. It never fails the build: a surviving mutant is a question to look +# at, not a defect. +# +# Scope, test selection and timeouts live in `.cargo/mutants.toml` so a local run +# matches this one. +# +# Split across four shards. The configured scope generates 307 mutants, and a +# mutant costs about 2.4 seconds on a warm laptop, so the whole run is about +# twelve minutes there and rather more on a runner. Four shards keep each job +# inside its limit with room to spare. + +on: + workflow_dispatch: + +# It reads the repository, mutates a copy of the source in a scratch directory +# and uploads a report as an artifact. It writes nothing back here. +permissions: + contents: read + +jobs: + mutants: + name: Shard ${{ matrix.shard }} of 0 to 3 + runs-on: ubuntu-latest + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + # Zero-indexed, which the flag's own help does not say: it gives `1/4` as + # the example. Numbering these 1 to 4 quietly skips shard 0 and runs an + # empty shard 4, covering three quarters of the mutants while reporting a + # full set of results. + shard: [0, 1, 2, 3] + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install cargo-mutants + run: cargo install cargo-mutants --locked + - name: Run mutation testing + # Surviving mutants exit non-zero; that is a report, not a failure. + continue-on-error: true + run: cargo mutants --no-shuffle --shard ${{ matrix.shard }}/4 + - name: Upload this shard's report + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutants-report-${{ matrix.shard }} + path: mutants.out/ + retention-days: 30 + + summary: + name: Surviving mutants, all shards + needs: mutants + # The shards are advisory and one may fail on its own; the report is still + # worth assembling from the ones that finished, and it says which did not. + if: always() + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Collect the shard reports + uses: actions/download-artifact@v4 + with: + pattern: mutants-report-* + path: shards + - name: Write the summary + run: | + set -euo pipefail + { + echo "## Surviving mutants" + echo + arrived=$(find shards -maxdepth 1 -type d -name 'mutants-report-*' | wc -l) + echo "Reports from ${arrived} of 4 shards." + echo + # Sorted so the same set of survivors reads the same way between + # runs: the shards finish in whatever order they finish. + if find shards -name missed.txt -size +0 | read -r _; then + echo "Logic no test distinguishes. Each line is a question: is a test" + echo "missing, or does the code not do anything?" + echo + echo '```' + find shards -name missed.txt -exec cat {} + | LC_ALL=C sort + echo '```' + else + echo "None: every mutant in the examined code was caught." + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..0e550e8 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,73 @@ +name: Close abandoned issues + +# Marks issues nobody has touched in three months, and closes them a month after +# that if still nothing. The point is not tidiness: an issue list where half the +# entries are questions someone stopped caring about is a list nobody reads, and +# then the real reports get missed too. +# +# This is the only scheduled workflow here, and it is deliberate. Everything else +# runs on a push, a pull request or by hand, because a workflow that fires on a +# timer is one nobody is watching when it goes wrong. A stale sweep has nothing +# to hang off except time, so it gets the exception rather than the rule getting +# dropped. The same exception was made in get_MNV, for the same reason. +# +# It is set up so that being wrong is cheap: +# +# * Three months of silence, then another month before anything closes. A +# report from someone who is waiting on a reply is not abandoned. +# * Anything labelled `bug`, `security` or `pinned` is never touched. A +# confirmed defect does not stop existing because nobody commented on it. +# * Pull requests are left alone entirely. +# * A closed issue can be reopened by anyone with a comment, and the message +# says so. +# +# `workflow_dispatch` is here too, so the sweep can be run and watched on purpose +# rather than only meeting it after the fact. + +on: + schedule: + # Mondays at 06:00 UTC. Weekly is far more often than this repository needs; + # it is the cheapest way to keep the batch small enough to look at. + - cron: "0 6 * * 1" + workflow_dispatch: + +permissions: + issues: write + pull-requests: read + +jobs: + stale: + name: Sweep issues nobody has touched + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/stale@v9 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + + days-before-issue-stale: 90 + days-before-issue-close: 30 + stale-issue-label: stale + exempt-issue-labels: "bug,security,pinned,good first issue,help wanted" + + # Pull requests are out of scope. The ones that arrive here are mostly + # Dependabot's and are merged or closed within the day; a sweep would + # only ever catch one a person is still working on. + days-before-pr-stale: -1 + days-before-pr-close: -1 + + stale-issue-message: > + No activity here for three months, so this is marked stale. If it is + still relevant, a comment is enough to keep it open, and it will be + closed in a month otherwise. Nothing labelled bug, security or pinned + is ever marked this way, so if this is a defect that was never + labelled as one, say so and it will be. + + close-issue-message: > + Closed after four months without activity. This is housekeeping and + not a judgement: comment and it reopens, and the history stays here + either way. + + # The default. Small enough that a bad configuration cannot sweep the + # whole tracker before anyone notices. + operations-per-run: 30 diff --git a/.gitignore b/.gitignore index e47dfd9..4e9462e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,10 @@ target/ # MkDocs build output and the Material plugin cache site/ .cache/ + +# cargo-mutants scratch output +mutants.out/ +mutants.out.old/ + +# macOS +.DS_Store diff --git a/src/lca.rs b/src/lca.rs index 2491274..bb46419 100644 --- a/src/lca.rs +++ b/src/lca.rs @@ -187,6 +187,56 @@ mod tests { panic!("no common ancestor between {} and {}", u, v); } + #[test] + fn test_lifting_table_is_deep_enough_for_a_ladder() { + // The table needs a level for every power of two up to the deepest node. + // The random trees below are balanced enough that one level short still + // answers every query, so nothing there notices if `levels` is computed + // too small. A ladder is the worst case: depth grows with the node count + // rather than its logarithm. + // + // Only pairs involving the deepest leaf are checked, which is where a + // short table goes wrong and is O(depth) rather than O(nodes squared). + let depth = 400; + let mut newick = String::new(); + for _ in 0..depth { + newick.push('('); + } + newick.push_str("A:1"); + for i in 0..depth { + newick.push_str(&format!(",L{}:1):1", i)); + } + newick.push(';'); + + let (nodes, root) = make(&newick); + let lca = build_lca_structure(root, &nodes); + + let deepest = (0..nodes.len()).max_by_key(|&i| lca.depth_top[i]).unwrap(); + assert!( + lca.depth_top[deepest] >= depth, + "expected a ladder at least {} deep, got {}", + depth, + lca.depth_top[deepest] + ); + + for other in 0..nodes.len() { + assert_eq!( + lca.mrca(deepest, other), + mrca_by_walking(&nodes, deepest, other), + "mrca(deepest, {}) on a ladder {} deep", + other, + depth + ); + assert_eq!( + lca.mrca(other, deepest), + mrca_by_walking(&nodes, other, deepest), + "mrca({}, deepest) on a ladder {} deep", + other, + depth + ); + } + } + #[test] fn test_mrca_matches_walking_up_on_random_trees() { let mut rng = Rng::new(0x2545_F491_4F6C_DD1D); From 494e54e605471c9580fd25ecdeb7b1717a382547 Mon Sep 17 00:00:00 2001 From: Paururo <50167687+Paururo@users.noreply.github.com> Date: Sat, 22 Aug 2026 08:58:02 +0200 Subject: [PATCH 2/2] Use as_chunks in the npy test reader Rust 1.98's clippy added chunks_exact_to_as_chunks, so this turned CI red on the next run against stable. The code is already on main, which means main is red too until this lands: it is a new lint on old code rather than anything this branch introduced. Same reading, one less unwrap: as_chunks gives [u8; 8] directly instead of a slice that has to be converted at every element. --- tests/integration.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/integration.rs b/tests/integration.rs index 3c5e72b..4245603 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -309,10 +309,9 @@ fn read_npy(path: &std::path::Path) -> (String, Vec) { let data = &bytes[10 + header_len..]; assert_eq!(data.len() % 8, 0, "payload is whole f64s"); - let values = data - .chunks_exact(8) - .map(|c| f64::from_le_bytes(c.try_into().unwrap())) - .collect(); + let (chunks, rest) = data.as_chunks::<8>(); + assert!(rest.is_empty(), "payload is whole f64s"); + let values = chunks.iter().copied().map(f64::from_le_bytes).collect(); (header, values) }