Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ to loosen. Change a rule only in that test and here, in the same PR, with the re
a budget failure means.
6. **Ratchets only go down** (`tests/test_code_shape.py`, `scripts/ci/sonar_ratchet.py`): no module under `src/` over
1000 lines; ruff C901 counts per file pinned in `tests/complexity_baseline.json`; open code-scan issues on `main`
equal to `sonar-baseline.txt`. A change that fixes one lowers the pinned number in the same commit; nothing is ever raised.
never above `sonar-baseline.txt`, and every pull request fails while `main` sits below it, so the PR after a fixing
merge lowers it (`scripts/ci/sonar_ratchet.py`). A change that fixes one lowers the pinned number in the same commit;
nothing is ever raised.

### Writing tests that prove something

Expand Down
2 changes: 1 addition & 1 deletion docs/development/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ sharpit 0.3.0 passed the full local gate and still failed three of these jobs on
|---|---|---|
| `test` (Python 3.12, 3.13, 3.14; Windows 3.14) | the full suite on every leg; lint, format, pyright strict and the github.com link check on the Ubuntu 3.12 leg only (version-independent: pyright pins 3.12). uv's cache is on in every job. The suite runs in `test shard (os, python, i/n)` jobs; each required `test (os, python)` check only reports whether every shard passed (see *Shards* below) | `uv sync --locked --extra test && uv run ruff check && uv run ruff format --check && uv run pyright && uv run pytest -q -n auto` (add `--python 3.12` / `3.14` to change interpreter; `SHARPIT_SHARD=2/4` runs one shard) |
| `coverage` | coverage for the code-scan, with the `sys.monitoring` tracer, in three `coverage shard (i/3)` jobs; `coverage` fails unless every shard passed, then `coverage combine`s their data into the `coverage.xml` sonar reads. Every overhead budget test skips itself while a tracer runs (`tests/overhead.py::paired`) and the plain `test` legs enforce it | `COVERAGE_CORE=sysmon COVERAGE_FILE="$TEMP/.coverage" uv run pytest -q -n auto --cov=sharpit --cov-report=xml`. Subprocess runs (pytester) are measured through `[tool.coverage.run] patch = ["subprocess"]`. `COVERAGE_FILE` must stay outside the repo: `no_side_effects` treats files in the cwd as writes |
| `sonar` (needs `coverage`) | the code-scan quality gate (new-code coverage ≥ 85%, no new issues) and the ratchet: open issues on `main` equal `sonar-baseline.txt` | not reproducible offline; read the PR's quality gate and issues on the code-scan dashboard. When a merged PR fixed issues, `main` goes red until `sonar-baseline.txt` is lowered in a one-line PR (`scripts/ci/sonar_ratchet.py` prints the number) |
| `sonar` (needs `coverage`) | the code-scan quality gate (new-code coverage ≥ 85%, no new issues) and the ratchet: open issues on `main` never above `sonar-baseline.txt`; a pull request fails while `main` is below it | not reproducible offline; read the PR's quality gate and issues on the code-scan dashboard. When a merge fixed issues, `main` stays green and the next pull request fails until it lowers `sonar-baseline.txt` to the number `scripts/ci/sonar_ratchet.py` prints |
| `lowest` | the lowest direct dependency versions sharpit claims to support (Python 3.12), in two `lowest shard (i/2)` jobs | `uv sync --extra test --no-dev --resolution lowest-direct --python 3.12 && uv run --no-sync pytest -q -n auto` (`--no-sync`: a plain `uv run` re-locks and undoes the resolution). Restore `uv.lock` afterwards if the sync rewrote it |
| `no-sqlalchemy` | sharpit installs, imports and serves every panel without SQLAlchemy | `uv sync --locked --extra test --no-install-package sqlalchemy --no-install-package aiosqlite --no-install-package alembic --no-install-package greenlet && uv run --no-sync pytest -q -n auto -m "not needs_sqlalchemy"`. A test that needs SQLAlchemy uses `pytest.importorskip` and the `needs_sqlalchemy` marker |
| `sharpit-gate` | dogfood: the example's fixed route passes `pytest --sharpit`, its planted N+1 fails it; reports uploaded as an artifact | `uv run --no-sync pytest examples/fastapi_sqla/tests_gate -k fixed --sharpit --sharpit-junit=sharpit-junit.xml` (must pass) and `-k n_plus_one --sharpit` (must fail) |
Expand Down
41 changes: 28 additions & 13 deletions scripts/ci/sonar_ratchet.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Sonar ratchet: a pull request may add no Sonar issue, and main must hold exactly the baseline count of open issues.
"""Sonar ratchet: a pull request may add no Sonar issue, and the baseline tracks main's open issues, only downwards.

Run after the SonarCloud scan (which waits for the quality gate, so the analysis is processed):
python scripts/ci/sonar_ratchet.py --pull-request 12
python scripts/ci/sonar_ratchet.py --branch main
Lower `sonar-baseline.txt` in the same commit that fixes issues; it may only go down. main below the baseline fails
too: a fix that left the baseline high would let a later change add an issue back unnoticed.
Lower `sonar-baseline.txt` in the same commit that fixes issues; it may only go down. main above the baseline fails.
main below it passes (the merge that fixed issues could not know main's new count), and every pull request then fails
until it lowers the baseline to main's count, so the slack never outlives one merge and main never turns red.
"""

