fix(674,688): cross-check frontmatter against PyYAML; split the ceiling calibration claim
Two defects in scripts/decisions_validate.py, fixed together because they share the validator and its pytest suite. #674 — the validator reported OK on frontmatter PyYAML rejects. The hand-rolled reader is deliberately dependency-free (decisions-guard and the Husky hooks install nothing), so it cannot see a bare apostrophe closing a single-quoted scalar. Hit twice in one session by two independent agents. `pyyaml_frontmatter_faults()` now cross-checks the parse against PyYAML whenever PyYAML is importable, and is SKIPPED with a ::notice:: when it is not — the read path stays dependency-free. The two known hazards fail differently and the fix covers both: the apostrophe makes PyYAML reject the document, while an unquoted ` #` parses fine and silently TRUNCATES the value. So the check compares parsed results key by key rather than try/except-ing the load, which is also what makes it generalize past the two known characters. PyYAML wrote these files, so on disagreement it is authoritative and the file is the defect. The comparison has one implementation, called by the validator and by the existing test_decisions_lib agreement test, so the tool and the suite cannot drift. #688 — test_real_corpus_ceiling_sits_at_the_TAIL_BOUNDARY asserted p90 <= 60 <= p95 in the BLOCKING script-tests job. p90 sat exactly on the ceiling and the distribution above it is sparse, so one ordinary record moved p90 by twenty lines and reddened CI for whoever wrote it; it reproduced twice live (#672, #706) and both times the only in-scope remedy was trimming the new record to fit the constant. v5 splits the claim by robustness instead of hunting for a better single assertion. The blocking test now asserts only the coarse, non-ratcheting property (the ceiling flags a nonempty proper minority, 0 < fraction_over < 1/3); the fine tail-boundary claim is measured every run and REPORTED as a ::notice::, on the same reasoning stale_records already uses — a constant going out of date is the passage of corpus growth, not a defect in the commit under test. The fine property is still asserted, against synthetic distributions the test owns. The ceiling stays 60. Verification: 424 scripts/tests pass; ruff at baseline parity (47 before and after); the cross-check is clean on all 183 real records; a positive control pins that record_wing_faults alone still reports both hazard files as clean, so the new red cannot pass for the wrong reason; and a test demonstrates that appending #672's 62-line and #687's 107-line records to the real corpus does not red the blocking property. Docs: new record docs.frontmatter-pyyaml-crosscheck, docs.corpus-size-signal updated for the v5 split, catalog regenerated, docs/ci-cd.md updated for both. fixes #674 fixes #688 Decisions-Edit: yes Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ import subprocess
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import scripts.decisions_lib as dl # noqa: E402 (run with PYTHONPATH=. or as module)
|
||||
|
||||
@@ -52,6 +53,11 @@ _STALE_AFTER_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
# guards the calibration claim asserts against the SAME value the CLI uses and the two cannot drift.
|
||||
RECORD_CEILING_DEFAULT = 60
|
||||
|
||||
# The coarse, non-ratcheting calibration bound (#688): the ceiling must flag a nonempty PROPER
|
||||
# MINORITY of records. Above a third it is cutting into the bulk rather than marking a tail. See
|
||||
# `ceiling_calibration` for why the fine percentile claim is reported instead of asserted.
|
||||
CEILING_MINORITY_MAX = 1 / 3
|
||||
|
||||
|
||||
def _parse_stale_after(value: str | None) -> date | None:
|
||||
"""`stale-after` as a date, or None if absent, empty, or malformed.
|
||||
@@ -541,6 +547,92 @@ def record_wing_faults(records_dir: Path | None = None, archive_dir: Path | None
|
||||
return faults
|
||||
|
||||
|
||||
def _frontmatter_block(text: str) -> str | None:
|
||||
"""The raw YAML between the opening `---` and the next `---`, or None if there isn't one."""
|
||||
if not dl.has_frontmatter(text):
|
||||
return None
|
||||
lines = text.splitlines()
|
||||
end = next((i for i, ln in enumerate(lines[1:], start=1) if ln.rstrip() == "---"), None)
|
||||
if end is None:
|
||||
return None
|
||||
return "\n".join(lines[1:end])
|
||||
|
||||
|
||||
def pyyaml_frontmatter_faults(files) -> tuple[list[str], bool]:
|
||||
"""Faults where PyYAML disagrees with the dependency-free reader. Returns (faults, ran).
|
||||
|
||||
#674: the two known hazards are a bare apostrophe inside a single-quoted scalar
|
||||
(`rule: 'SQLite's LOWER()'`) and an unquoted ` #` (`rule: use --flag #2`). Before this check the
|
||||
validator reported OK on both, because `dl._read_frontmatter` is a hand parser that cannot see
|
||||
either. It was hit TWICE in one session by two independent agents, which is what makes it worth
|
||||
a guard rather than a note.
|
||||
|
||||
The two hazards fail DIFFERENTLY, and catching only the first would have missed half of it:
|
||||
|
||||
* the apostrophe makes PyYAML **reject** the document outright (`ParserError`);
|
||||
* the unquoted ` #` parses fine and **silently truncates** the value — PyYAML reads
|
||||
`use --flag`, the hand parser reads `use --flag #2`. No exception, a wrong value.
|
||||
|
||||
So this compares the parsed RESULT and does not merely try/except the load. That is also why it
|
||||
generalizes past the two known characters, which is the property #674 asked for: any future
|
||||
construct where the writer's library and our reader disagree shows up as a diff, without anyone
|
||||
enumerating it first.
|
||||
|
||||
DIRECTION MATTERS: PyYAML is the WRITER (`migrate_decisions_split.render_record` emits these
|
||||
files with `yaml.safe_dump`), so it is the authority on what the on-disk bytes mean. The hand
|
||||
reader is the permissive one, and a disagreement is a defect in the FILE, not in either parser.
|
||||
|
||||
`ran` is False when PyYAML is not importable. The read path is deliberately dependency-free —
|
||||
`decisions-guard`, the Husky hooks and every contributor machine install nothing — so this check
|
||||
is strictly additive: it must never be the reason the validator cannot run. main() announces the
|
||||
skip rather than passing quietly, because a check that reports success while doing nothing is
|
||||
the exact defect class this corpus keeps re-learning (#603's `stale-after`, #609's marker).
|
||||
"""
|
||||
try:
|
||||
import yaml # pyright: ignore[reportMissingImports]
|
||||
except Exception:
|
||||
return [], False
|
||||
|
||||
faults: list[str] = []
|
||||
for p in files:
|
||||
try:
|
||||
text = p.read_text(encoding="utf-8")
|
||||
except Exception: # noqa: S112 (record_wing_faults already reports the unreadable file by name)
|
||||
continue
|
||||
block = _frontmatter_block(text)
|
||||
if block is None:
|
||||
continue # no/unterminated frontmatter: reported by record_wing_faults
|
||||
try:
|
||||
theirs_raw = yaml.safe_load(block)
|
||||
except yaml.YAMLError as exc:
|
||||
first = str(exc).splitlines()[0] if str(exc).strip() else exc.__class__.__name__
|
||||
faults.append(
|
||||
f"{p}: PyYAML REJECTS this frontmatter, though the dependency-free reader accepted "
|
||||
f"it ({first}). PyYAML is what WROTE these files, so its verdict is authoritative. "
|
||||
f"Common cause: a bare apostrophe inside a single-quoted value (write '' for a "
|
||||
f"literal apostrophe, as `yaml.safe_dump` does)."
|
||||
)
|
||||
continue
|
||||
if theirs_raw is None:
|
||||
theirs_raw = {}
|
||||
if not isinstance(theirs_raw, dict):
|
||||
faults.append(f"{p}: frontmatter parses as {type(theirs_raw).__name__}, not a mapping.")
|
||||
continue
|
||||
mine = dl._read_frontmatter(block)
|
||||
if mine is None:
|
||||
continue # the reader bailed: reported by record_wing_faults as parse-to-0
|
||||
theirs = {k: ("" if v is None else str(v)) for k, v in theirs_raw.items()}
|
||||
for k in sorted(set(mine) | set(theirs)):
|
||||
if mine.get(k) != theirs.get(k):
|
||||
faults.append(
|
||||
f"{p}: frontmatter key {k!r} means different things to the two parsers — "
|
||||
f"reader={mine.get(k)!r} but PyYAML={theirs.get(k)!r}. PyYAML wrote this file, "
|
||||
f"so its reading is the real value and the record is silently corrupt. Common "
|
||||
f"cause: an unquoted ` #`, which YAML treats as a comment and truncates there."
|
||||
)
|
||||
return faults, True
|
||||
|
||||
|
||||
def _unknown_frontmatter_keys(path: Path) -> set[str]:
|
||||
"""Frontmatter keys outside the known schema. Empty on any read/parse failure (reported elsewhere)."""
|
||||
try:
|
||||
@@ -642,6 +734,62 @@ def oversized_records(records, ceiling: int) -> list[tuple[str, int]]:
|
||||
return sorted([kv for kv in out if kv[1] > ceiling], key=lambda kv: -kv[1])
|
||||
|
||||
|
||||
class CeilingCalibration(NamedTuple):
|
||||
n: int
|
||||
p90: int
|
||||
p95: int
|
||||
n_over: int
|
||||
fraction_over: float
|
||||
marks_tail: bool # the FINE claim: p90 <= ceiling <= p95
|
||||
flags_minority: bool # the COARSE claim: 0 < fraction_over < CEILING_MINORITY_MAX
|
||||
|
||||
|
||||
def ceiling_calibration(records, ceiling: int) -> CeilingCalibration:
|
||||
"""How well `ceiling` still marks the start of the corpus's tail (#688).
|
||||
|
||||
Two claims of DIFFERENT robustness, deliberately separated, because conflating them is what
|
||||
made the previous guard a ratchet:
|
||||
|
||||
`marks_tail` — `p90 <= ceiling <= p95`. Correct as a definition of "start of the tail", but an
|
||||
order statistic over a SPARSE distribution is a STEP function: at #688 the lengths just above
|
||||
the ceiling ran 60, 61, 62, 63, then jumped to 81, so ONE new record could move p90 by twenty
|
||||
lines and the only remedy the assertion admitted was to raise the ceiling. It is real signal,
|
||||
but it is signal about the CONSTANT drifting, not a defect in the commit under test — the same
|
||||
shape as `stale_records`, and it is reported the same way: a notice, never a failure.
|
||||
|
||||
`flags_minority` — `0 < fraction_over < 1/3`. Deliberately coarse, and what the blocking test
|
||||
asserts. Each added record moves a fraction by at most 1/N, so routine growth cannot cross it:
|
||||
at 17/176 over the ceiling, reaching a third would take ~42 consecutive over-ceiling additions.
|
||||
It still catches genuine mis-calibration in both directions — a ceiling of 200 flags nobody
|
||||
(fraction 0, signals nothing), a ceiling of 20 flags most of the corpus (cutting into the bulk,
|
||||
so every author learns to ignore it).
|
||||
|
||||
Why not simply re-derive the constant instead: re-deriving fixes the instance and keeps the
|
||||
mechanism. The v3 fraction band and the v4 percentile containment both failed the same way, one
|
||||
faster than the other, and picking a new number would queue up the fifth version.
|
||||
"""
|
||||
lengths = sorted(record_prose_lines(r) for r in records if r.key)
|
||||
n = len(lengths)
|
||||
if n == 0:
|
||||
return CeilingCalibration(0, 0, 0, 0, 0.0, False, False)
|
||||
|
||||
def pct(q: float) -> int:
|
||||
return lengths[min(int(n * q), n - 1)]
|
||||
|
||||
n_over = sum(1 for v in lengths if v > ceiling)
|
||||
frac = n_over / n
|
||||
p90, p95 = pct(0.90), pct(0.95)
|
||||
return CeilingCalibration(
|
||||
n=n,
|
||||
p90=p90,
|
||||
p95=p95,
|
||||
n_over=n_over,
|
||||
fraction_over=frac,
|
||||
marks_tail=p90 <= ceiling <= p95,
|
||||
flags_minority=0 < frac < CEILING_MINORITY_MAX,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_ok() -> bool:
|
||||
try:
|
||||
import scripts.build_decisions_catalog as bc # pyright: ignore[reportMissingImports]
|
||||
@@ -684,6 +832,19 @@ def main(argv=None) -> int:
|
||||
archive_records += dl.parse_file(f)
|
||||
removed, rewritten, demoted = _diff_findings(args.base, args.head) if args.base and args.head else ([], [], [])
|
||||
oversized = oversized_records(records, args.record_ceiling)
|
||||
|
||||
# #674: cross-check the dependency-free reader against the library that WROTE these files.
|
||||
# Strictly additive — absent PyYAML skips the check (and SAYS so) rather than failing the run.
|
||||
yaml_faults, yaml_ran = pyyaml_frontmatter_faults(record_wing_files())
|
||||
if not yaml_ran:
|
||||
print(
|
||||
"::notice::decisions-validate: PyYAML is not importable, so the frontmatter cross-check "
|
||||
"was SKIPPED — every other check ran. This is the expected state on the dependency-free "
|
||||
"read path (decisions-guard, the Husky hooks); CI's script-tests job runs it with PyYAML "
|
||||
"present.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
errs = validate(
|
||||
records,
|
||||
archive_keys=_archive_keys(),
|
||||
@@ -692,7 +853,7 @@ def main(argv=None) -> int:
|
||||
rewritten=rewritten,
|
||||
archive_records=archive_records,
|
||||
demoted=demoted,
|
||||
wing_faults=record_wing_faults(),
|
||||
wing_faults=record_wing_faults() + yaml_faults,
|
||||
)
|
||||
|
||||
# Aggregate: an unthresholded TREND, not a gate (#620). Printed every run so the number stays
|
||||
@@ -723,6 +884,20 @@ def main(argv=None) -> int:
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
# Ceiling calibration drift (#688): a NOTICE, never a failure. The ceiling drifting away from
|
||||
# the tail boundary is the passage of corpus growth, not a defect in the commit under test — the
|
||||
# same reasoning `stale_records` is built on. Asserting it in the blocking `script-tests` job
|
||||
# made the next author of a substantial record pay for an unrelated constant going out of date.
|
||||
cal = ceiling_calibration(records, args.record_ceiling)
|
||||
if cal.n and not cal.marks_tail:
|
||||
print(
|
||||
f"::notice::decisions-validate: the {args.record_ceiling}-line ceiling has drifted from "
|
||||
f"the tail boundary of the distribution (p90={cal.p90}, p95={cal.p95}, "
|
||||
f"{cal.n_over}/{cal.n} records over it). Re-derive it when convenient — this is a "
|
||||
f"maintenance signal about the constant, not a problem with this change.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
stale = stale_records(records, date.today())
|
||||
if stale:
|
||||
listed = "; ".join(f"{h} (stale-after {d})" for h, d in stale)
|
||||
|
||||
Reference in New Issue
Block a user