From be3374ae5df41e560f4e0a0d1ea018bf359fb360 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 21:25:35 +0000 Subject: [PATCH 1/2] chore: lower the Sonar baseline to 100 (0.9.0 fixed three open issues) Signed-off-by: Flavio Oliva --- sonar-baseline.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sonar-baseline.txt b/sonar-baseline.txt index a9c8fe829..29d6383b5 100644 --- a/sonar-baseline.txt +++ b/sonar-baseline.txt @@ -1 +1 @@ -103 +100 From 82ef32f028f4cb35ea248fff5e29e67a48627385 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 21:40:08 +0000 Subject: [PATCH 2/2] fix(ci): hold the stale Sonar baseline on the next pull request, never on main main fails only above sonar-baseline.txt. Every pull request fails while main's open-issue count is below the baseline, so the merge after a fix lowers it and main never turns red when issues are fixed. Signed-off-by: Flavio Oliva --- AGENTS.md | 4 +++- docs/development/ci.md | 2 +- scripts/ci/sonar_ratchet.py | 41 +++++++++++++++++++++++++------------ skills/release/SKILL.md | 4 ++-- tests/test_sonar_ratchet.py | 40 +++++++++++++++++++++++++++++------- 5 files changed, 67 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6e5b71282..033868bd0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/docs/development/ci.md b/docs/development/ci.md index 778a4876e..f5070cc58 100644 --- a/docs/development/ci.md +++ b/docs/development/ci.md @@ -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) | diff --git a/scripts/ci/sonar_ratchet.py b/scripts/ci/sonar_ratchet.py index 2b66a69c8..c2f6b5c74 100644 --- a/scripts/ci/sonar_ratchet.py +++ b/scripts/ci/sonar_ratchet.py @@ -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 @@ -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}") @@ -44,6 +54,10 @@ 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) @@ -51,11 +65,12 @@ def main(argv: list[str] | None = None) -> 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 diff --git a/skills/release/SKILL.md b/skills/release/SKILL.md index 3bcb16b9a..9dcc60fcf 100644 --- a/skills/release/SKILL.md +++ b/skills/release/SKILL.md @@ -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. diff --git a/tests/test_sonar_ratchet.py b/tests/test_sonar_ratchet.py index 2fb8c16ea..7a4a3ec5c 100644 --- a/tests/test_sonar_ratchet.py +++ b/tests/test_sonar_ratchet.py @@ -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]] = []