Files
AiSOC/scripts/check_fidelity_datasets.py
T
Beenu AroraandBeenu Arora e78f31768c Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ (#861)
* Reformat the tree under ruff 0.16, excluding the subtree nobody may edit

Mechanical. `ruff format` with no other change, so the diff can be read as
"the formatter moved" rather than reviewed line by line: 218 files, 862
insertions against 1075 deletions, almost all of it collapsing calls that
0.4.10 wrapped and 0.16 fits inside the 140-column limit.

`plans/` is excluded in `ruff.toml` rather than reformatted. It is the
archived prototype subtree that `.github/workflows/codeql.yml` already
excludes and `scripts/check_mypy_baseline.py` excludes from every coverage
direction, and the project rules forbid editing anything under it -- so
formatting it would be a diff nobody may take. 844 lint findings and ~280
unformatted files live there. They are excluded because they cannot be
fixed, which is a different statement from saying the code is clean.

* Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/

The bump alone reds every open pull request: `ruff format --check` is a hard
gate on the required `Python - Lint & Type-check` job and 0.16 formats
differently from 0.4.10. The reformat is the previous commit; this one moves
the pin, fixes the findings, and answers the scope question.

Fourteen declarations now read `>=0.16.8,<0.17` -- seven manifests, three
workflows, `.devcontainer/Dockerfile`, and the three `poetry.lock` files that
resolve it (now 0.16.9, which is byte-identical to 0.16.8 on both format and
lint across this tree).

The three findings 0.16 reports on `services/` are fixed, not suppressed: two
`C420` comprehensions become `dict.fromkeys` (both values are string literals,
so the shared-value hazard does not apply) and one `UP031` percent-format
becomes an f-string in a test that counts characters. All three rewrites were
asserted equal to the originals before being kept.

Scope. `ruff check services/` left `scripts/` -- every CI gate in this
repository, the code the rest of its claims are verified by -- linted by
nothing. Lint now covers `services/ scripts/ tests/ tools/`, the trees the
root `ruff.toml` governs that nothing else lints, and `ruff format --check .`
covers everything, because formatting has no semantic content and `.` needs
no edit when a tree is added. That surfaced 17 findings outside `services/`,
each fixed at the source: two `B007` loops switched to `.values()`, a `B904`
re-raise in `security_audit.py` now chains `from exc`, two `E402` imports
that genuinely follow a `sys.path` mutation carry a reason next to the
marker, and two over-length lines were wrapped.

`E501` is ignored for the two detection-spec data modules. Both open their
rule table with `# fmt: off`, so the formatter is already opted out of that
layout deliberately, and all 199 long lines are single dict or string
literals -- 72 positive fixtures, 66 negative, 50 `match_when` clauses, 11
descriptions. Two named files, not `scripts/`.

`packages/` and `plugins/` stay outside the lint gate, and the gap is a
number rather than a shrug: 91 findings and 2. Two of the five packages are
linted by their own workflows under their own configs, and bringing the
three published SDKs under this gate means behaviour-touching fixes that
belong in a change reviewed as such.

* Make packages/aisoc-detections clean under the ruff its own workflow now installs

`python-detections.yml` lints `aisoc_detections detections tests` under the
pin this PR moved, so the package has to be clean under 0.16 too. Two
findings, both fixed at the source rather than silenced: `Callable` moves to
`collections.abc`, and a `# noqa: BLE001` that 0.16 correctly reports as
unused becomes the sentence it was standing in for -- a detection module is
third-party content, so any exception at import is the author's and becomes a
DetectionError naming the file.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-24 19:36:59 -07:00

161 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""Gate: every fidelity dataset is obtainable, and unmeasured floors say so.
Two of the four fidelity datasets shipped a downloader and two did not.
`ait_lds_loader.py` and `mitre_engenuity_loader.py` could parse the full
corpora from the day they landed, and there was no way to obtain either —
so the only numbers anyone could produce came from a ten-line micro
fixture. A micro fixture proves the loader parses. It says nothing about
how the classifier behaves at scale, which is the entire question a
fidelity benchmark exists to answer.
The asymmetry was invisible because each half looked complete on its own:
the loaders had tests, the fixtures had thresholds, and nothing compared
the set of loaders against the set of downloaders.
This checks three things:
1. Every dataset with a loader has a downloader.
2. Every downloader requires explicit licence acceptance. These are
third-party corpora under attribution terms, and a script that
fetches one without the operator reading them agrees to terms on
their behalf.
3. A threshold block marked `measured: false` is not presented
anywhere as an observed result.
Run: python3 scripts/check_fidelity_datasets.py
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
# `scripts/` is on sys.path when this file is run as a program, but not when a
# test loads it by path with importlib. gate_toolkit sits beside it either way.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gate_toolkit import repo_root, self_test_if_requested
self_test_if_requested(__file__)
try:
import yaml
except ImportError: # pragma: no cover
print("PyYAML is required: pip install pyyaml", file=sys.stderr)
raise SystemExit(2) from None
REPO_ROOT = repo_root()
FIDELITY = REPO_ROOT / "services" / "agents" / "tests" / "fidelity"
DOWNLOADS = REPO_ROOT / "scripts" / "datasets"
THRESHOLDS = FIDELITY / "expected_results.yaml"
BENCHMARK_DOCS = (
REPO_ROOT / "apps" / "docs" / "docs" / "benchmark.md",
REPO_ROOT / "apps" / "docs" / "docs" / "benchmark-fidelity.md",
)
def loaders() -> set[str]:
"""Dataset names that have a loader module."""
return {path.stem.removesuffix("_loader") for path in FIDELITY.glob("*_loader.py")}
def downloaders() -> set[str]:
return {path.stem.removeprefix("download_") for path in DOWNLOADS.glob("download_*.py")}
def check_every_loader_can_be_fed() -> list[str]:
missing = sorted(loaders() - downloaders())
return [
f"{name}: has a loader ({name}_loader.py) and no downloader. The full "
f"corpus cannot be obtained, so any published number for it comes from "
f"a micro fixture — which proves the loader parses and nothing else."
for name in missing
]
def check_downloaders_require_licence_acceptance() -> list[str]:
errors: list[str] = []
for path in sorted(DOWNLOADS.glob("download_*.py")):
source = path.read_text(encoding="utf-8")
if "--accept-license" not in source:
errors.append(
f"{path.name}: does not require --accept-license. These are "
f"third-party corpora under attribution terms; fetching one "
f"without the operator reading them agrees on their behalf."
)
if "Citation" not in source and "citation" not in source:
errors.append(f"{path.name}: carries no citation. Attribution is a licence condition for every dataset here, not a courtesy.")
return errors
def check_unmeasured_floors_are_not_published() -> list[str]:
"""A floor nobody has run must not appear as an observed number."""
if not THRESHOLDS.exists():
return [f"{THRESHOLDS.relative_to(REPO_ROOT)} is missing"]
data = yaml.safe_load(THRESHOLDS.read_text(encoding="utf-8")) or {}
unmeasured = {name for name, entry in data.items() if isinstance(entry, dict) and entry.get("measured") is False}
if not unmeasured:
return []
errors: list[str] = []
for name in sorted(unmeasured):
entry = data[name]
notes = str(entry.get("notes") or "").strip()
# Must *lead* with the marker. Matching it anywhere passed a note
# whose third paragraph happened to use the word in passing — a
# caveat a reader reaches after two paragraphs is not a caveat.
if not notes.upper().startswith("UNMEASURED"):
errors.append(
f"{name}: marked measured:false but its notes do not open "
f"with UNMEASURED. A reader looking at the floor cannot tell "
f"it from an observed result."
)
# And it must not be quoted as a result in the published docs.
dataset = str(entry.get("dataset") or name)
for doc in BENCHMARK_DOCS:
if not doc.exists():
continue
text = doc.read_text(encoding="utf-8")
pattern = re.compile(
rf"{re.escape(dataset)}[^\n]*\bfull\b[^\n]*\d+(?:\.\d+)?\s*%",
re.IGNORECASE,
)
if pattern.search(text):
errors.append(
f"{name}: {doc.name} quotes a full-corpus percentage for {dataset}, but the threshold block says it was never measured."
)
return errors
def main(argv: list[str] | None = None) -> int:
argparse.ArgumentParser(description=__doc__).parse_args(argv)
if not FIDELITY.is_dir():
print("fidelity-datasets: harness directory not found", file=sys.stderr)
return 2
errors = check_every_loader_can_be_fed() + check_downloaders_require_licence_acceptance() + check_unmeasured_floors_are_not_published()
if errors:
print("FIDELITY DATASET GATE FAILED:", file=sys.stderr)
for error in errors:
print(f" - {error}", file=sys.stderr)
return 1
found = sorted(loaders())
data = yaml.safe_load(THRESHOLDS.read_text(encoding="utf-8")) or {}
unmeasured = [name for name, entry in data.items() if isinstance(entry, dict) and entry.get("measured") is False]
print(f"fidelity-datasets: OK — {len(found)} dataset(s) with a loader ({', '.join(found)}), each with a licence-gated downloader")
if unmeasured:
print(f" {len(unmeasured)} full-corpus floor(s) not yet measured: {', '.join(sorted(unmeasured))}")
return 0
if __name__ == "__main__":
raise SystemExit(main())