from __future__ import annotations
Expand All @@ -21,20 +22,29 @@
BASELINE = Path(__file__).resolve().parents[2] / "sonar-baseline.txt"


def verdict(open_issues: int, baseline: int | None) -> tuple[bool, str]:
"""baseline None means a pull request: any issue it adds fails."""
if baseline is None:
if open_issues:
return False, f"this pull request adds {open_issues} Sonar issue(s); fix them before merging"
return True, "no new Sonar issues"
def _lower(open_issues: int, baseline: int) -> str:
below = f"main has {open_issues} open Sonar issues, below the baseline of {baseline}"
return f"{below}: lower sonar-baseline.txt to {open_issues}"


def verdict(open_issues: int, baseline: int) -> tuple[bool, str]:
"""main: only an issue count above the baseline fails."""
if open_issues > baseline:
return False, f"{open_issues} open Sonar issues on main, above the baseline of {baseline}"
if open_issues < baseline:
below = f"{open_issues} open Sonar issues, below the baseline of {baseline}"
return False, f"{below}: lower sonar-baseline.txt to {open_issues}"
return True, f"{_lower(open_issues, baseline)} (the next pull request must)"
return True, f"{open_issues} open Sonar issues, at the baseline"


def pull_request_verdict(new_issues: int, main_open: int, baseline: int) -> tuple[bool, str]:
"""A pull request adds no issue and carries a baseline no higher than main's count (lower: it fixes some)."""
if new_issues:
return False, f"this pull request adds {new_issues} Sonar issue(s); fix them before merging"
if main_open < baseline:
return False, _lower(main_open, baseline)
return True, "no new Sonar issues; the baseline is current"


def open_issue_count(scope: dict[str, str]) -> int:
query = urllib.parse.urlencode({"componentKeys": PROJECT, "resolved": "false", "ps": 1, **scope})
request = urllib.request.Request(f"https://sonarcloud.io/api/issues/search?{query}")
Expand All @@ -44,18 +54,23 @@ def open_issue_count(scope: dict[str, str]) -> int:
return int(json.load(response)["total"])


def _baseline() -> int:
return int(BASELINE.read_text().strip())


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser()
target = parser.add_mutually_exclusive_group(required=True)
target.add_argument("--pull-request", type=int)
target.add_argument("--branch")
args = parser.parse_args(argv)
if args.pull_request is not None:
ok, message = verdict(open_issue_count({"pullRequest": str(args.pull_request)}), None)
new_issues = open_issue_count({"pullRequest": str(args.pull_request)})
ok, message = pull_request_verdict(new_issues, open_issue_count({"branch": "main"}), _baseline())
elif args.branch != "main": # the baseline counts main's issues; a release/** push only refreshes its analysis
ok, message = True, f"{args.branch}: no baseline (only main is ratcheted; its pull requests add no issue)"
else:
ok, message = verdict(open_issue_count({"branch": args.branch}), int(BASELINE.read_text().strip()))
ok, message = verdict(open_issue_count({"branch": args.branch}), _baseline())
print(message if ok else f"::error::{message}")
return 0 if ok else 1

Expand Down
4 changes: 2 additions & 2 deletions skills/release/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ stops the release until the owner decides where it goes.

- `/sharpit:check` green.
- CI green on `main`: `gh run list --branch main --limit 3`, the `sonar` job included. The code-scan ratchet
(`scripts/ci/sonar_ratchet.py`) fails on `main` when a merged PR fixed issues and `sonar-baseline.txt` was not
lowered (0.3.0: 122 open against 123); lower it in a one-line PR before tagging, and tag the release merge commit
(`scripts/ci/sonar_ratchet.py`) fails every pull request while `main` has fewer open issues than
`sonar-baseline.txt`; lower it in the release PR or a one-line PR before tagging, and tag the release merge commit
explicitly if `main` moved (step 10).
- `/sharpit:known-issues`: no open Critical or High safety issue.
- `/sharpit:doc-review` clean: version references, links (github.com only) and the changelog footer.
Expand Down
2 changes: 1 addition & 1 deletion sonar-baseline.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
103
100
40 changes: 33 additions & 7 deletions tests/test_sonar_ratchet.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
import pytest
from scripts.ci import sonar_ratchet
from scripts.ci.sonar_ratchet import verdict
from scripts.ci.sonar_ratchet import pull_request_verdict, verdict


def test_pull_request_with_any_new_issue_fails():
assert verdict(1, None)[0] is False
assert verdict(0, None)[0] is True
assert pull_request_verdict(1, main_open=10, baseline=10)[0] is False
assert pull_request_verdict(0, main_open=10, baseline=10)[0] is True


def test_main_must_sit_exactly_at_the_baseline():
def test_pull_request_fails_while_main_sits_below_the_baseline():
"""A merge that fixed issues leaves the baseline stale; the next pull request lowers it, so main never turns red."""
ok, message = pull_request_verdict(0, main_open=9, baseline=10)
assert ok is False
assert "lower sonar-baseline.txt to 9" in message


def test_pull_request_may_lower_the_baseline_ahead_of_its_own_fixes():
assert pull_request_verdict(0, main_open=10, baseline=8)[0] is True


def test_main_above_the_baseline_fails():
assert verdict(11, 10)[0] is False
assert verdict(10, 10)[0] is True


def test_main_below_the_baseline_fails_until_the_baseline_is_lowered():
"""A fix that leaves the baseline high would let a later change add an issue back unnoticed."""
def test_main_below_the_baseline_passes_with_a_warning():
"""The fixing merge cannot know main's new count; the next pull request is held to it instead."""
ok, message = verdict(9, 10)
assert ok is False
assert ok is True
assert "lower sonar-baseline.txt to 9" in message


def test_a_pull_request_reads_its_own_new_issues_and_mains_open_count(monkeypatch: pytest.MonkeyPatch) -> None:
queried: list[dict[str, str]] = []

def spy(scope: dict[str, str]) -> int:
queried.append(scope)
return 0 if "pullRequest" in scope else 1

monkeypatch.setattr(sonar_ratchet, "open_issue_count", spy)

rc = sonar_ratchet.main(["--pull-request", "12"])

assert queried == [{"pullRequest": "12"}, {"branch": "main"}]
assert rc == 1


def test_a_release_branch_push_is_not_held_to_mains_baseline(monkeypatch: pytest.MonkeyPatch) -> None:
"""sonar-baseline.txt counts main's open issues; a release/** push only refreshes the base analysis."""
queried: list[dict[str, str]] = []
Expand Down