From aafbe188da4edeb4714df5c755397d4dbb002707 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:33:17 +0200 Subject: [PATCH 01/18] feat(efficacy): score a change task's tree in full, with interfaces and data upgrade - score.py scores a changed tree on every reading a build has, both suites, churn before the battery, and files its security reading beside it - the interfaces reading: the API, route and export modules the fixture passed whole must still pass; inherited failures counted neither way - the harness refuses a fixture whose baseline does not name the four interface modules, and copies the baseline into each change record - quality.py --task change adds the data upgrade: seed through the fixture's own forms at the starting commit, open a copy with the changed tree, check values, old invoices and new rows; provenance recorded - security.py, quality.py and judge.py take --task change, each into folders of its own - round 6's ISO table: interfaces on Interoperability, data upgrade on Adaptability, each once, read whatever the build did; pilots unchanged - archive.py and reuse.py carry the change readings and judgings; reuse brings change tasks in a change run naming the round's fixtures - FR-16-01 to FR-16-07, QT-03-02, QT-08-03, ch. 8 and ADR-023 history Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/05-building-block-view.md | 7 +- docs/architecture/08-crosscutting-concepts.md | 40 +- docs/coverage.md | 12 + docs/decisions/023-the-iso-radar.md | 1 + docs/requirements.md | 19 +- tests/efficacy/archive.py | 45 +- tests/efficacy/change-fixtures.json | 2 +- tests/efficacy/harness.py | 45 +- tests/efficacy/judge.py | 96 +- tests/efficacy/quality.py | 922 +++++++++++++++++- tests/efficacy/report.py | 172 +++- tests/efficacy/reuse.py | 180 +++- tests/efficacy/score.py | 229 ++++- tests/efficacy/security.py | 91 +- 14 files changed, 1693 insertions(+), 168 deletions(-) diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index 42a51d7..dfb0e92 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -21,9 +21,9 @@ dependency with its keyword. | `progress.py` | Watches a run: one bar per arm, its voided tries, its cost and the trial running; then its scoring: one bar per arm, the security readings and the trial being scored; then its judging: one bar per arm of judgings out of those owed, the failures still owed and the blind label in hand. Redrawn every 30 s. Read-only | The run records, the scoring area | The console | | `score.py` | Installs each frozen trial cleanly, runs the hidden suite, the static tools and the adherence checklist, counts scope and cost | The run root, the hidden suite, `scoring-requirements.txt`, `toolconfig/` | `scores/`, `scores-change/` | | `probes.py` | The structural and web-quality probes, run inside the trial's own interpreter | A trial's tree | Its findings, to `score.py` | -| `security.py` | Seeds each app, signs in its administrator, runs the 11 security and 3 data-protection probes | The scored trees | `security-scores/` | -| `quality.py` | Signs in each app's administrator and runs the quality probes in process: malformed requests, concurrent writes, latency, a 500-line invoice, SQL per invoice line, two instances side by side; then installs the build on Python 3.14 and serves a signed-in page | The scored trees | `quality-scores/` | -| `judge.py` | Builds a blind bundle per trial, runs the judge CLI against the rubric, checks every quoted line | The scored trees | `judge/` | +| `security.py` | Seeds each app, signs in its administrator, runs the 11 security and 3 data-protection probes | The scored trees | `security-scores/`, `security-scores-change/` | +| `quality.py` | Signs in each app's administrator and runs the quality probes in process: malformed requests, concurrent writes, latency, a 500-line invoice, SQL per invoice line, two instances side by side; then installs the build on Python 3.14 and serves a signed-in page; on a change task's tree also the data upgrade, the fixture's seeded database opened by the changed tree | The scored trees | `quality-scores/`, `quality-scores-change/` | +| `judge.py` | Builds a blind bundle per trial, runs the judge CLI against the rubric, checks every quoted line | The scored trees | `judge/`, `judge-change/` | | `control/control.py` | Builds the rubric control: trees damaged or improved on one row each, from two pinned bases | `base.zip`, `base-2.zip`, `overlay/` | A control root for `judge.py` | | `report.py` | Pairs trials, computes intervals and verdicts, applies withdrawals, prints the report | The run root, the scoring area, `withdrawn.json` | `docs/reports/YYYY-MM-DD-efficacy.md` in this repository | | `archive.py` | Copies a round's raw data to the private archive, restores it, recomputes the report's figures from both | The run root, the scoring area | The archive clone, `archived.json` | @@ -76,6 +76,7 @@ are still read. | `security/`, `security-scores/` | Each trial's probe files, and its readings; the probe environment goes once it is read | | `quality/`, `quality-scores/` | Each trial's quality probe files, and its readings; both environments go once they are read | | `judge/` | Each blind bundle, its judgings and the unblinding map | +| `scoring-change/`, `security-change/`, `security-scores-change/`, `quality-change/`, `quality-scores-change/`, `judge-change/` | The same for each change task's tree, apart from the build's; `quality-change/` also holds the fixture's seeded database and its copy for the data upgrade | | `archived.json` | The stamp a verified archive writes, with the hash of every file the report reads | | `.running` | A claim that one run of that tool is working here | diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 1ab3fc0..6a1790a 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -360,6 +360,38 @@ green, whether the acceptance modules pass through the API, and, from round The decision is ADR-009, including why round 1's change-task pass rate was withdrawn. +**The changed tree, scored in full.** From round 6 every arm's change task +of a block starts from one fixture, a qualifying `none` build of round 5e, +so the changed tree is read on every ISO axis the build is. It gets the +same scoring, security and quality readings and judge, each filed apart +from the build's under a `-change` folder of its own (FR-16-01, FR-16-03, +FR-16-05). A changed tree that does not install loses its probes and goes +unjudged, as a build does; a reading the reader could not take is missing. + +Two readings compare the changed tree with its fixture, each counted on one +axis only: + +| Reading | What it reads | Fails when | ISO place | +| ------- | ------------- | ---------- | --------- | +| Interfaces | The hidden suite's API, route and two export modules on the changed tree, against the fixture's frozen baseline | A module the fixture passed whole no longer does | Compatibility, Interoperability | +| Data upgrade | Products, customers, rules, a jurisdiction and invoices saved through the fixture's own forms, then the changed tree on a copy of that database | A record is gone or reads differently, an old invoice will not open or price as it did, or the file takes no new record | Flexibility, Adaptability | + +- **Inherited is not broken.** An interface module the fixture already + failed is the fixture's, not the change's, and counts neither way + (FR-16-02). +- **Values, not counts.** Each record is read back as the fixture showed + it: the list pages, each invoice's JSON and CSV exports, the customer's + export, and the old invoice priced again. A key or column only the + changed tree has is the change's own, and is no loss (FR-16-04). +- **Lost and missing.** A changed tree that will not open the file, or + sign in on it, has lost the data and fails. A fixture that cannot seed is + no arm's, so the reading is missing. Each reading names the fixture's + hash, the starting commit and the seeded database's hash. +- **One place each.** The data upgrade is the migration target on + Adaptability: the change adapts to data an earlier version saved. It is + not read on Interoperability too, so no build is credited twice + (FR-16-06). + ### 8.6.5 Pattern use For each design pattern it finds, the judge records where it is, what it @@ -622,8 +654,8 @@ interval of the difference against `none` lies past the axis's margin each radar, shown and not scored, and the appendix holds one table of sub-scores per axis. The decision is ADR-023. -Round 6's targets read three sources the pilot's did not (FR-12-21 to -FR-12-23): +Round 6's targets read four sources the pilot's did not (FR-12-21 to +FR-12-23, FR-16-06): - **Hidden-suite modules.** Functional correctness has one target per build module, met where the module passes whole: no check failed, errored or @@ -637,6 +669,10 @@ FR-12-23): - **Latency.** Its target reads a cutoff calibrated from the reference build and a planted slowdown, frozen before round 6 registers. Until then it is not measured. +- **The change task's tree.** Its interfaces are one target on + Interoperability and its data upgrade one on Adaptability (8.6.4). Both + are read whatever the trial's build did, since the change starts from a + fixture, not from that build (FR-16-06). A pilot round read by the ISO radar keeps the targets it had before round 6, and reads round 6's only when `--round6-targets` asks for them. diff --git a/docs/coverage.md b/docs/coverage.md index 3407a58..079ec0a 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -231,3 +231,15 @@ when: | FR-15-04 | Self-test | `quality.py` "the latency is two repeats of 30 requests each"
`quality.py` "a slowed app reads slower by its delay" | | FR-15-05 | Self-test | `quality.py` "a build that serves its page on the other Python passes portability"
`quality.py` "a build that boots on its own Python only fails portability"
`quality.py` "a build whose sign-in fails on the other Python fails portability"
`quality.py` "a build the other Python will not install fails portability"
`quality.py` "no other Python is missing, not passed" | | FR-15-06 | Self-test | `quality.py` "a reading's environment is gone once it is read" | + +## 16 The changed tree + +| ID | Kind | Checked by | +| -- | ---- | ---------- | +| FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is" | +| FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | +| FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks" | +| FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | +| FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | diff --git a/docs/decisions/023-the-iso-radar.md b/docs/decisions/023-the-iso-radar.md index 65d19dd..97bf88c 100644 --- a/docs/decisions/023-the-iso-radar.md +++ b/docs/decisions/023-the-iso-radar.md @@ -90,3 +90,4 @@ split; `#N` is in this repository; a dash means none. | 2026-11-04 | From round 6 the radar reads ISO/IEC 25010:2023: eight axes, the share of targets met, markers past a margin, cost above | The pilot's radars read the benchmark's rows, not the software's qualities; the spike in #118 settled the chart | #121 | | 2026-11-14 | Rule 10 and alternative E: from round 6 the verdict in the text reads the radar's markers, as ADR-024 decides | Round 5e read by the radar showed the verdict and the chart disagreeing | #165 | | 2026-11-15 | Round 6's targets: one per hidden-suite build module for correctness, one per quality probe, latency against a cutoff registered later; a pilot round's draft keeps its own | Round 5e read by the radar showed Functionality, Performance and Flexibility at 100 % for every arm | #155, #119 | +| 2026-11-15 | Round 6's change task: its interfaces one target on Interoperability, its data upgrade one on Adaptability, each read once, whatever the build did | Round 6 reads every axis on the change task, and Interoperability had no target | #178, #158 | diff --git a/docs/requirements.md b/docs/requirements.md index 0ccb31e..bdbf59c 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -245,6 +245,18 @@ | FR-15-05 | The benchmark shall read portability on Python 3.14, the trial installed, booted and serving a signed-in page there, and leave it missing where no Python 3.14 is found. | Quality reader | | FR-15-06 | The benchmark shall read the quality probes in a fresh environment per trial on the spec's Python, and remove every environment once it is read. | Quality reader | +### 16 The changed tree + +| ID | Requirement | Delivered by | +| -- | ----------- | ------------ | +| FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, and its security reading filed beside its score. | Scorer | +| FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | +| FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, and not judge one that did not install. | Judge | +| FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | +| FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | + ## Quality requirements - **Numbering:** characteristics follow ISO/IEC 25010:2023 order, 01 @@ -338,8 +350,9 @@ - **Pilot drafts:** a pilot round read by the ISO radar keeps the targets it had before round 6: the hidden suite at 98 % or more for correctness, and no quality probe. Round 6's are read there only when asked for. -- **Later:** interoperability and the migration targets come with the - changed tree's scoring. The export formats take no target of their own: +- **Change task:** two targets read the change task's tree against its + fixture, each in one place: its interfaces on Interoperability, its data + upgrade on Adaptability. The export formats take no target of their own: the hidden suite's export modules grade them. ### 01 Functional suitability @@ -365,6 +378,7 @@ | ID | Sub-characteristic | Target | Read from | | -- | ------------------ | ------ | --------- | | QT-03-01 | Co-existence | Two instances side by side keep their data and files apart. | Quality probe `coexistence` | +| QT-03-02 | Interoperability | The change keeps every interface its fixture passed: its Python names, routes and two exports. | Change score `interfaces` | ### 04 Interaction capability @@ -436,3 +450,4 @@ | -- | ------------------ | ------ | --------- | | QT-08-01 | Installability | `pip install .` succeeds in a clean environment. | Installs in a clean environment | | QT-08-02 | Adaptability | The build installs and serves a signed-in page on a second Python. | Quality probe `python_portability` | +| QT-08-03 | Adaptability | The changed tree opens its fixture's database, nothing lost. | Change task's quality probe `data_upgrade` | diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index 3c61ca2..00c6862 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -35,8 +35,14 @@ STAMP = "archived.json" # The scoring area's per-trial readings the report aggregates, each a JSON -# file named for its trial. -READINGS = ("scores", "scores-change", "security-scores", "quality-scores") +# file named for its trial, a change task's beside the build's. +READINGS = ("scores", "scores-change", "security-scores", + "security-scores-change", "quality-scores", + "quality-scores-change") + +# The judgings' folders, the build's and the change task's, each with its +# own labels and map. +JUDGINGS = ("judge", "judge-change") # What a frozen workspace holds that no reading needs and any scoring # rebuilds: tool caches, compiled bytecode, and every virtual environment, @@ -117,8 +123,9 @@ def readings_digest(root): files = {os.path.basename(path): path for path in glob.glob(os.path.join(root, "run-*.json"))} patterns = [os.path.join(kind, "*.json") for kind in READINGS] - patterns += [os.path.join("judge", "T*.json"), - os.path.join("judge", "map.json")] + for judging in JUDGINGS: + patterns += [os.path.join(judging, "T*.json"), + os.path.join(judging, "map.json")] for pattern in patterns: for path in glob.glob(os.path.join(area, pattern)): files[os.path.relpath(path, area).replace(os.sep, "/")] = path @@ -213,10 +220,11 @@ def archive(root, into): # A judging's bundle is rebuilt from its tree, so only the judgings, the # unblinding map and a failed judging's output tail are kept. - for path in sorted(glob.glob(os.path.join(area, "judge", "*"))): - if os.path.isfile(path): - copy_file(path, os.path.join(into_area, "judge", - os.path.basename(path))) + for judging in JUDGINGS: + for path in sorted(glob.glob(os.path.join(area, judging, "*"))): + if os.path.isfile(path): + copy_file(path, os.path.join(into_area, judging, + os.path.basename(path))) lock = os.path.join(area, "tool-lock.txt") if os.path.isfile(lock): copy_file(lock, os.path.join(into_area, "tool-lock.txt")) @@ -361,7 +369,9 @@ def drop_trees(root): for part in ("scoring", "scoring-change"): for kind in ("tree", "venv"): folders += glob.glob(os.path.join(area, part, "*", kind)) - folders += glob.glob(os.path.join(area, "security", "*", "venv")) + for reader in ("security", "security-change", "quality", + "quality-change"): + folders += glob.glob(os.path.join(area, reader, "*", "venv")) for folder in folders: remove_tree(folder) return len(folders) @@ -444,7 +454,8 @@ def plant_root(scratch): # what the archive copies, so a kind it stops copying shows. for name, arm in (("none-1", "none"), ("hybrid-1", "hybrid")): for kind in ("scores", "scores-change", "security-scores", - "quality-scores"): + "security-scores-change", "quality-scores", + "quality-scores-change"): dump_json(os.path.join(area, kind, "%s.json" % name), {"name": name, "arm": arm, "trial": 1, "suite_revision": "suite1"}) @@ -453,6 +464,11 @@ def plant_root(scratch): "answer": {"rubric": {}}}) dump_json(os.path.join(area, "judge", "map.json"), {"seed": 1, "blind": {"none-1": "T1"}}) + dump_json(os.path.join(area, "judge-change", "T1.json"), + {"trial": "none-1", "task": "change", "blind_id": "T1", + "outcome": "judged", "answer": {"rubric": {}}}) + dump_json(os.path.join(area, "judge-change", "map.json"), + {"seed": 1, "blind": {"none-1": "T1"}}) os.makedirs(os.path.join(area, "judge", "T1")) with io.open(os.path.join(area, "judge", "T1", "bundle.txt"), "w", encoding="utf-8") as handle: @@ -502,6 +518,15 @@ def self_test(): ("quality readings are archived beside the security readings", {"scoring/quality-scores/none-1.json", "scoring/quality-scores/hybrid-1.json"} <= set(files)), + ("a change task's security and quality readings and judgings are " + "archived beside its score", + {"scoring/security-scores-change/none-1.json", + "scoring/quality-scores-change/hybrid-1.json", + "scoring/judge-change/T1.json", + "scoring/judge-change/map.json"} <= set(files) + and set(readings_digest(root)) >= { + "quality-scores-change/none-1.json", + "judge-change/T1.json"}), ("a voided directory is kept as a marker", manifest["voided"] == ["hybrid-1-2026-10-01T11-00-00"] and os.path.isfile(os.path.join(into, "void", manifest["voided"][0], diff --git a/tests/efficacy/change-fixtures.json b/tests/efficacy/change-fixtures.json index 832190e..311c4c0 100644 --- a/tests/efficacy/change-fixtures.json +++ b/tests/efficacy/change-fixtures.json @@ -9,7 +9,7 @@ "fixture_fields": { "trial": "the source build's trial name, as none-3", "sha256": "the sha256 of that build's frozen tarball", - "baseline": "the source build's frozen readings the qualification took, an object" + "baseline": "the source build's frozen readings the qualification took, an object; its interfaces maps each of test_api_contract.py, test_http_routes.py, test_export_json.py and test_export_csv.py to whether the build passed that module whole" }, "fixtures": [] } diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index 27a6d89..6ec8613 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -470,6 +470,20 @@ def scoring_area(root): return os.path.abspath(root).rstrip("\\/") + "-scoring" +# The tasks a scoring area holds readings of. A change task's readings sit +# beside the build's, each folder the build's name with `-change` after it: +# both are keyed by the trial, and one must never overwrite the other. +TASKS = ("build", "change") + + +def task_folder(kind, task="build"): + """The folder of the scoring area that holds `kind` for `task`.""" + if task not in TASKS: + raise TrialError("%r is not a task; one is %s" % (task, + " or ".join(TASKS))) + return kind if task == "build" else "%s-change" % kind + + def dry_run_area(root): """The directory beside a run root that a dry run prepares in.""" return os.path.abspath(root).rstrip("\\/") + "-dry-run" @@ -1818,6 +1832,13 @@ def manifest_path(entry): return os.path.join(HERE, entry["tasks"]["change"]["fixtures"]["manifest"]) +# The hidden-suite modules that read what a build exposes to other software: +# its Python names, its routes and its two exports. A change task must leave +# each one answering as it did on the fixture. +INTERFACE_MODULES = ("test_api_contract.py", "test_http_routes.py", + "test_export_json.py", "test_export_csv.py") + + def read_fixtures(entry, directory): """The fixtures a round's change task starts from, each checked against its tarball in `directory`, in the order the blocks take them.""" @@ -1849,6 +1870,16 @@ def read_fixtures(entry, directory): or not fixture["baseline"]: raise TrialError("fixture %s carries no baseline readings, so it " "has not qualified" % trial) + + # The interfaces a change must keep are read against what the fixture + # passed, so each one's pass on the fixture is frozen beside it. + interfaces = fixture["baseline"].get("interfaces") + if not isinstance(interfaces, dict) or any( + not isinstance(interfaces.get(module), bool) + for module in INTERFACE_MODULES): + raise TrialError("fixture %s's baseline does not say which of %s " + "it passed whole" + % (trial, ", ".join(INTERFACE_MODULES))) tarball = os.path.join(directory, "%s.tar" % trial) if not os.path.isfile(tarball): raise TrialError("fixture %s has no tarball at %s" @@ -2109,7 +2140,8 @@ def run_fixture_change_trial(arm, block, root, home, options, fixture): "block": block, "round": round_name, "task": "change", "base": base, "vendored": vendored, "fixture": {key: fixture[key] - for key in ("trial", "sha256", "tarball")}, + for key in ("trial", "sha256", "tarball", + "baseline")}, "spec": {"file": os.path.basename(spec), "sha256": digest}} return run_agent(workspace, "change-%s" % trial_name(arm, block), prompt, record, root, home, options) @@ -4433,8 +4465,10 @@ def refused(*args): except TrialError: return True + interfaces = {module: True for module in INTERFACE_MODULES} listed = [{"trial": name, "sha256": hashes[name], - "baseline": {"build_suite": 1.0}} for name in hashes] + "baseline": {"build_suite": 1.0, "interfaces": interfaces}} + for name in hashes] listing_as([]) checks = [("an empty fixture manifest refuses a named round's change " "task", refused(entry, tarballs))] @@ -4443,6 +4477,13 @@ def refused(*args): listing_as([dict(listed[0], baseline={})] + listed[1:]) checks.append(("a fixture listed without its baseline readings is " "refused", refused(entry, tarballs))) + partial = dict(interfaces) + partial.pop(INTERFACE_MODULES[0]) + listing_as([dict(listed[0], baseline={"build_suite": 1.0, + "interfaces": partial})] + + listed[1:]) + checks.append(("a fixture whose baseline leaves an interface module " + "unread is refused", refused(entry, tarballs))) listing_as(listed) fixtures = read_fixtures(entry, tarballs) order = [fixture_for(fixtures, block)["trial"] for block in range(1, 5)] diff --git a/tests/efficacy/judge.py b/tests/efficacy/judge.py index 17d97b8..470712e 100644 --- a/tests/efficacy/judge.py +++ b/tests/efficacy/judge.py @@ -33,7 +33,8 @@ import lib # noqa: E402 import score # noqa: E402 from harness import (LiveRunError, TrialError, canonical, # noqa: E402 - claim_area, claim_refusal_check, release_area) + claim_area, claim_refusal_check, release_area, + task_folder) HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPT = os.path.basename(__file__) @@ -343,8 +344,9 @@ def copied_dir(base, name): for cache, inner in USER_CACHE_DIRS) -def build_bundle(tree, target): - """Copy one trial's tree into a blind bundle and return what was stripped. +def build_bundle(tree, target, trial=None): + """Copy one trial's tree into a blind bundle and return what was stripped; + `trial` names the trial where the tree's own folder does not. The context file is the loudest marker but not the only one: a README that credits its conventions names the arm just as clearly, so the text files @@ -385,9 +387,13 @@ def build_bundle(tree, target): if spec: with io.open(os.path.join(target, "SPEC.md"), "wb") as handle: handle.write(spec.pop("text")) + # A changed tree's folder carries the task beside the trial's name, and + # a path through its scoring area the trial's name alone. + names = {os.path.basename(tree), trial or os.path.basename(tree)} + leaks = [leak for name in sorted(names) + for leak in surviving_markers(target, name)] return {"removed": removed, "markers_masked": masked, "spec": spec, - "leaks": surviving_markers(target, os.path.basename(tree)), - "digest": digest(target)} + "leaks": leaks, "digest": digest(target)} def spec_text(path): @@ -692,24 +698,30 @@ def refusal(stripped): return None -def trees(root): - """Every scored trial's extracted tree, by canonical trial name.""" +def trees(root, task="build"): + """Every scored trial's extracted tree of `task`, by canonical trial + name: the folder scoring made for the trial, whatever the tree's own + folder is called.""" found = {} - scoring = os.path.join(score.scoring_area(root), "scoring") + scoring = os.path.join(score.scoring_area(root), + task_folder("scoring", task)) for path in sorted(glob.glob(os.path.join(scoring, "*", "tree", "*"))): if os.path.isdir(path): - found[canonical(os.path.basename(path))] = path + trial = os.path.basename(os.path.dirname(os.path.dirname(path))) + found[canonical(trial)] = path return found -def failed_builds(root): - """The trials whose build did not install, by canonical trial name. +def failed_builds(root, task="build"): + """The trials whose tree of `task` did not install, by canonical name. A trial that produced no installable workspace has its quality metrics - recorded as missing, never scored, so its tree is not judged. + recorded as missing, never scored, so its tree is not judged; a change + task that left one is held to the same rule. """ failed = set() - pattern = os.path.join(score.scoring_area(root), "scores", "*.json") + pattern = os.path.join(score.scoring_area(root), + task_folder("scores", task), "*.json") for file in sorted(glob.glob(pattern)): with io.open(file, encoding="utf-8") as handle: record = json.load(handle) @@ -790,10 +802,10 @@ def main(argv): print("--root is required unless --self-test is given") return 2 - available = trees(options.root) + available = trees(options.root, options.task) if not available: - print("no extracted trial trees under %s; score.py writes them" - % score.scoring_area(options.root)) + print("no extracted %s trees under %s; score.py writes them" + % (options.task, score.scoring_area(options.root))) return 2 try: @@ -809,10 +821,11 @@ def main(argv): # The report reads no judge row of a build that did not install, so # judging one would spend readings on a tree nothing counts. - failed = failed_builds(options.root) + failed = failed_builds(options.root, options.task) for name in wanted: if name in failed: - print("%s not judged: its build did not install" % name) + print("%s not judged: its %s tree did not install" + % (name, options.task)) wanted = [name for name in wanted if name not in failed] # A second run against the area takes the same next label as a live one, @@ -837,7 +850,10 @@ def judge_trials(options, available, wanted): # calls on one unchanged tree returned readability 4, 4, 4, 3, 4, 4. The # mean of several is what the report reads, so what is owed here is the # shortfall, which also makes an interrupted run resumable. - judging = os.path.join(score.scoring_area(options.root), "judge") + # A change task's judgings go apart from the build's, with labels and a + # map of their own: both are keyed by the trial. + judging = os.path.join(score.scoring_area(options.root), + task_folder("judge", options.task)) done = judged(judging) if options.repeat < 1: print("refused: --repeat is a count of judgings per trial, at least 1") @@ -892,14 +908,15 @@ def judge_trials(options, available, wanted): repeats.setdefault(name, []).append(label) print("%s as %s" % (name, label)) bundle = os.path.join(bundles, label) - stripped = build_bundle(available[name], bundle) + stripped = build_bundle(available[name], bundle, name) refused = refusal(stripped) if refused: answer = {"argv": None, "error": refused} else: answer = judge_bundle(bundle, options, schema_path) - record = {"trial": name, "blind_id": label, "model": options.model, + record = {"trial": name, "task": options.task, "blind_id": label, + "model": options.model, "repeat": len(repeats[name]), "effort": options.effort, "cli": version, "seed": options.seed, "bundle": stripped, @@ -1353,8 +1370,38 @@ def failed_checks(scratch): encoding="utf-8") as handle: json.dump({"name": name, "install": {"value": value}}, handle) found = failed_builds(root) + changes = os.path.join(score.scoring_area(root), "scores-change") + os.makedirs(changes) + for name, value in (("none-2", False), ("none-1", True)): + with io.open(os.path.join(changes, "%s.json" % name), "w", + encoding="utf-8") as handle: + json.dump({"name": name, "install": {"value": value}}, handle) return [("only a build that did not install goes unjudged", - found == {"none-1"})] + found == {"none-1"}), + ("a changed tree that did not install goes unjudged, read from " + "its own scores", failed_builds(root, "change") == {"none-2"})] + + +def change_checks(scratch): + """A change task's trees are found by their trial, apart from the + build's, and a bundle naming the trial in a path is caught.""" + root = os.path.join(scratch, "changed") + area = score.scoring_area(root) + built = os.path.join(area, "scoring", "none-1", "tree", "none-1") + changed = os.path.join(area, "scoring-change", "none-1", "tree", + "change-none-1") + for tree in (built, changed): + os.makedirs(tree) + plant(changed, {"notes.txt": "built under %s\n" % changed.replace( + "change-none-1", "x")}) + stripped = build_bundle(changed, os.path.join(scratch, "change-bundle"), + "none-1") + return [("a change task's trees are found by their trial, apart from " + "the build's", + trees(root, "change") == {"none-1": changed} + and trees(root) == {"none-1": built}), + ("a changed tree's bundle naming its trial in a path leaks", + any(leak[1] == "none-1" for leak in stripped["leaks"]))] def claim_checks(scratch): @@ -1388,6 +1435,7 @@ def self_test(): checks.extend(claim_checks(scratch)) checks.extend(default_checks(scratch)) checks.extend(failed_checks(scratch)) + checks.extend(change_checks(scratch)) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) shutil.rmtree(scratch, ignore_errors=True) @@ -1408,6 +1456,10 @@ def parse_args(argv): "judge nothing") parser.add_argument("--trial", action="append", default=[], help="judge only this trial, as none-1; repeatable") + parser.add_argument("--task", choices=("build", "change"), + default="build", + help="judge the build trials' trees, or the trees the " + "change tasks left") parser.add_argument("--cli", default=DEFAULT_CLI, choices=("codex", "claude"), help="which CLI drives the judge. `codex` is the " diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 9dde650..380bc20 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -4,7 +4,9 @@ fault tolerance under malformed requests, concurrent writes, latency, an invoice of 500 lines, SQL statements per invoice line, two instances side by side, and the same build on another Python. Each passes or fails, except the -latency, which is recorded as two repeats of its 95th percentile. +latency, which is recorded as two repeats of its 95th percentile. A change +task's tree is read on the same probes and on one more, the data upgrade: a +database its fixture seeded, opened by the changed tree with nothing lost. Each trial is installed into a fresh environment of its own, on the spec's Python, and read there in one in-process run through the test client. A probe @@ -15,11 +17,13 @@ import argparse import datetime +import hashlib import io import json import os import shutil import sys +import tarfile import tempfile sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -27,7 +31,7 @@ import lib # noqa: E402 from harness import (LiveRunError, canonical, claim_area, # noqa: E402 claim_refusal_check, release_area, remove_tree, - scoring_area) + scoring_area, task_folder) from score import (create_venv, pip, python_in, run, # noqa: E402 venv_version) @@ -40,6 +44,10 @@ "python_portability") MEASURED = ("latency_p95_ms",) +# The probe a change task's tree is read on besides: the database the +# fixture saved, opened by the changed tree with nothing lost. +CHANGE_PROBES = ("data_upgrade",) + # The probes the one in-process run reads; portability needs an interpreter # of its own. IN_PROCESS = tuple(name for name in PROBES if name != "python_portability") @@ -71,7 +79,7 @@ # behind that sign-in; a request it turns away, with its redirect, a 401 or # a 403, is never measured, and the probe is lost. QUALITY_SCRIPT = r''' -import builtins, html, io, json, logging, math, os, platform, re, sqlite3 +import builtins, csv, html, io, json, logging, math, os, platform, re, sqlite3 import sys, tempfile, threading, time from decimal import Decimal, InvalidOperation from html.parser import HTMLParser @@ -213,10 +221,14 @@ def folder(): return tempfile.mkdtemp(prefix="quality-probe-", dir=DATABASES) +# The data upgrade names the database the application opens: the one the +# fixture seeds, and then a copy of it for the changed tree. Every other mode +# starts on an empty one of its own. try: import importlib package = importlib.import_module(PACKAGE) - app = package.create_app(os.path.join(folder(), "quality-probe.sqlite")) + app = package.create_app(os.environ.get("QUALITY_DATABASE") + or os.path.join(folder(), "quality-probe.sqlite")) client = app.test_client() except Exception as error: report["error"] = repr(error)[:300] @@ -872,6 +884,265 @@ def fuzz_robustness(): return passed(not failed, requests=len(answers), failed=failed) +# What the data upgrade seeds through the fixture's own application: a +# product of each rated category, a customer, a rule of three kinds over the +# new products, a jurisdiction of its own, and invoices that read all of +# them, one billed to the customer and one on the seed's own data. +UPGRADE_PRODUCTS = ( + {"sku": "UPG-1", "name": "Upgrade lamp", "unit_price": "7.50", + "tax_category": "standard"}, + {"sku": "UPG-2", "name": "Upgrade manual", "unit_price": "15.00", + "tax_category": "reduced"}) +UPGRADE_CUSTOMER = {"name": "Ada Upgrade", "email": "ada.upgrade@example.test", + "address": "1 Upgrade Street\n10115 Berlin"} +UPGRADE_RULES = ( + {"rule_id": "u-pct-lamp", "kind": "percentage", "sku": "UPG-1", + "percent": "12"}, + {"rule_id": "u-bulk-manual", "kind": "bulk", "sku": "UPG-2", "buy": "3", + "pay": "2"}, + {"rule_id": "u-coupon", "kind": "coupon", "sku": "", "code": "UPGRADE", + "amount": "5.00"}) +UPGRADE_JURISDICTION = {"code": "UP", "name": "Upgradia", + "default_rate": "0.2", + "rates": "standard=0.2,reduced=0.05"} +CUSTOMER_LINK = re.compile(r"/customers/(\d+)(?![\d/])") + + +def upgrade_body(jurisdiction, customer, lines, coupons): + return {"jurisdiction": jurisdiction, "currency": "EUR", + "customer": customer, "coupon_codes": coupons, + "sku": [sku for sku, _ in lines], + "quantity": [str(quantity) for _, quantity in lines]} + + +def text_of(answer): + return html.unescape(answer.get_data(as_text=True)) + + +def created(path, body): + """Post one record through its form; Gated where it is turned away.""" + answer = held(form_post(client, path, path, body), "the post to " + path) + return answer.status_code + + +def customer_id(email): + """The id the customer list links to for `email`, read from each linked + customer's export.""" + for found in sorted(set(CUSTOMER_LINK.findall( + text_of(page(client, "/customers")))), key=int): + try: + export = json.loads(page(client, "/customers/%s/export.json" + % found).get_data(as_text=True)) + except ValueError: + continue + if isinstance(export, dict) and export.get("email") == email: + return found + return None + + +def listed_on(): + """What each list page must show of the records seeded.""" + return { + "/products": [value for item in UPGRADE_PRODUCTS + for value in (item["sku"], item["name"])], + "/customers": [UPGRADE_CUSTOMER["name"], UPGRADE_CUSTOMER["email"]], + "/rules": [item["rule_id"] for item in UPGRADE_RULES], + "/jurisdictions": [UPGRADE_JURISDICTION["code"], + UPGRADE_JURISDICTION["name"]]} + + +def invoice_reading(path): + """A saved invoice as other software reads it: its page's status, its + JSON export parsed, and its CSV export's text.""" + shown = page(client, path) + export = page(client, path + "/export.json") + csv_text = page(client, path + "/export.csv") + try: + parsed = json.loads(export.get_data(as_text=True)) + except ValueError: + parsed = None + return {"status": shown.status_code, "export_status": export.status_code, + "export": parsed, "csv_status": csv_text.status_code, + "csv": csv_text.get_data(as_text=True)} + + +def seed_upgrade(): + """Seed the records through the fixture's forms and read each back as + the fixture shows it; the readings, or why the fixture could not.""" + for item in UPGRADE_PRODUCTS: + created("/products", item) + created("/customers", UPGRADE_CUSTOMER) + for item in UPGRADE_RULES: + created("/rules", item) + created("/jurisdictions", UPGRADE_JURISDICTION) + customer = customer_id(UPGRADE_CUSTOMER["email"]) + if customer is None: + return None, "the seeded customer is not listed with its export" + bodies = (upgrade_body("UP", customer, (("UPG-1", 3), ("UPG-2", 4)), + "UPGRADE"), + upgrade_body("DE", "", WORKED, "WELCOME")) + invoices = [] + for body in bodies: + answer = held(form_post(client, "/invoices/new", "/invoices", body), + "the save") + path = saved_page(answer) + if path is None: + return None, "an invoice was not saved: it answered %d" % ( + answer.status_code) + reading = invoice_reading(path) + if not (200 <= reading["status"] < 300 + and isinstance(reading["export"], dict) + and 200 <= reading["csv_status"] < 300): + return None, "the fixture does not show the invoice it saved" + preview = held(form_post(client, "/invoices/new", + "/invoices/preview", body, + headers={"HX-Request": "true"}), + "the preview") + try: + total = Decimal(str(reading["export"].get("total"))) + except InvalidOperation: + total = None + + # A preview is read against the old total only where the fixture's + # own preview shows it. + reading.update(body=body, path=path, + total=None if total is None else str(total), + previewed=bool(total is not None and ok(preview) + and shows_total(preview, total))) + invoices.append(reading) + pages = listed_on() + for path, values in pages.items(): + shown = text_of(page(client, path)) + missing = [value for value in values if value not in shown] + if missing: + return None, "%s does not list %s" % (path, missing[0]) + export = page(client, "/customers/%s/export.json" % customer) + try: + customer_export = json.loads(export.get_data(as_text=True)) + except ValueError: + return None, "the seeded customer's export is not JSON" + return {"invoices": invoices, "pages": pages, + "customer": {"id": customer, "export": customer_export}}, None + + +def unkept(old, new, where="$"): + """The first place `new` no longer holds what `old` did, or None: every + key `old` had with the same value, a list as long, item by item. A key + only `new` has is the change's own, and is no loss.""" + if isinstance(old, dict): + if not isinstance(new, dict): + return where + for key, value in old.items(): + if key not in new: + return "%s.%s" % (where, key) + found = unkept(value, new[key], "%s.%s" % (where, key)) + if found: + return found + return None + if isinstance(old, list): + if not isinstance(new, list) or len(new) != len(old): + return where + for index, (before, after) in enumerate(zip(old, new)): + found = unkept(before, after, "%s[%d]" % (where, index)) + if found: + return found + return None + return None if old == new else where + + +def csv_unkept(old, new): + """Where a CSV export no longer holds an old column's values, or None. + A column only the new export has is the change's own.""" + before = list(csv.DictReader(io.StringIO(old))) + after = list(csv.DictReader(io.StringIO(new))) + if len(before) != len(after): + return "it holds %d rows, not %d" % (len(after), len(before)) + for index, (row, now) in enumerate(zip(before, after)): + for column, value in row.items(): + if now.get(column) != value: + return "row %d's %s reads %r, not %r" % ( + index + 1, column, now.get(column), value) + return None + + +def data_upgrade(seeded): + """The changed tree on a copy of the fixture's database: every record + seeded is still there and reads the same, every old invoice opens and + prices as it did, and the upgraded database takes new records.""" + failures = [] + for path, values in seeded["pages"].items(): + answer = page(client, path) + shown = text_of(answer) + if not ok(answer): + failures.append("%s answered %d" % (path, answer.status_code)) + continue + failures += ["%s no longer lists %s" % (path, value) + for value in values if value not in shown] + for old in seeded["invoices"]: + now = invoice_reading(old["path"]) + if not 200 <= now["status"] < 300: + failures.append("%s answered %d" % (old["path"], now["status"])) + continue + place = unkept(old["export"], now["export"]) + if place: + failures.append("%s/export.json no longer reads the same at %s" + % (old["path"], place)) + if now["csv_status"] != old["csv_status"]: + failures.append("%s/export.csv answered %d" % ( + old["path"], now["csv_status"])) + else: + place = csv_unkept(old["csv"], now["csv"]) + if place: + failures.append("%s/export.csv: %s" % (old["path"], place)) + if old["previewed"]: + preview = held(form_post(client, "/invoices/new", + "/invoices/preview", old["body"], + headers={"HX-Request": "true"}), + "the preview") + if not (ok(preview) and shows_total(preview, + Decimal(old["total"]))): + failures.append("the old invoice %s no longer prices at %s" + % (old["path"], old["total"])) + customer = seeded["customer"] + answer = page(client, "/customers/%s/export.json" % customer["id"]) + try: + export = json.loads(answer.get_data(as_text=True)) + except ValueError: + export = None + place = unkept(customer["export"], export) + if place: + failures.append("the customer's export no longer reads the same at %s" + % place) + + # The new schema has to take new rows on the old file too, not only read + # the old ones: a column added for new tables alone fails here. + written = {"/jurisdictions": {"code": "U2", "name": "Upgradia Nova", + "default_rate": "0.1", + "rates": "standard=0.1"}, + "/rules": {"rule_id": "u-pct-after", "kind": "percentage", + "sku": "UPG-2", "percent": "3"}} + for path, body in written.items(): + created(path, body) + if body["code" if path == "/jurisdictions" else "rule_id"] \ + not in text_of(page(client, path)): + failures.append("a record posted to %s after the upgrade is not " + "listed" % path) + saved = saved_page(held(form_post(client, "/invoices/new", "/invoices", + seeded["invoices"][0]["body"]), + "the save")) + if saved is None: + failures.append("an invoice saved after the upgrade has no page") + else: + again = invoice_reading(saved) + total = (again["export"] or {}).get("total") if isinstance( + again["export"], dict) else None + if str(total) != str(seeded["invoices"][0]["export"].get("total")): + failures.append("the first invoice saved again totals %r, not %r" + % (total, seeded["invoices"][0]["export"].get( + "total"))) + return passed(not failures, failures=failures[:20]) + + report["signed_in"] = sign_in(client) if not report["signed_in"] or MODE == "portability": try: @@ -880,6 +1151,27 @@ def fuzz_robustness(): report["index_error"] = str(error) finish() +# The data upgrade's two halves each run alone: the fixture seeds and reads +# back, and the changed tree reads the copy of what it seeded. +if MODE in ("seed", "upgrade"): + report["running"] = MODE + save() + try: + if MODE == "seed": + report["seeded"], report["seed_error"] = seed_upgrade() + else: + with real_open(os.environ["QUALITY_SEEDED"], + encoding="utf-8") as handle: + report["probes"]["data_upgrade"] = data_upgrade( + json.load(handle)) + except Gated as error: + report["gated"] = str(error) + except Raised as error: + report["raised"] = str(error) + except Exception as error: + report["reader_error"] = repr(error)[:300] + finish() + # Fuzzing comes last: what a malformed request stores cannot reach another # probe's reading. PROBES = (("latency_p95_ms", latency_p95_ms), ("n_plus_one", n_plus_one), @@ -1067,30 +1359,49 @@ def read_portability(tree, where, other): remove_tree(venv) -def read_trial(area, name, scores_file, other): - """Every quality probe on one scored trial, read from its score file.""" +def read_trial(area, name, scores_file, other, task="build"): + """Every quality probe on one scored trial of `task`, read from its score + file; a change task's adds the data upgrade.""" with io.open(scores_file, encoding="utf-8") as handle: scores = json.load(handle) tree = scores.get("workspace") result = {"name": name, "read_at": datetime.datetime.now().isoformat( timespec="seconds")} - where = os.path.join(area, "quality", name) + where = os.path.join(area, task_folder("quality", task), name) os.makedirs(where, exist_ok=True) + + # The fixture seeds first, in an environment of its own that is gone + # before the changed tree's is made. + seeded = reason = None + if task == "change": + seeded, reason = seed_fixture(scores, where) + upgrade = None venv = create_venv(os.path.join(where, "venv")) try: result["python"] = venv_version(venv) installed = pip(venv, "install", tree, cwd=where) if installed["failed"] or installed["status"] != 0: - reason = ("the trial did not install: %s" - % (installed["stderr"] or installed["stdout"])[-300:]) - probes = probe_results(None, reason, lost=True) + reason_lost = ("the trial did not install: %s" + % (installed["stderr"] + or installed["stdout"])[-300:]) + probes = probe_results(None, reason_lost, lost=True) + if task == "change" and seeded: + upgrade = dict(lost_reading("data_upgrade", reason_lost), + **provenance(scores, seeded)) else: - payload, reason, stalled = probe_runtime(python_in(venv), where) - probes = probe_results(payload, reason, stalled=stalled) + payload, why, stalled = probe_runtime(python_in(venv), where) + probes = probe_results(payload, why, stalled=stalled) + if task == "change" and seeded: + upgrade = upgrade_with(python_in(venv), where, seeded, + dict(os.environ), + provenance(scores, seeded)) finally: # About 290 MB a trial, and nothing reads it again. remove_tree(venv) + if task == "change" and upgrade is None: + upgrade = dict(missing_reading("data_upgrade", reason), + **provenance(scores, None)) # A build the spec's Python could not install, boot or sign in is lost # on the other one too: it was never read there. @@ -1106,9 +1417,142 @@ def read_trial(area, name, scores_file, other): else: probes["python_portability"] = read_portability(tree, where, other) result["probes"] = {name: probes[name] for name in PROBES} + if task == "change": + result["probes"]["data_upgrade"] = upgrade return result +def fixture_tree(scores, where): + """The tree the change task started from, out of the changed tree's own + history: its starting commit, as the agent was handed it.""" + tree, base = scores.get("workspace"), scores.get("base") + if not base: + return None, "the change names no starting commit" + target = os.path.join(where, "fixture") + remove_tree(target) + os.makedirs(target) + archive = os.path.join(os.path.abspath(where), "fixture.tar") + made = run(["git", "-C", tree, "archive", "--format=tar", "-o", archive, + base], timeout=300) + if made["failed"] or made["status"] != 0: + return None, ("git could not read the starting commit %s: %s" + % (base, (made["failed"] or made["stderr"])[-300:])) + with tarfile.open(archive) as handle: + handle.extractall(target, filter="data") + os.remove(archive) + return target, None + + +def folder_digest(folder): + """The sha256 over a folder's files, by name and content.""" + digest = hashlib.sha256() + for name in sorted(os.listdir(folder)): + path = os.path.join(folder, name) + if os.path.isfile(path): + digest.update(name.encode("utf-8") + b"\0") + with io.open(path, "rb") as handle: + digest.update(handle.read()) + return digest.hexdigest() + + +def seed_fixture(scores, where): + """Seed a database through the fixture's own application, installed on + the spec's Python; the seeding, or None and why it is missing.""" + tree, reason = fixture_tree(scores, where) + if reason: + return None, reason + venv = create_venv(os.path.join(where, "venv-fixture")) + try: + installed = pip(venv, "install", tree, cwd=where) + if installed["failed"] or installed["status"] != 0: + return None, ("the fixture did not install: %s" + % (installed["stderr"] + or installed["stdout"])[-300:]) + return seed_with(python_in(venv), where, dict(os.environ)) + finally: + + # The fixture's environment, as large as the trial's, is not read + # again once it has seeded. + remove_tree(venv) + remove_tree(tree) + + +# Where the fixture's database is seeded, and where the changed tree's copy +# of it is, each a folder of its own so a database's sidecars go with it. +SEEDED, UPGRADED, DATABASE = "seeded", "upgraded", "upgrade.sqlite" + + +def seed_with(python, where, env): + """Seed through the application `python` imports; the seeding, or None + and why. A fixture that cannot seed leaves the upgrade unread, never + failed: it is no arm's.""" + folder = os.path.join(where, SEEDED) + remove_tree(folder) + os.makedirs(folder) + env = dict(env, QUALITY_DATABASE=os.path.join(folder, DATABASE)) + payload, reason, stalled = probe_runtime(python, where, "seed", env=env) + if reason: + return None, reason + if "error" in payload: + return None, "the fixture would not boot: %s" % payload["error"] + if not payload.get("signed_in"): + return None, "the fixture's administrator could not sign in" + if not payload.get("seeded"): + return None, "the fixture could not be seeded: %s" % ( + payload.get("seed_error") or payload.get("gated") + or payload.get("raised") or payload.get("reader_error") + or stalled) + readings = os.path.join(where, "seeded.json") + with io.open(readings, "w", encoding="utf-8") as handle: + json.dump(payload["seeded"], handle, indent=2, sort_keys=True) + return {"folder": folder, "readings": readings, + "sha256": folder_digest(folder), + "python": payload.get("python")}, None + + +def provenance(scores, seeded): + """What a data upgrade was read against: the fixture by its hash, the + commit the change started from, and the database it seeded.""" + fixture = scores.get("fixture") or {} + return {"fixture": fixture.get("trial"), + "fixture_sha256": fixture.get("sha256"), + "base": scores.get("base"), + "seeded_sha256": (seeded or {}).get("sha256")} + + +def upgrade_with(python, where, seeded, env, origin): + """The changed tree, as `python` imports it, on a copy of the seeded + database: the data upgrade's reading, beside where it came from.""" + copy = os.path.join(where, UPGRADED) + remove_tree(copy) + shutil.copytree(seeded["folder"], copy) + env = dict(env, QUALITY_DATABASE=os.path.join(copy, DATABASE), + QUALITY_SEEDED=seeded["readings"]) + payload, reason, stalled = probe_runtime(python, where, "upgrade", + env=env) + if reason: + return dict(missing_reading("data_upgrade", reason), **origin) + + # A changed tree that will not open, sign in on or answer from the + # database its fixture saved has lost that data to its users. + if "error" in payload: + return dict(lost_reading("data_upgrade", ( + "the changed tree would not open the fixture's database: %s" + % payload["error"])), **origin) + if not payload.get("signed_in"): + return dict(lost_reading("data_upgrade", ( + "the administrator could not sign in on the fixture's " + "database")), **origin) + probe = (payload.get("probes") or {}).get("data_upgrade") + if probe is not None: + return dict(probe, **origin) + trouble = payload.get("gated") or payload.get("raised") or stalled + if trouble: + return dict(lost_reading("data_upgrade", trouble), **origin) + return dict(missing_reading("data_upgrade", payload.get( + "reader_error") or "the upgrade did not report"), **origin) + + # A stand-in application for the in-process probes, importable without # Flask, on a real SQLite file, so the statement count and the database lock # are SQLite's own. `sound` passes every probe; each other mode plants the @@ -1449,6 +1893,382 @@ def create_app(database): return App(database) ''' +# A stand-in for the data upgrade, a fixture at version 1 and a changed +# tree at version 2 of one application on a real SQLite file: version 2 adds +# a cap to each jurisdiction and a minimum to each rule, shows the cap in its +# JSON and CSV exports, and adds the columns to an old file. `sound` does +# all of that. Each other mode plants one fault in version 2 alone: +# `unmigrated` adds the columns to new files only and then reads them, +# `dropping` rebuilds an old file empty, `rewriting` migrates and resets every +# jurisdiction's rate, rows all kept, `fragile` cannot read an old +# jurisdiction's empty cap, so old invoices break while new ones open, and +# `refusing` will not open an old file at all. At version 1, `unlisting` +# links no customer, so nothing can be seeded. +UPGRADE_APP = '''import decimal +import json +import os +import sqlite3 + +VERSION = __VERSION__ +MODE = "__MODE__" +TOKEN = '' +CENT = decimal.Decimal("0.01") +SEED = (("WID-1", "Widget", "10.00", "standard"), + ("GAD-2", "Gadget", "24.50", "standard"), + ("BOK-3", "Handbook", "12.00", "reduced"), + ("SRV-4", "Support hour", "80.00", "standard"), + ("SEE-5", "Seed pack", "3.75", "zero")) +TABLES = ("products", "customers", "rules", "jurisdictions", "invoices", + "lines") +ADDED = (("rules", "minimum"), ("jurisdictions", "caps")) + + +class Response(object): + def __init__(self, status, body="", headers=None): + self.status_code = status + self.headers = dict(headers or {}) + self._body = body + + def get_data(self, as_text=False): + return self._body if as_text else self._body.encode("utf-8") + + +def form(action, body=""): + return ('%s
%s
' + % (body, action, TOKEN)) + + +def columns(connection, table): + return [row[1] for row in connection.execute( + "PRAGMA table_info(%s)" % table)] + + +class App(object): + def __init__(self, database): + self.database = database + connection = self.connect() + old = "jurisdictions" in [row[0] for row in connection.execute( + "SELECT name FROM sqlite_master WHERE type = 'table'")] + stale = old and VERSION == 2 and "caps" not in columns( + connection, "jurisdictions") + if stale and MODE == "refusing": + raise RuntimeError("this database is from an older version") + if stale and MODE == "dropping": + for table in TABLES: + connection.execute("DROP TABLE %s" % table) + added = ", minimum TEXT" if VERSION == 2 else "" + capped = ", caps TEXT" if VERSION == 2 else "" + connection.executescript( + "CREATE TABLE IF NOT EXISTS admin (password TEXT);" + "CREATE TABLE IF NOT EXISTS products (sku TEXT PRIMARY KEY, " + "name TEXT, unit_price TEXT, tax_category TEXT);" + "CREATE TABLE IF NOT EXISTS customers (id INTEGER PRIMARY KEY, " + "name TEXT, email TEXT, address TEXT);" + "CREATE TABLE IF NOT EXISTS rules (rule_id TEXT PRIMARY KEY, " + "kind TEXT, sku TEXT, detail TEXT%s);" + "CREATE TABLE IF NOT EXISTS jurisdictions (code TEXT PRIMARY " + "KEY, name TEXT, default_rate TEXT%s);" + "CREATE TABLE IF NOT EXISTS invoices (id INTEGER PRIMARY KEY, " + "jurisdiction TEXT, customer TEXT, coupons TEXT);" + "CREATE TABLE IF NOT EXISTS lines (invoice INTEGER, position " + "INTEGER, sku TEXT, quantity INTEGER);" % (added, capped)) + if stale and MODE not in ("unmigrated", "dropping"): + for table, column in ADDED: + connection.execute("ALTER TABLE %s ADD COLUMN %s TEXT" + % (table, column)) + if MODE == "rewriting": + connection.execute("UPDATE jurisdictions SET " + "default_rate = '0'") + if not connection.execute("SELECT * FROM admin").fetchone(): + connection.execute("INSERT INTO admin VALUES (?)", ( + os.environ.get("TARIFF_ADMIN_PASSWORD"),)) + if not connection.execute("SELECT * FROM products").fetchone(): + connection.executemany("INSERT INTO products VALUES " + "(?, ?, ?, ?)", SEED) + for code, rate in (("DE", "0.19"), ("IE", "0.23")): + self.add_jurisdiction(connection, code, code, rate) + connection.commit() + connection.close() + + def connect(self): + return sqlite3.connect(self.database) + + def add_jurisdiction(self, connection, code, name, rate): + if VERSION == 2: + connection.execute("INSERT INTO jurisdictions VALUES " + "(?, ?, ?, ?)", (code, name, rate, "{}")) + else: + connection.execute("INSERT INTO jurisdictions VALUES (?, ?, ?)", + (code, name, rate)) + + def test_client(self): + return Client(self) + + +def listed(value): + if value is None: + return [] + return list(value) if isinstance(value, (list, tuple)) else [value] + + +class Client(object): + def __init__(self, app): + self.app = app + self.signed = False + + def open(self, path, method="GET", data=None, headers=None): + connection = self.app.connect() + try: + answer = self.dispatch(connection, path.split("?")[0], method, + data or {}) + connection.commit() + return answer + except Exception as error: + return Response(500, "Internal Server Error: %r" % error) + finally: + connection.close() + + def dispatch(self, connection, path, method, data): + if path == "/sign-in": + if method == "GET": + return Response(200, form("/sign-in")) + stored = connection.execute("SELECT password FROM admin") + if (data.get("csrf_token") == "t" + and data.get("username") == "admin" + and data.get("password") == stored.fetchone()[0]): + self.signed = True + return Response(302, "", {"Location": "/"}) + return Response(200, "wrong" + form("/sign-in")) + if not self.signed: + return Response(302, "", {"Location": "/sign-in"}) + if method == "POST" and data.get("csrf_token") != "t": + return Response(400, "missing token") + parts = path.strip("/").split("/") + if path == "/": + return Response(200, "dashboard") + if parts[0] in ("products", "rules", "jurisdictions") \\ + and len(parts) == 1: + if method == "POST": + return self.create(connection, parts[0], data) + return Response(200, form(path, self.listing(connection, + parts[0]))) + if parts[0] == "customers": + return self.customers(connection, parts, method, data) + if parts[0] == "invoices": + return self.invoices(connection, parts, method, data) + return Response(404, "not found") + + def listing(self, connection, table): + if table == "products": + rows = connection.execute("SELECT sku, name FROM products") + elif table == "rules": + rows = connection.execute("SELECT rule_id, kind FROM rules") + elif VERSION == 2: + rows = connection.execute("SELECT code, name, caps FROM " + "jurisdictions") + else: + rows = connection.execute("SELECT code, name FROM jurisdictions") + return "".join("

%s

" % " ".join(str(value) for value in row) + for row in rows) + + def create(self, connection, table, data): + if table == "products": + connection.execute("INSERT INTO products VALUES (?, ?, ?, ?)", ( + data["sku"], data["name"], data["unit_price"], + data["tax_category"])) + elif table == "rules": + detail = json.dumps({key: data.get(key) for key in ( + "percent", "buy", "pay", "code", "amount")}) + if VERSION == 2: + connection.execute("INSERT INTO rules VALUES (?, ?, ?, ?, ?)", + (data["rule_id"], data["kind"], + data.get("sku"), detail, None)) + else: + connection.execute("INSERT INTO rules VALUES (?, ?, ?, ?)", + (data["rule_id"], data["kind"], + data.get("sku"), detail)) + else: + self.app.add_jurisdiction(connection, data["code"], data["name"], + data["default_rate"]) + return Response(302, "", {"Location": "/" + table}) + + def customers(self, connection, parts, method, data): + if len(parts) == 1 and method == "POST": + connection.execute("INSERT INTO customers (name, email, address) " + "VALUES (?, ?, ?)", (data["name"], + data["email"], + data["address"])) + return Response(302, "", {"Location": "/customers"}) + if len(parts) == 1: + rows = connection.execute("SELECT id, name, email FROM customers") + return Response(200, form("/customers", "".join( + ("

%s %s

" if MODE == "unlisting" + else '

%s %s

') % row + for row in rows))) + row = connection.execute("SELECT id, name, email, address FROM " + "customers WHERE id = ?", + (parts[1],)).fetchone() + if row is None: + return Response(404, "not found") + invoices = [found[0] for found in connection.execute( + "SELECT id FROM invoices WHERE customer = ? ORDER BY id", + (str(row[0]),))] + return Response(200, json.dumps({ + "customer_id": row[0], "name": row[1], "email": row[2], + "address": row[3], "invoices": invoices})) + + def priced(self, connection, jurisdiction, coupons, lines): + found = connection.execute("SELECT * FROM jurisdictions WHERE code " + "= ?", (jurisdiction,)).fetchone() + if found is None: + raise LookupError(jurisdiction) + rate = decimal.Decimal(found[2]) + if VERSION == 2: + caps = json.loads(found[3]) if MODE == "fragile" else ( + json.loads(found[3] or "{}")) + rate = rate if caps is not None else rate + net = [] + for sku, quantity in lines: + price = connection.execute("SELECT unit_price FROM products " + "WHERE sku = ?", (sku,)).fetchone() + net.append((sku, quantity, (decimal.Decimal(price[0]) + * quantity).quantize(CENT))) + subtotal = sum((amount for _, _, amount in net), + decimal.Decimal("0")) + for kind, detail in connection.execute("SELECT kind, detail FROM " + "rules"): + detail = json.loads(detail) + if kind == "coupon" and detail.get("code") in coupons \\ + and detail.get("amount"): + subtotal -= decimal.Decimal(detail["amount"]) + total = (subtotal * (1 + rate)).quantize(CENT) + return net, str(total) + + def invoices(self, connection, parts, method, data): + if parts[1:] in (["preview"], []) and method == "POST": + lines = [(sku, int(quantity)) for sku, quantity in zip( + listed(data.get("sku")), listed(data.get("quantity")))] + coupons = (data.get("coupon_codes") or "").split(",") + _, total = self.priced(connection, data["jurisdiction"], coupons, + lines) + if parts[1:] == ["preview"]: + return Response(200, "

Total %s

" % total) + invoice = connection.execute( + "INSERT INTO invoices (jurisdiction, customer, coupons) " + "VALUES (?, ?, ?)", (data["jurisdiction"], + data.get("customer") or "", + data.get("coupon_codes") or "") + ).lastrowid + connection.executemany("INSERT INTO lines VALUES (?, ?, ?, ?)", + [(invoice, position, sku, quantity) + for position, (sku, quantity) + in enumerate(lines)]) + return Response(302, "", {"Location": "/invoices/%d" % invoice}) + if parts[1:] == ["new"]: + return Response(200, form("/invoices/preview")) + row = connection.execute("SELECT jurisdiction, coupons FROM invoices " + "WHERE id = ?", (parts[1],)).fetchone() + if row is None: + return Response(404, "not found") + lines = connection.execute("SELECT sku, quantity FROM lines WHERE " + "invoice = ? ORDER BY position", + (parts[1],)).fetchall() + net, total = self.priced(connection, row[0], row[1].split(","), + lines) + if parts[2:] == ["export.json"]: + export = {"invoice_id": int(parts[1]), "jurisdiction": row[0], + "lines": [{"sku": sku, "quantity": quantity, + "net": str(amount)} + for sku, quantity, amount in net], + "total": total} + if VERSION == 2: + export["caps"] = {} + return Response(200, json.dumps(export)) + if parts[2:] == ["export.csv"]: + head = "sku,quantity,net" + (",cap" if VERSION == 2 else "") + return Response(200, "\\n".join([head] + [ + "%s,%d,%s" % (sku, quantity, amount) + + ("," if VERSION == 2 else "") + for sku, quantity, amount in net]) + "\\n") + return Response(200, "

Invoice %s

Total %s

" + % (parts[1], total)) + + +def create_app(database): + return App(database) +''' + +# The faults the data upgrade must catch at version 2, and what each loses. +UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "fragile", + "refusing") + + +def plant_upgrade(where, version, mode): + """The stand-in at `version` in `mode`, importable from its own folder; + the environment that imports it.""" + site = os.path.join(where, "site-%d" % version) + package = os.path.join(site, "tariff") + os.makedirs(package) + with io.open(os.path.join(package, "__init__.py"), "w", + encoding="utf-8") as handle: + handle.write(UPGRADE_APP.replace("__VERSION__", str(version)) + .replace("__MODE__", mode)) + return dict(os.environ, PYTHONPATH=site) + + +def upgrade_reading(scratch, fixture, changed): + """The data upgrade of a version 2 in mode `changed` over a version 1 + in mode `fixture`: the reading, or why seeding left it missing.""" + where = os.path.join(scratch, "upgrade-%s-%s" % (fixture, changed)) + os.makedirs(where) + seeded, reason = seed_with(sys.executable, where, + plant_upgrade(where, 1, fixture)) + if seeded is None: + return dict(missing_reading("data_upgrade", reason)) + return upgrade_with(sys.executable, where, seeded, + plant_upgrade(where, 2, changed), + {"seeded_sha256": seeded["sha256"]}) + + +def upgrade_self_checks(scratch): + """A sound upgrade passes; each planted fault fails or loses the probe; + a fixture that cannot seed leaves it missing.""" + sound = upgrade_reading(scratch, "sound", "sound") + faults = {mode: upgrade_reading(scratch, "sound", mode) + for mode in UPGRADE_FAULTS} + unseeded = upgrade_reading(scratch, "unlisting", "sound") + failed = sorted(mode for mode, reading in faults.items() + if reading.get("passed") is False) + return [ + ("a version 2 that migrates the old database keeps every record", + sound.get("passed") is True and not sound.get("failures") + and len(sound.get("seeded_sha256") or "") == 64), + ("a schema change shipped without a migration fails the upgrade", + faults["unmigrated"].get("passed") is False + and any("/jurisdictions" in failure for failure in + faults["unmigrated"].get("failures") or [])), + ("an old database rebuilt empty fails the upgrade", + faults["dropping"].get("passed") is False + and any("no longer lists" in failure for failure in + faults["dropping"].get("failures") or [])), + ("rows all kept with their values changed fail the upgrade", + faults["rewriting"].get("passed") is False + and any("no longer reads the same" in failure for failure in + faults["rewriting"].get("failures") or [])), + ("old invoices that break on the new field fail the upgrade", + faults["fragile"].get("passed") is False + and any("/invoices/" in failure for failure in + faults["fragile"].get("failures") or [])), + ("a version 2 that will not open the old database loses the upgrade", + faults["refusing"].get("passed") is False + and bool(faults["refusing"].get("lost"))), + ("every planted upgrade fault fails", + failed == sorted(UPGRADE_FAULTS)), + ("a fixture that cannot seed leaves the upgrade missing, not failed", + unseeded.get("passed") is None and bool(unseeded.get("missing"))), + ] + + FAULTS = {"fragile": "fuzz_robustness", "brittle": "fuzz_robustness", "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", @@ -1681,6 +2501,47 @@ def leftover_self_checks(scratch): sorted(result["probes"]) == sorted(PROBES) and all("did not install" in probe.get("lost", "") for probe in result["probes"].values())), + ] + change_reading_checks(area, tree) + + +def change_reading_checks(area, tree): + """A change task is read from its own scores into its own folders, adds + the data upgrade, and loses it with a changed tree that will not + install; with no fixture to seed, the upgrade is missing.""" + scores_file = os.path.join(area, "scores-change", "none-1.json") + os.makedirs(os.path.dirname(scores_file)) + with io.open(scores_file, "w", encoding="utf-8") as handle: + json.dump({"workspace": tree, "fixture": {"trial": "none-2", + "sha256": "f" * 64}}, + handle) + unseeded = read_trial(area, "none-1", scores_file, None, "change") + + # A fixture that seeded, as the reading takes it, over the same tree. + saved = globals()["seed_fixture"] + globals()["seed_fixture"] = lambda scores, where: ( + {"sha256": "a" * 64, "folder": where, "readings": None}, None) + try: + seeded = read_trial(area, "none-1", scores_file, None, "change") + finally: + globals()["seed_fixture"] = saved + upgrade = seeded["probes"]["data_upgrade"] + return [ + ("a change task is read from its own scores into " + "quality-scores-change", + sorted(scored_trials(area, "change")) == ["none-1"] + and readings_folder(area, "change") + == os.path.join(area, "quality-scores-change") + and os.path.isdir(os.path.join(area, "quality-change", "none-1"))), + ("a change task with no starting commit leaves the upgrade missing", + sorted(unseeded["probes"]) == sorted(PROBES + CHANGE_PROBES) + and "starting commit" in (unseeded["probes"]["data_upgrade"] + .get("missing") or "")), + ("a changed tree that does not install loses the upgrade, its " + "fixture named", + "did not install" in (upgrade.get("lost") or "") + and upgrade.get("passed") is False + and upgrade.get("fixture_sha256") == "f" * 64 + and upgrade.get("seeded_sha256") == "a" * 64), ] @@ -1692,7 +2553,7 @@ def self_test(): os.makedirs(scratch) checks = (runtime_self_checks(scratch) + reading_self_checks() + portability_self_checks(scratch) + claim_self_checks(scratch) - + leftover_self_checks(scratch)) + + leftover_self_checks(scratch) + upgrade_self_checks(scratch)) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) remove_tree(scratch) @@ -1718,6 +2579,10 @@ def parse_args(argv): parser.add_argument("--reread", action="store_true", help="read a trial already read; by default such a " "trial is skipped") + parser.add_argument("--task", choices=("build", "change"), + default="build", + help="read the build trials' trees, or the trees the " + "change tasks left, with the data upgrade") parser.add_argument("--self-test", action="store_true", help="prove every probe against a planted app; read " "no trial") @@ -1732,20 +2597,14 @@ def main(argv): print("--root is required unless --self-test is given") return 2 - # A score is filed under its trial's name, read as the arms spell it. area = scoring_area(options.root) - scores = os.path.join(area, "scores") - scored = {canonical(os.path.splitext(entry)[0]): - os.path.join(scores, entry) - for entry in (sorted(os.listdir(scores)) - if os.path.isdir(scores) else []) - if entry.endswith(".json")} + scored = scored_trials(area, options.task) wanted = (sorted(canonical(name) for name in options.trial) if options.trial else sorted(scored)) missing = [name for name in wanted if name not in scored] if not scored or missing: - print("no build score for %s under %s; score.py writes them" - % (", ".join(missing) or "any trial", area)) + print("no %s score for %s under %s; score.py writes them" + % (options.task, ", ".join(missing) or "any trial", area)) return 2 # A run clears each trial's environment before rebuilding it, so a second @@ -1761,9 +2620,24 @@ def main(argv): release_area(claim) +def scored_trials(area, task): + """Every score of `task` in the scoring area, by the trial's name as the + arms spell it.""" + scores = os.path.join(area, task_folder("scores", task)) + return {canonical(os.path.splitext(entry)[0]): os.path.join(scores, entry) + for entry in (sorted(os.listdir(scores)) + if os.path.isdir(scores) else []) + if entry.endswith(".json")} + + +def readings_folder(area, task): + """Where the quality readings of `task` are filed.""" + return os.path.join(area, task_folder("quality-scores", task)) + + def read_trials(options, area, scored, wanted): """Read each wanted trial not read yet; return the exit code.""" - target = os.path.join(area, "quality-scores") + target = readings_folder(area, options.task) done = [] if not options.reread: for name in wanted: @@ -1781,7 +2655,7 @@ def read_trials(options, area, scored, wanted): os.makedirs(target, exist_ok=True) for name in wanted: print("%s reading for quality" % name) - result = read_trial(area, name, scored[name], other) + result = read_trial(area, name, scored[name], other, options.task) with io.open(os.path.join(target, "%s.json" % name), "w", encoding="utf-8") as handle: json.dump(result, handle, indent=2, sort_keys=True) diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 4f2e961..9b73948 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -651,9 +651,42 @@ def load(root, named=None): name = canonical(reading.get("name") or "") if name in trials and not trials[name].get("change_only"): trials[name][key] = reading + + # A change task's own readings sit beside its change score, as the + # build's beside its score, and go only with a trial that has one. + for kind, key in CHANGE_READINGS: + for file in sorted(glob.glob(os.path.join(area, kind, "*.json"))): + with io.open(file, encoding="utf-8") as handle: + reading = json.load(handle) + name = canonical(reading.get("name") or "") + if name in trials and trials[name]["change"] is not None: + trials[name][key] = reading + for file in sorted(glob.glob(os.path.join(area, "judge-change", + "T*.json"))): + with io.open(file, encoding="utf-8") as handle: + judging = json.load(handle) + name = canonical(judging.get("trial") or "") + if (name in trials and trials[name]["change"] is not None + and judging.get("outcome") == "judged"): + trials[name].setdefault("change_judgings", []).append(judging) return trials +# The change task's readings beyond its score, each the folder it is filed +# in and the key a trial carries it under. +CHANGE_READINGS = (("security-scores-change", "change_security"), + ("quality-scores-change", "change_quality")) + + +def drop_change(trial): + """A trial, in place, without its change task's readings.""" + trial["change"] = None + for _, key in CHANGE_READINGS: + trial.pop(key, None) + trial.pop("change_judgings", None) + return trial + + def round_trials(root): """A root's trials as its report and its archive's verify read them, and why they cannot be read: (trials, problem).""" @@ -1703,7 +1736,7 @@ def exclude_reached(trials, scans, per_task=False): and trials[build].get("change_only"): del trials[build] elif trials[build]["change"] is not None: - trials[build]["change"] = None + drop_change(trials[build]) else: continue left_out.append(name) @@ -5489,6 +5522,80 @@ def problem(*records): return checks +def change_reading_checks(): + """A change task's own readings go with its change score, never with a + build's; its two targets sit once each on the ISO radar, read whatever + its build did; a pilot round's table reads neither.""" + scratch = tempfile.mkdtemp(prefix="efficacy-report-change-readings-") + area = scoring_area(os.path.join(scratch, "run")) + + def plant(kind, name, body): + os.makedirs(os.path.join(area, kind), exist_ok=True) + with io.open(os.path.join(area, kind, name + ".json"), "w", + encoding="utf-8") as handle: + json.dump(body, handle) + upgrade = {"passed": True, "seeded_sha256": "a" * 64} + for name in ("none-1", "inline-1"): + plant("scores", name, {"name": name}) + plant("security-scores-change", name, {"name": name, "probes": {}}) + plant("quality-scores-change", name, { + "name": name, "probes": {"data_upgrade": upgrade}}) + plant("scores-change", "none-1", {"name": "none-1", "interfaces": { + "value": 1.0, "missing": None}}) + plant("judge-change", "T1", {"trial": "none-1", "outcome": "judged"}) + plant("judge-change", "T2", {"trial": "none-1", "outcome": "failed"}) + trials = load(os.path.join(scratch, "run")) + none, inline = trials["none-1"], trials["inline-1"] + checks = [("a change task's security, quality and judgings go with its " + "change score, apart from the build's", + none["change_quality"]["probes"]["data_upgrade"] == upgrade + and none["change_security"]["name"] == "none-1" + and len(none["change_judgings"]) == 1 + and none["security"] is None and none["quality"] is None + and "change_quality" not in inline + and "change_judgings" not in inline)] + drop_change(none) + checks.append(("a change reading left out takes its own readings along", + none["change"] is None and "change_quality" not in none + and "change_judgings" not in none)) + shutil.rmtree(scratch, ignore_errors=True) + + placed = [(axis, sub, source) for axis, sub, _, source, _, _ + in iso_targets() if source.startswith(CHANGE_SOURCE)] + checks.append(( + "the interfaces sit on Interoperability and the data upgrade on " + "Adaptability, once each", + placed == [("Compatibility", "Interoperability", + "change:interfaces"), + ("Flexibility", "Adaptability", "change:data_upgrade")])) + checks.append(("a pilot round's table reads no change-task target", + not any(source.startswith(CHANGE_SOURCE) + for _, _, _, source, _, _ + in iso_targets(pilot_axes())))) + + def reading(interfaces, data_upgrade, install=True): + trial = {"round": "C1", "scores": { + "install": {"value": install, "missing": None}}, + "change": {"name": "none-1", "interfaces": interfaces}, + "change_quality": {"probes": {"data_upgrade": data_upgrade}}} + scores = iso_trial_scores(trial) + return (scores["Compatibility"]["Interoperability"], + target_met(trial, "change:data_upgrade", AT_LEAST, 1.0)) + kept = reading({"value": 1.0, "missing": None}, upgrade) + broken = reading({"value": 0.0, "missing": None}, + {"passed": False, "lost": "would not open"}) + unread = reading({"value": None, "missing": "no baseline"}, + {"passed": None, "missing": "no fixture"}) + gated = reading({"value": 1.0, "missing": None}, upgrade, install=False) + checks.append(("a change kept, broken, lost or unread reads met, not " + "met, not met and not measured", + kept == (1.0, True) and broken == (0.0, False) + and unread == (None, None))) + checks.append(("a named round's change targets read whatever its build " + "did", gated == (1.0, True))) + return checks + + def change_only_checks(): """A named round's change task is read whether or not its build trial was scored or reached, on rows of its own; a pilot round's keeps @@ -6189,10 +6296,11 @@ def radar_panels(table, results, active): # bare arm. Safety, the ninth characteristic, does not apply to this backend. # Each sub-characteristic lists its targets as (what it asks, where the value # comes from, the pass condition): a metric row by its key, a security probe -# by `probe:`, a quality probe by `quality:`, or a hidden-suite -# module by `suite:`. A target is met, not met, or not measured, and a -# sub-characteristic with no target reads not measured, never 0 %. This is -# round 6's table; a pilot round read by the radar keeps its own, below. +# by `probe:`, a quality probe by `quality:`, a hidden-suite +# module by `suite:`, or a reading of the change task's tree against +# its fixture by `change:`. A target is met, not met, or not measured, +# and a sub-characteristic with no target reads not measured, never 0 %. This +# is round 6's table; a pilot round read by the radar keeps its own, below. AT_LEAST, AT_MOST = ">=", "<=" ISO_AXES = ( ("Functionality", ( @@ -6229,9 +6337,11 @@ def radar_panels(table, results, active): ("two instances side by side keep their data and files apart", "quality:coexistence", AT_LEAST, 1.0),)), - # The changed tree's targets join here once the change task's tree - # is scored: the data an earlier build saved still reads. - ("Interoperability", ()), + # The change task's tree is read here against its fixture: what the + # fixture exposed to other software still answers as it did. + ("Interoperability", ( + ("the change keeps every interface its fixture passed", + "change:interfaces", AT_LEAST, 1.0),)), )), ("Usability", ( ("Appropriateness recognisability", ()), @@ -6347,12 +6457,14 @@ def radar_panels(table, results, active): )), ("Flexibility", ( - # The changed tree's targets join here too once it is scored: a - # schema change shipped as a migration, the database named by - # configuration. + # The changed tree adapts to the database its fixture saved: its + # schema change applied to the old file, nothing lost. The data + # upgrade is read here alone, never on Interoperability too. ("Adaptability", ( ("the build installs and serves a signed-in page on a second " - "Python", "quality:python_portability", AT_LEAST, 1.0),)), + "Python", "quality:python_portability", AT_LEAST, 1.0), + ("the changed tree opens its fixture's database, nothing lost", + "change:data_upgrade", AT_LEAST, 1.0),)), ("Scalability", ()), ("Installability", ( ("pip install . succeeds in a clean environment", "install", @@ -6406,8 +6518,10 @@ def radar_panels(table, results, active): ("the hidden suite passes at 98 % or more", "task_success", AT_LEAST, 0.98),) -# The sources round 6 added; a pilot round's draft reads none of them. -ROUND6_SOURCES = ("quality:", "suite:") +# The sources round 6 added; a pilot round's draft reads none of them. A +# change-task target, `change:`, reads the change task's own readings. +CHANGE_SOURCE = "change:" +ROUND6_SOURCES = ("quality:", "suite:", CHANGE_SOURCE) def pilot_axes(): @@ -6484,6 +6598,8 @@ def iso_value(trial, source): return quality_value(trial, source[len("quality:"):]) if source.startswith("suite:"): return module_value(trial, source[len("suite:"):]) + if source.startswith(CHANGE_SOURCE): + return change_target_value(trial, source[len(CHANGE_SOURCE):]) if source in ISO_EXTRA: accessor = ISO_EXTRA[source] else: @@ -6497,6 +6613,18 @@ def iso_value(trial, source): return None +def change_target_value(trial, name): + """A change-task target's value: the interfaces reading of the change + score, or the data upgrade of the change task's quality reading; None + where not measured.""" + if name == "interfaces": + return change_value(trial, "interfaces") + if name == "data_upgrade": + return quality_value({"quality": trial.get("change_quality")}, + "data_upgrade") + return None + + def target_met(trial, source, condition, threshold): """Whether one trial meets a target: True, False, or None where its value was not measured or its threshold is not registered yet.""" @@ -6536,7 +6664,8 @@ def iso_trial_scores(trial, withdrawn=(), axes=ISO_AXES): met = [target_met(trial, source, condition, threshold) for _, source, condition, threshold in targets if source not in withdrawn - and not (gated and source not in CHANGE)] + and not (gated and source not in CHANGE + and not source.startswith(CHANGE_SOURCE))] measured = [outcome for outcome in met if outcome is not None] per_sub[sub] = (sum(measured) / len(measured) if measured else None) @@ -8349,15 +8478,17 @@ def planted(install=True, probes=None, **scores): "rules file." in words, words[:8])) # Every target reads a metric row, a probe security.py or quality.py - # runs, a hidden-suite module, or a reading of the radar's own; a target - # pointed elsewhere would read not measured for every trial without - # failing. + # runs, a hidden-suite module, the change score's interfaces or a probe + # of the change task's quality reading, or a reading of the radar's own; + # a target pointed elsewhere would read not measured for every trial + # without failing. import quality import security readers = {"probe:": set(security.SECURITY_PROBES + security.DATA_PROTECTION_PROBES), "quality:": set(quality.PROBES), - "suite:": set(HIDDEN_MODULES)} + "suite:": set(HIDDEN_MODULES), + CHANGE_SOURCE: {"interfaces"} | set(quality.CHANGE_PROBES)} keys = {key for key, _, _, _ in METRICS} | set(ISO_EXTRA) def reads(source): @@ -8533,7 +8664,7 @@ def read(axes): lines = iso_axis_lines(run, table, ["none", "hybrid"]) thin = [line for line in lines if line.startswith("| Installability |")] empty = [line for line in lines - if line.startswith("| Interoperability |")] + if line.startswith("| Scalability |")] checks.append(("the tables mark a thin sub-characteristic and read an " "empty one as not measured", len(thin) == 1 and "(fewer than 3 targets)" in thin[0] @@ -9016,6 +9147,7 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in python_checks()) checks.extend((label, ok, ok) for label, ok in round_identity_checks()) checks.extend((label, ok, ok) for label, ok in change_only_checks()) + checks.extend((label, ok, ok) for label, ok in change_reading_checks()) for label, ok, got in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) diff --git a/tests/efficacy/reuse.py b/tests/efficacy/reuse.py index a09a3b0..94c151c 100644 --- a/tests/efficacy/reuse.py +++ b/tests/efficacy/reuse.py @@ -25,13 +25,16 @@ import lib # noqa: E402 from harness import (ARMS, PROMPT, REGISTRATIONS, TrialError, # noqa: E402 assert_outside_repository, canonical, identity_problem, - now, project_folder, recorded_round, + now, project_folder, read_change_prompt, recorded_round, registration_digest, remove_tree, scorable_trials, - scoring_area, write_run) + scoring_area, task_folder, write_run) # The scoring area's per-trial readings, each a JSON file named for the -# trial, that a reused trial brings with it. -READINGS = ("scores", "security-scores", "quality-scores") +# trial, that a reused trial brings with it; a reused change task brings the +# same readings of its own, from beside the build's. +KINDS = ("scores", "security-scores", "quality-scores") +READINGS = KINDS +CHANGE_READINGS = tuple(task_folder(kind, "change") for kind in KINDS) def existing_file(directory, name): @@ -69,10 +72,12 @@ def annotated(source, target, updates): json.dump(data, handle, indent=2, sort_keys=True) -def judgings_of(area, name): - """Every completed judging of a trial in a scoring area, by file.""" +def judgings_of(area, name, task="build"): + """Every completed judging of a trial's `task` in a scoring area, by + file.""" found = {} - for file in sorted(glob.glob(os.path.join(area, "judge", "T*.json"))): + for file in sorted(glob.glob(os.path.join(area, task_folder("judge", task), + "T*.json"))): with io.open(file, encoding="utf-8") as handle: record = json.load(handle) try: @@ -84,9 +89,10 @@ def judgings_of(area, name): return found -def reuse_trial(name, record, source, target, identity=None): - """Copy one trial's artifacts into the target root and scoring area; - `identity` names the round and registration it ran under, if named. +def reuse_trial(name, record, source, target, identity=None, task="build"): + """Copy one trial's artifacts of `task` into the target root and scoring + area; `identity` names the round and registration it ran under, if + named. Returns the run record to write for it and the blind label its judging carries, None where it was never judged. @@ -109,8 +115,9 @@ def reuse_trial(name, record, source, target, identity=None): copied = dict(record) copied["reused_from"] = origin + frozen = name if task == "build" else "change-%s" % name copied["frozen"] = dict(record["frozen"], - tarball=os.path.join(target, "%s.tar" % name)) + tarball=os.path.join(target, "%s.tar" % frozen)) copy_file(tarball, copied["frozen"]["tarball"]) # The transcripts, filed under the workspace the trial ran in, which the @@ -127,32 +134,33 @@ def reuse_trial(name, record, source, target, identity=None): from_area, to_area = scoring_area(source), scoring_area(target) updates = {"name": name, "arm": copied["arm"], "reused_from": origin} - for kind in READINGS: + for kind in READINGS if task == "build" else CHANGE_READINGS: found = existing_file(os.path.join(from_area, kind), name) if found: annotated(found, os.path.join(to_area, kind, "%s.json" % name), updates) label = None - for file, judging in judgings_of(from_area, name).items(): + for file, judging in judgings_of(from_area, name, task).items(): label = judging.get("blind_id") - annotated(file, os.path.join(to_area, "judge", + annotated(file, os.path.join(to_area, task_folder("judge", task), os.path.basename(file)), {"trial": name, "reused_from": origin}) return copied, label -def read_map(area): - """The scoring area's unblinding map, empty where there is none.""" - path = os.path.join(area, "judge", "map.json") +def read_map(area, task="build"): + """The scoring area's unblinding map of `task`, empty where there is + none.""" + path = os.path.join(area, task_folder("judge", task), "map.json") if not os.path.isfile(path): return {"blind": {}} with io.open(path, encoding="utf-8") as handle: return json.load(handle) -def write_map(area, mapping): - path = os.path.join(area, "judge", "map.json") +def write_map(area, mapping, task="build"): + path = os.path.join(area, task_folder("judge", task), "map.json") os.makedirs(os.path.dirname(path), exist_ok=True) with io.open(path, "w", encoding="utf-8") as handle: json.dump(mapping, handle, indent=2, sort_keys=True) @@ -190,6 +198,15 @@ def reuse(source, target, arms): clash = sorted(set(chosen) & set(held)) if clash: raise TrialError("%s already offers %s" % (target, ", ".join(clash))) + changes, fixtures = change_tasks(source, arms) + try: + held = scorable_trials(target, task="change") + except TrialError: + held = {} + clash = sorted(set(changes) & set(held)) + if clash: + raise TrialError("%s already offers the change tasks of %s" + % (target, ", ".join(clash))) # One ruler for both rounds: the earlier round's tool lock goes with its # trials, and a target already holding a different one is another run. @@ -208,14 +225,38 @@ def reuse(source, target, arms): else: copy_file(from_lock, to_lock) - mapping = read_map(scoring_area(target)) + started_at = now() + os.makedirs(target, exist_ok=True) + stamp = started_at.strftime("%Y-%m-%dT%H-%M-%S") + run_file = os.path.join(target, "run-%s-reused.json" % stamp) + records = copy_trials(chosen, source, target, identity, "build") + write_run(run_file, started_at, records, "build", PROMPT, + identity=identity) + + # A change task comes with its arm's build trials, in a run record of its + # own; a named round's names the fixtures its change runs took. + if changes: + change_identity = identity + if identity and fixtures: + change_identity = dict(identity, fixtures=fixtures) + records = copy_trials(changes, source, target, identity, "change") + write_run(os.path.join(target, "run-%s-reused-change.json" % stamp), + started_at, records, "change", read_change_prompt(), + identity=change_identity) + return sorted(chosen), run_file + + +def copy_trials(chosen, source, target, identity, task): + """Copy each chosen trial of `task` with its labels; return the run + records to write for them.""" + mapping = read_map(scoring_area(target), task) if "seed" not in mapping: - mapping["seed"] = read_map(scoring_area(source)).get("seed") + mapping["seed"] = read_map(scoring_area(source), task).get("seed") taken = {label: name for name, label in mapping["blind"].items()} records, labels = [], {} for name in sorted(chosen): copied, label = reuse_trial(name, chosen[name], source, target, - identity) + identity, task) records.append(copied) if label: if label in taken and taken[label] != name: @@ -224,18 +265,27 @@ def reuse(source, target, arms): labels[name] = label mapping["blind"].update(labels) if labels: - write_map(scoring_area(target), mapping) + write_map(scoring_area(target), mapping, task) + return records - started_at = now() - os.makedirs(target, exist_ok=True) - run_file = os.path.join(target, "run-%s-reused.json" - % started_at.strftime("%Y-%m-%dT%H-%M-%S")) - write_run(run_file, started_at, records, "build", PROMPT, - identity=identity) - return sorted(chosen), run_file +def change_tasks(source, arms): + """The earlier root's scorable change tasks of the given arms, by name, + and the fixtures its change runs took; none where it ran none.""" + chosen = {name: record for name, record + in scorable_trials(source, task="change").items() + if record.get("arm") in arms} + fixtures = None + for file in sorted(glob.glob(os.path.join(source, "run-*.json"))): + with io.open(file, encoding="utf-8") as handle: + run = json.load(handle) + if run.get("task") == "change" and run.get("fixtures"): + fixtures = run["fixtures"] + break + return chosen, fixtures -def plant_source(scratch, name="earlier", identity=None): + +def plant_source(scratch, name="earlier", identity=None, changes=False): """A source root of an earlier round: one trial per arm, each scored, judged and read for security, with a transcript and a lock; a named round's where `identity` names one.""" @@ -281,9 +331,76 @@ def plant_source(scratch, name="earlier", identity=None): with io.open(os.path.join(area, "tool-lock.txt"), "w", encoding="utf-8") as handle: handle.write("ruler==1.0\n") + if changes: + plant_changes(source, identity) return source +def plant_changes(source, identity): + """A change task of arms none and inline in `source`, each scored, read + for security and quality and judged, in a change run of its own.""" + area = scoring_area(source) + records = [] + for arm in ("none", "inline"): + name = "%s-1" % arm + tarball = os.path.join(source, "change-%s.tar" % name) + with io.open(tarball, "wb") as handle: + handle.write(b"changed " + name.encode()) + records.append({"arm": arm, "trial": 1, "task": "change", + "outcome": "completed", + "frozen": {"head": "def", "tarball": tarball}}) + for kind in CHANGE_READINGS: + os.makedirs(os.path.join(area, kind), exist_ok=True) + with io.open(os.path.join(area, kind, "%s.json" % name), "w", + encoding="utf-8") as handle: + json.dump({"name": name, "arm": arm, "trial": 1}, handle) + header = (dict(identity, fixtures={"manifest_sha256": "f" * 64}) + if identity else None) + write_run(os.path.join(source, "run-planted-change.json"), + datetime.datetime(2026, 9, 16, 12, 0, 0), records, "change", + read_change_prompt(), identity=header) + os.makedirs(os.path.join(area, "judge-change")) + with io.open(os.path.join(area, "judge-change", "T1.json"), "w", + encoding="utf-8") as handle: + json.dump({"trial": "inline-1", "blind_id": "T1", + "outcome": "judged", "answer": {"rubric": {}}}, handle) + write_map(area, {"seed": 1, "blind": {"inline-1": "T1"}}, "change") + + +def change_checks(scratch): + """A change task comes with its arm's build trials, with every reading + and judging of its own, in a change run naming its round's fixtures.""" + digest = registration_digest(REGISTRATIONS["C1"]) + identity = {"round": "C1", "registration": digest} + source = plant_source(scratch, "changed", identity, changes=True) + target = os.path.join(scratch, "changed-later") + area = scoring_area(target) + reuse(source, target, ["inline", "hand"]) + runs = [os.path.join(target, entry) for entry in os.listdir(target) + if entry.endswith("-reused-change.json")] + with io.open(runs[0] if runs else os.devnull, encoding="utf-8") as handle: + header = json.load(handle) if runs else {} + copied = [os.path.join(area, kind, "inline-1.json") + for kind in CHANGE_READINGS] + return [ + ("a change task comes with its arm's build trials, in a change run " + "naming its round's fixtures", + len(runs) == 1 and header.get("task") == "change" + and header.get("round") == "C1" + and header.get("fixtures") == {"manifest_sha256": "f" * 64} + and sorted(scorable_trials(target, task="change")) == ["inline-1"] + and os.path.isfile(os.path.join(target, "change-inline-1.tar"))), + ("a change task's score, security and quality readings and " + "judgings come along under their own folders", + all(os.path.isfile(path) for path in copied) + and not os.path.exists(os.path.join(area, "scores-change", + "none-1.json")) + and os.path.isfile(os.path.join(area, "judge-change", "T1.json")) + and read_map(area, "change")["blind"] == {"inline-1": "T1"} + and read_map(area)["blind"] == {"inline-1": "T2", "hand-1": "T1"}), + ] + + def self_test(): """Prove a reuse copies the chosen arms' trials, and only those, under the words, and refuses to offer a trial twice.""" @@ -393,6 +510,7 @@ def loaded(*parts): joined.append(os.path.exists(os.path.join(into, "none-1.tar"))) checks.append(("a reuse never mixes a named round's trials with others", joined == [False, False])) + checks += change_checks(scratch) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) diff --git a/tests/efficacy/score.py b/tests/efficacy/score.py index 94071d8..71a3d45 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -38,10 +38,10 @@ import lib # noqa: E402 import probes # noqa: E402 -from harness import (SCORABLE, LiveRunError, TrialError, # noqa: E402 - canonical, claim_area, claim_refusal_check, +from harness import (INTERFACE_MODULES, SCORABLE, LiveRunError, # noqa: E402 + TrialError, canonical, claim_area, claim_refusal_check, frozen_top, name_of, release_area, remove_tree, - scorable_trials, scoring_area) + scorable_trials, scoring_area, task_folder) HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPT = os.path.basename(__file__) @@ -1235,7 +1235,19 @@ def score_trial(record, options, suite, lock): raise ScoreError("%s; score with --no-web to accept the skips" % refusal) scores["hidden_suite"] = run_hidden_suite(venv, suite, workspace, "build") + measure_code(scores, venv, workspace, options, lock, source) + scores["scope"] = scope(workspace, roots) + scores["cost"] = cost(record) + + scores["flagged"] = metric_flags(scores) + drop_venv(venv) + return scores + +def measure_code(scores, venv, workspace, options, lock, source): + """The static battery, the structure and web probes and adherence, read + into `scores` from the installed tree once its suites have run.""" + roots, seen = scores["discovery"]["roots"], scores["seen"] scores["battery"] = install_battery(venv, lock) # Again after the battery, which installs the lock's own Playwright over @@ -1278,13 +1290,6 @@ def score_trial(record, options, suite, lock): # is read from one of them. scores["adherence"] = adherence(workspace, scores) - scores["scope"] = scope(workspace, roots) - scores["cost"] = cost(record) - - scores["flagged"] = metric_flags(scores) - drop_venv(venv) - return scores - # What churn does not count: environments, caches, build output and the # application's database. Each changes when the agent runs the code rather @@ -1328,28 +1333,43 @@ def churn(workspace, base): invocation=outcome["argv"]) -def score_change_trial(record, options, suite): - """Score one frozen change task: install, both suites, churn and cost.""" +def score_change_trial(record, options, suite, lock): + """Score one frozen change task: everything a build is scored on, both + suites, the interfaces it kept, churn and cost.""" name = name_of(record) frozen = "change-%s" % name # Apart from `scoring/`, whose extracted trees the judge takes for build # trials; a change tree there would be judged as one. - scoring = os.path.join(scoring_area(options.root), "scoring-change", name) + scoring = os.path.join(scoring_area(options.root), + task_folder("scoring", "change"), name) os.makedirs(scoring, exist_ok=True) workspace = extract((record.get("frozen") or {}).get("tarball"), os.path.join(scoring, "tree"), frozen) + files = python_files(workspace) venv = create_venv(os.path.join(scoring, "venv")) + # The fixture is named by its hash and with the readings it qualified + # on, so every reading of the change says what it was read against. scores = {"arm": record["arm"], "trial": record["trial"], "name": name, "task": "change", "workspace": workspace, "base": record.get("base"), "model": record.get("model"), + "fixture": record.get("fixture"), + "templates_tree": record.get("templates_tree"), "suite_revision": suite["revision"], "python": venv_version(venv), "scored_at": datetime.datetime.now().isoformat( - timespec="seconds")} + timespec="seconds"), + "python_files": files} scores["install"] = install_trial(venv, workspace) + source = package_source(venv) + scores["boot"] = boot_check(venv, workspace) + discovery = discover_roots(venv, workspace) + roots = discovery["roots"] + scores["discovery"] = {"roots": roots, "how": discovery["how"], + "installed": discovery["installed"]} + scores["seen"] = count_source(roots) # The build suite re-runs unchanged beside the change suite: a change that # passes its own checks by breaking the application has not scored well. @@ -1364,15 +1384,75 @@ def score_change_trial(record, options, suite): scores["build_suite"] = run_hidden_suite(venv, suite, workspace, "build") scores["change_suite"] = run_hidden_suite(venv, suite, workspace, "change") + scores["interfaces"] = interfaces(scores["build_suite"], + record.get("fixture")) + + # Before the battery, whose tools leave reports and caches in the tree + # that the agent never wrote. scores["churn"] = (churn(workspace, record["base"]) if record.get("base") else absent("the change record names no starting " "commit")) + measure_code(scores, venv, workspace, options, lock, source) + scores["scope"] = scope(workspace, roots) scores["cost"] = cost(record) scores["flagged"] = metric_flags(scores) drop_venv(venv) return scores +def module_whole(report, module): + """Whether a suite report shows a module passed whole: some check + passed and none failed, errored or was skipped; a module it does not + list did not run.""" + counts = ((report or {}).get("modules") or {}).get(module) + if not isinstance(counts, dict): + return False + unproven = sum(counts.get(key) or 0 + for key in ("failed", "error", "skipped")) + return not unproven and bool(counts.get("passed")) + + +def interfaces(build_suite, fixture): + """Whether what the fixture exposed still answers after the change: + 1.0 where every interface module the fixture passed whole passes whole + on the changed tree, 0.0 where one no longer does. + + A module the fixture already failed is inherited, never the change's, + and counts neither way; it is told apart from one the change broke. + """ + baseline = ((fixture or {}).get("baseline") or {}).get("interfaces") + if not isinstance(baseline, dict) or any( + not isinstance(baseline.get(module), bool) + for module in INTERFACE_MODULES): + return absent("the change task names no fixture whose interface " + "modules were frozen") + if build_suite.get("missing"): + return absent("the build suite did not run on the changed tree: %s" + % build_suite["missing"]) + report = build_suite.get("report") + modules = {} + for module in INTERFACE_MODULES: + before, after = baseline[module], module_whole(report, module) + verdict = ({(True, True): "kept", (True, False): "broken", + (False, True): "repaired", (False, False): "inherited"} + [(before, after)]) + modules[module] = {"fixture": before, "changed": after, + "verdict": verdict} + held = [module for module in INTERFACE_MODULES if baseline[module]] + broken = [module for module in held + if modules[module]["verdict"] == "broken"] + inherited = [module for module in INTERFACE_MODULES + if modules[module]["verdict"] == "inherited"] + fixture_name = (fixture or {}).get("trial") + if not held: + return absent("the fixture passed none of the interface modules " + "whole, so the change had none to keep", + modules=modules, inherited=inherited, + fixture=fixture_name) + return measured(0.0 if broken else 1.0, modules=modules, broken=broken, + inherited=inherited, fixture=fixture_name) + + PLANTED_MODULE = '''"""A plausible module, so the battery has something to read.""" @@ -1687,6 +1767,97 @@ def security_checks(scratch): owed == ["hand-1", "none-1"])] +def interface_checks(): + """The interfaces reading: kept, broken, inherited and repaired told + apart, and missing where there is nothing to read it against.""" + def suite(failing=(), skipped=(), absent_modules=()): + modules = {module: {"passed": 3, "failed": 1 if module in failing + else 0, "skipped": 1 if module in skipped else 0} + for module in INTERFACE_MODULES + if module not in absent_modules} + return measured(1.0, report={"modules": modules}) + + def fixture(failed=()): + return {"trial": "none-2", "sha256": "0" * 64, "baseline": { + "interfaces": {module: module not in failed + for module in INTERFACE_MODULES}}} + + api, routes = INTERFACE_MODULES[0], INTERFACE_MODULES[1] + kept = interfaces(suite(), fixture()) + broken = interfaces(suite(failing=[routes]), fixture()) + skipped = interfaces(suite(skipped=[routes]), fixture()) + unrun = interfaces(suite(absent_modules=[routes]), fixture()) + inherited = interfaces(suite(failing=[api]), fixture(failed=[api])) + repaired = interfaces(suite(), fixture(failed=[api])) + none_held = interfaces(suite(), fixture(failed=INTERFACE_MODULES)) + return [ + ("a change keeping every interface the fixture passed reads 1", + kept["value"] == 1.0 and not kept["broken"]), + ("an interface module the change broke reads 0 and is named", + broken["value"] == 0.0 and broken["broken"] == [routes] + and broken["modules"][routes]["verdict"] == "broken"), + ("a skipped or unrun interface module is not kept", + skipped["value"] == 0.0 and unrun["value"] == 0.0), + ("a module the fixture already failed is inherited, not the change's", + inherited["value"] == 1.0 and inherited["inherited"] == [api] + and inherited["modules"][api]["verdict"] == "inherited"), + ("a module the change repaired reads repaired", + repaired["value"] == 1.0 + and repaired["modules"][api]["verdict"] == "repaired"), + ("interfaces read missing with no frozen baseline, no build suite, " + "or none the fixture passed", + interfaces(suite(), None)["missing"] is not None + and interfaces(suite(), {"baseline": {}})["missing"] is not None + and interfaces(absent("no grader"), fixture())["missing"] + is not None + and none_held["value"] is None and none_held["missing"]), + ] + + +def change_breadth_checks(scratch): + """A change task is scored on every reading a build is, with its own + suites and churn in place of the build's one suite.""" + import argparse as _argparse + stubs = { + "extract": lambda tarball, into, name: os.path.join(into, name), + "python_files": lambda workspace: [], + "create_venv": lambda where: where, + "venv_version": lambda venv: "3.12.0", + "install_trial": lambda venv, workspace: measured(True), + "package_source": lambda venv: "site", + "boot_check": lambda venv, workspace: measured(True), + "discover_roots": lambda venv, workspace: { + "roots": [], "how": "stub", "installed": None}, + "count_source": lambda roots: {"files": 0, "lines": 0}, + "pip": lambda venv, *args, **kwargs: None, + "run_hidden_suite": lambda venv, suite, workspace, which: measured( + 1.0, report={"modules": {}}), + "install_battery": lambda venv, lock: {"missing": "stubbed"}, + "package_moved": lambda before, after: None, + "adherence": lambda workspace, scores: measured(1.0), + "scope": lambda workspace, roots: measured({}), + "churn": lambda workspace, base: measured({}), + "drop_venv": lambda venv: None, + } + saved = {name: globals()[name] for name in stubs} + record = {"arm": "none", "trial": 1, "base": "abc", "frozen": { + "tarball": "none-1.tar"}, "fixture": None} + options = _argparse.Namespace(root=os.path.join(scratch, "breadth"), + web=False) + suite = {"revision": "stub", "path": scratch} + globals().update(stubs) + try: + build = score_trial(record, options, suite, "lock") + change = score_change_trial(record, options, suite, "lock") + finally: + globals().update(saved) + owed = set(build) - {"hidden_suite"} + return [("a changed tree is scored on every reading a build is", + owed <= set(change) + and {"build_suite", "change_suite", "interfaces", + "churn"} <= set(change))] + + PLANTED_SEEDING_APP = '''\ import os @@ -2068,7 +2239,8 @@ def self_test(): + coverage_checks(scratch) + ruler_checks(scratch) + adherence_checks(scratch) + python_files_checks(scratch) - + scope_checks(scratch) + revision_checks(scratch)) + + scope_checks(scratch) + revision_checks(scratch) + + interface_checks() + change_breadth_checks(scratch)) dropped = create_venv(os.path.join(scratch, "dropped")) drop_venv(dropped) checks.append(("a scored trial's environment is dropped", @@ -2203,11 +2375,11 @@ def rate(key): flagged = len(scores.get("flagged") or []) if scores.get("task") == "change": changed = (scores.get("churn") or {}).get("value") or {} - return ("change suite %s, build suite %s, %s file(s) and %s line(s) " - "changed, %d metric(s) flagged" + return ("change suite %s, build suite %s, interfaces kept %s, %s " + "file(s) and %s line(s) changed, %d metric(s) flagged" % (rate("change_suite"), rate("build_suite"), - changed.get("files", "?"), changed.get("lines", "?"), - flagged)) + rate("interfaces"), changed.get("files", "?"), + changed.get("lines", "?"), flagged)) return "suite %s, %d metric(s) flagged" % (rate("hidden_suite"), flagged) @@ -2253,8 +2425,7 @@ def score_trials(options): # trial, and one must never overwrite the other. area = scoring_area(options.root) lock = os.path.join(area, "tool-lock.txt") - target = os.path.join(area, "scores" if options.task == "build" - else "scores-change") + target = os.path.join(area, task_folder("scores", options.task)) try: wanted = {canonical(name) for name in options.trial} except TrialError as error: @@ -2297,7 +2468,7 @@ def score_trials(options): print("%s scoring the %s task" % (name, options.task)) try: if options.task == "change": - scores = score_change_trial(record, options, suite) + scores = score_change_trial(record, options, suite, lock) else: scores = score_trial(record, options, suite, lock) except ScoreError as error: @@ -2311,17 +2482,17 @@ def score_trials(options): print(" %s" % summary(scores)) scored.append(name) - # The probe pass rates are primary, so a build scoring files them rather - # than leaving them to a second command someone must remember. - owed = [] - if options.task == "build": - owed = security_owed(os.path.join(area, "security-scores"), - scored + skipped, scored) + # The probe pass rates are primary, so scoring files them rather than + # leaving them to a second command someone must remember; a change task's + # go beside its own scores, as the build's do. + owed = security_owed(os.path.join(area, task_folder("security-scores", + options.task)), + scored + skipped, scored) if owed: # Imported here, because security.py imports this module. import security security.file_readings(area, {name: existing_score(target, name) - for name in owed}, owed) + for name in owed}, owed, options.task) done = bool(scored or skipped) lib.print_verdict(refused == 0 and done, diff --git a/tests/efficacy/security.py b/tests/efficacy/security.py index 9250b7a..0aeed4c 100644 --- a/tests/efficacy/security.py +++ b/tests/efficacy/security.py @@ -28,7 +28,7 @@ import lib # noqa: E402 from harness import (LiveRunError, canonical, claim_area, # noqa: E402 claim_refusal_check, release_area, remove_tree, - scoring_area) + scoring_area, task_folder) from score import (absent, create_venv, lock_lines, measured, pip, # noqa: E402 python_in, run, script_in) @@ -1037,8 +1037,10 @@ def audit_dependencies(venv, where, auditor): return audit_metric(outcome["stdout"] or outcome["stderr"], audited_at) -def read_trial(area, name, scores_file, auditor, auditor_reason): - """Every security check on one scored trial, read from its score file.""" +def read_trial(area, name, scores_file, auditor, auditor_reason, + task="build"): + """Every security check on one scored trial of `task`, read from its + score file.""" with io.open(scores_file, encoding="utf-8") as handle: scores = json.load(handle) roots = (scores.get("discovery") or {}).get("roots") or [] @@ -1048,7 +1050,7 @@ def read_trial(area, name, scores_file, auditor, auditor_reason): timespec="seconds"), "auditor": PIP_AUDIT, "roots": roots} result.update(static_checks(roots)) - where = os.path.join(area, "security", name) + where = os.path.join(area, task_folder("security", task), name) os.makedirs(where, exist_ok=True) venv = create_venv(os.path.join(where, "venv")) try: @@ -1551,11 +1553,43 @@ def leftover_self_checks(scratch): scores_file = os.path.join(area, "none-1.json") with io.open(scores_file, "w", encoding="utf-8") as handle: json.dump({"workspace": tree, "discovery": {"roots": []}}, handle) + def lost(reading): + return sorted(name for name, probe in reading["probes"].items() + if probe.get("lost")) + result = read_trial(area, "none-1", scores_file, None, "not planted") + changed = read_trial(area, "none-1", scores_file, None, "not planted", + "change") return [("a reading's environment is gone once it is read", "probes" in result and not os.path.exists(os.path.join(area, "security", "none-1", - "venv")))] + "venv"))), + ("a changed tree that does not install loses its probes, as a " + "build's does", + lost(changed) and lost(changed) == lost(result) + and os.path.isdir(os.path.join(area, "security-change", + "none-1")) + and not os.path.exists(os.path.join(area, "security-change", + "none-1", "venv")))] + + +def task_self_checks(scratch): + """A change task is read from its own scores into its own folder, never + from or into the build's.""" + area = os.path.join(scratch, "tasks") + for kind, name in (("scores", "none-1"), ("scores-change", "inline-2")): + os.makedirs(os.path.join(area, kind)) + with io.open(os.path.join(area, kind, "%s.json" % name), "w", + encoding="utf-8") as handle: + handle.write("{}") + return [("a change task is read from its own scores into " + "security-scores-change", + sorted(scored_trials(area, "change")) == ["inline-2"] + and sorted(scored_trials(area, "build")) == ["none-1"] + and readings_folder(area, "change") + == os.path.join(area, "security-scores-change") + and readings_folder(area, "build") + == os.path.join(area, "security-scores"))] def self_test(): @@ -1566,7 +1600,7 @@ def self_test(): os.makedirs(scratch) checks = (static_self_checks(scratch) + runtime_self_checks(scratch) + audit_self_checks() + claim_self_checks(scratch) - + leftover_self_checks(scratch)) + + leftover_self_checks(scratch) + task_self_checks(scratch)) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) remove_tree(scratch) @@ -1591,6 +1625,10 @@ def parse_args(argv): parser.add_argument("--reread", action="store_true", help="read a trial already read; by default such a " "trial is skipped") + parser.add_argument("--task", choices=("build", "change"), + default="build", + help="read the build trials' trees, or the trees the " + "change tasks left") parser.add_argument("--self-test", action="store_true", help="prove every check against planted trees; read " "no trial") @@ -1605,20 +1643,14 @@ def main(argv): print("--root is required unless --self-test is given") return 2 - # A score is filed under its trial's name, read as the arms spell it. area = scoring_area(options.root) - scores = os.path.join(area, "scores") - scored = {canonical(os.path.splitext(entry)[0]): - os.path.join(scores, entry) - for entry in (sorted(os.listdir(scores)) - if os.path.isdir(scores) else []) - if entry.endswith(".json")} + scored = scored_trials(area, options.task) wanted = (sorted(canonical(name) for name in options.trial) if options.trial else sorted(scored)) missing = [name for name in wanted if name not in scored] if not scored or missing: - print("no build score for %s under %s; score.py writes them" - % (", ".join(missing) or "any trial", area)) + print("no %s score for %s under %s; score.py writes them" + % (options.task, ", ".join(missing) or "any trial", area)) return 2 # A run clears each trial's environment before rebuilding it, so a second @@ -1639,7 +1671,7 @@ def read_trials(options, area, scored, wanted): # A trial already read keeps its reading, as a reused trial from an # earlier round does; the checks were declared after that round. - target = os.path.join(area, "security-scores") + target = readings_folder(area, options.task) done = [] if not options.reread: for name in wanted: @@ -1654,21 +1686,36 @@ def read_trials(options, area, scored, wanted): % len(done)) return 0 - file_readings(area, scored, wanted) + file_readings(area, scored, wanted, options.task) lib.print_verdict(True, "%d trial(s) read, %d already read" % (len(wanted), len(done))) return 0 -def file_readings(area, scored, names): - """Read each named trial from its score file and file the reading under - `security-scores/`, overwriting any earlier one.""" - target = os.path.join(area, "security-scores") +def scored_trials(area, task): + """Every score of `task` in the scoring area, by the trial's name as the + arms spell it.""" + scores = os.path.join(area, task_folder("scores", task)) + return {canonical(os.path.splitext(entry)[0]): os.path.join(scores, entry) + for entry in (sorted(os.listdir(scores)) + if os.path.isdir(scores) else []) + if entry.endswith(".json")} + + +def readings_folder(area, task): + """Where the security readings of `task` are filed.""" + return os.path.join(area, task_folder("security-scores", task)) + + +def file_readings(area, scored, names, task="build"): + """Read each named trial of `task` from its score file and file the + reading beside the task's scores, overwriting any earlier one.""" + target = readings_folder(area, task) auditor, reason = install_auditor(os.path.join(area, "security", "tools")) os.makedirs(target, exist_ok=True) for name in names: print("%s reading for security" % name) - result = read_trial(area, name, scored[name], auditor, reason) + result = read_trial(area, name, scored[name], auditor, reason, task) with io.open(os.path.join(target, "%s.json" % name), "w", encoding="utf-8") as handle: json.dump(result, handle, indent=2, sort_keys=True) From c86d9a76aac55804ba493cc84b758b83f4461f82 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:51:11 +0200 Subject: [PATCH 02/18] feat(efficacy): the data upgrade re-saves an old invoice before new rows - the upgrade posted a new percentage rule and then re-saved the first old invoice, so its own rule repriced it: reference-change read failed - the old invoice is now saved again first, then the new records - the stand-in prices percentage rules, so the old order fails its sound upgrade check Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/quality.py | 46 ++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 380bc20..847680a 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1115,18 +1115,8 @@ def data_upgrade(seeded): % place) # The new schema has to take new rows on the old file too, not only read - # the old ones: a column added for new tables alone fails here. - written = {"/jurisdictions": {"code": "U2", "name": "Upgradia Nova", - "default_rate": "0.1", - "rates": "standard=0.1"}, - "/rules": {"rule_id": "u-pct-after", "kind": "percentage", - "sku": "UPG-2", "percent": "3"}} - for path, body in written.items(): - created(path, body) - if body["code" if path == "/jurisdictions" else "rule_id"] \ - not in text_of(page(client, path)): - failures.append("a record posted to %s after the upgrade is not " - "listed" % path) + # the old ones: a column added for new tables alone fails here. The old + # invoice is saved again first, before a new rule can reprice it. saved = saved_page(held(form_post(client, "/invoices/new", "/invoices", seeded["invoices"][0]["body"]), "the save")) @@ -1140,6 +1130,17 @@ def data_upgrade(seeded): failures.append("the first invoice saved again totals %r, not %r" % (total, seeded["invoices"][0]["export"].get( "total"))) + written = (("/jurisdictions", "code", { + "code": "U2", "name": "Upgradia Nova", "default_rate": "0.1", + "rates": "standard=0.1"}), + ("/rules", "rule_id", {"rule_id": "u-pct-after", + "kind": "percentage", "sku": "UPG-2", + "percent": "3"})) + for path, key, body in written: + created(path, body) + if body[key] not in text_of(page(client, path)): + failures.append("a record posted to %s after the upgrade is not " + "listed" % path) return passed(not failures, failures=failures[:20]) @@ -2124,22 +2125,23 @@ def priced(self, connection, jurisdiction, coupons, lines): raise LookupError(jurisdiction) rate = decimal.Decimal(found[2]) if VERSION == 2: - caps = json.loads(found[3]) if MODE == "fragile" else ( - json.loads(found[3] or "{}")) - rate = rate if caps is not None else rate + json.loads(found[3] if MODE == "fragile" else found[3] or "{}") + rules = [(kind, sku, json.loads(detail)) for kind, sku, detail + in connection.execute("SELECT kind, sku, detail FROM rules")] net = [] for sku, quantity in lines: price = connection.execute("SELECT unit_price FROM products " "WHERE sku = ?", (sku,)).fetchone() - net.append((sku, quantity, (decimal.Decimal(price[0]) - * quantity).quantize(CENT))) + amount = decimal.Decimal(price[0]) * quantity + for kind, scope, detail in rules: + if kind == "percentage" and scope == sku: + amount -= amount * decimal.Decimal(detail["percent"]) / 100 + net.append((sku, quantity, amount.quantize(CENT))) subtotal = sum((amount for _, _, amount in net), decimal.Decimal("0")) - for kind, detail in connection.execute("SELECT kind, detail FROM " - "rules"): - detail = json.loads(detail) - if kind == "coupon" and detail.get("code") in coupons \\ - and detail.get("amount"): + for kind, _, detail in rules: + if (kind == "coupon" and detail.get("code") in coupons + and detail.get("amount")): subtotal -= decimal.Decimal(detail["amount"]) total = (subtotal * (1 + rate)).quantize(CENT) return net, str(total) From c22bc0522a6cbad23d7a56d2b751535db6c5cfe4 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:02:59 +0200 Subject: [PATCH 03/18] feat(efficacy): a named round's ISO radar and verdicts, once a task - a named round draws the ISO radar and gives each arm's verdict for the build task and for the change task, each against none on the same task - the change radar reads each change task's tree: its score, its build suite as the hidden suite, its own security, quality and judgings - the build radar leaves the change targets to the change task's radar - each task's mean billed cost per trial is shown beside its radar, not scored; the summary, its tables, the plain report and the appendix name the task; aggregate.json keeps each task's reading - pilot rounds draw one radar over their trials as before - FR-16-08, ch. 8 and ADR-024 history Refs #169, #178. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/08-crosscutting-concepts.md | 13 + docs/coverage.md | 1 + .../024-verdicts-read-the-iso-radar.md | 1 + docs/requirements.md | 1 + tests/efficacy/report.py | 373 +++++++++++++++--- 5 files changed, 343 insertions(+), 46 deletions(-) diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 6a1790a..cb8c874 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -677,6 +677,19 @@ FR-12-23, FR-16-06): A pilot round read by the ISO radar keeps the targets it had before round 6, and reads round 6's only when `--round6-targets` asks for them. +**One radar a task** (FR-16-08). A named round draws the ISO radar and gives +each arm's verdict twice, once a task, each against `none` on the same task: + +| Task | Reads | Cost beside it | +| ---- | ----- | -------------- | +| Build | Each build trial's tree; no change target | The build's mean billed cost per trial | +| Change | Each change task's tree, scored in full, with the change targets | The change task's mean billed cost per trial | + +The summary, its tables, the plain report and the appendix name the task +each reads. Neither task's readings stand in for the other's, so a build +that broke says nothing of the change it never started. A pilot round +draws one radar over its trials as they are. + **Each approach in plain words** (FR-12-07): - What it did better and worse than `none`, by radar axis. diff --git a/docs/coverage.md b/docs/coverage.md index 079ec0a..cd7c034 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -243,3 +243,4 @@ when: | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | +| FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes" | diff --git a/docs/decisions/024-verdicts-read-the-iso-radar.md b/docs/decisions/024-verdicts-read-the-iso-radar.md index c9e7026..3366ab5 100644 --- a/docs/decisions/024-verdicts-read-the-iso-radar.md +++ b/docs/decisions/024-verdicts-read-the-iso-radar.md @@ -76,3 +76,4 @@ Every change to this decision, oldest first. `#N` is in this repository. | 2026-11-14 | From round 6 verdicts and the screen read the ISO radar's axes | Round 5e read by the ISO radar showed the radar and the verdict disagreeing; the owner chose the axes | #165 | | 2026-11-15 | Round 6's arms are the scripted ones, whichever screen reads round 5e | A file a model writes changes on every generation; the owner kept only arms a script builds | #167 | | 2026-11-15 | The report is written under this repository's `docs/reports/`, no longer the templates source's `docs/audits/` | The templates repository removes `docs/audits/` (solid-ai-templates#2448), and ADR-025 keeps the reports here | #170 | +| 2026-11-15 | A named round reads the radar and gives each verdict once a task, build and change, each against `none` on the same task, the task's cost beside each | Round 6 reads cost and every ISO axis on each task type | #169, #178 | diff --git a/docs/requirements.md b/docs/requirements.md index bdbf59c..c13dd90 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -256,6 +256,7 @@ | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | +| FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | ## Quality requirements diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 9b73948..cc1b0b2 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -1857,7 +1857,7 @@ def unrecorded_voids(root, sequence, recorded): def write_report(root, trials, table, results, seed, out_dir, - withdrawn=None, cross=None, iso=None, uses=None): + withdrawn=None, cross=None, iso=None, uses=None, tasks=None): """The dated round report, written to `out_dir`. The directory has no default so a shakedown of the writer renders into @@ -1868,7 +1868,8 @@ def write_report(root, trials, table, results, seed, out_dir, `cross` is the other vendor's judge's reading, already applied to `results`. `iso` is the ISO reading, computed here when not given and the round - draws that radar. + draws that radar. `tasks` is a named round's reading of each task, + computed here when not given; the build task's is the radar's `iso`. """ names = ordered(trials) arms = [arm for arm in ARMS if arm in {arm_of(name) for name in names}] @@ -1904,6 +1905,11 @@ def write_report(root, trials, table, results, seed, out_dir, scans = reaches(root) active = active_contrasts(trials) os.makedirs(out_dir, exist_ok=True) + if tasks is None: + tasks = task_readings(trials, seed, withdrawn or {}, + iso[3] if iso else None) + if tasks and tasks[0][0] == "build": + iso = tasks[0][4] if iso is None and iso_rules(trials): iso = iso_reading(trials, seed, withdrawn or {}) if iso: @@ -1912,16 +1918,17 @@ def write_report(root, trials, table, results, seed, out_dir, else: panels = radar_panels(table, results, active) draw = radar_svg - radar = {} - if panels: - for theme in RADAR_THEMES: - image = "%s-radar-%s.svg" % (stem, theme) - with io.open(os.path.join(out_dir, image), "w", encoding="utf-8", - newline="\n") as handle: - handle.write(draw(panels, theme)) - radar[theme] = image + radar = draw_radar(out_dir, "%s-radar" % stem, panels, draw) + + # A named round's every task has a radar of its own, its cost the + # task's: the build's is the one above, the change task's beside it. + drawn = [(reading, radar if reading[0] == "build" else draw_radar( + out_dir, "%s-radar-%s" % (stem, reading[0]), + iso_panels(reading[3], reading[4][0], reading[4][1], + active_contrasts(reading[2])), iso_radar_svg)) + for reading in tasks] lines.extend(executive_section(trials, table, results, withdrawn or {}, - lost, scans, radar, iso)) + lost, scans, radar, iso, drawn)) lines.append("") lines.extend(["## What produced these numbers", ""]) @@ -2068,9 +2075,9 @@ def write_report(root, trials, table, results, seed, out_dir, documents = { record: lines, appendix: appendix_lines(trials, table, results, k, seed, generation, - report, record, iso), + report, record, iso, drawn), report: plain_report_lines(root, trials, table, results, radar, - appendix, k, iso, uses)} + appendix, k, iso, uses, drawn)} for document, text in documents.items(): with io.open(os.path.join(out_dir, document), "w", encoding="utf-8", newline="\n") as handle: @@ -2078,6 +2085,20 @@ def write_report(root, trials, table, results, seed, out_dir, return os.path.join(out_dir, report) +def draw_radar(out_dir, stem, panels, draw): + """Each theme's radar of `panels` written to `out_dir` under `stem`; the + images by theme, none where there is no panel.""" + radar = {} + if panels: + for theme in RADAR_THEMES: + image = "%s-%s.svg" % (stem, theme) + with io.open(os.path.join(out_dir, image), "w", encoding="utf-8", + newline="\n") as handle: + handle.write(draw(panels, theme)) + radar[theme] = image + return radar + + def posthoc_rules_reading(trials, seed, withdrawn=None, check=None): """An earlier round's table and contrasts read by round 5d's rules, with withdrawn metrics blanked and the cross-check's disagreements @@ -2548,10 +2569,11 @@ def sureness_lines(trials, k): def plain_report_lines(root, trials, table, results, radar, appendix, k, - iso=None, uses=None): + iso=None, uses=None, tasks=()): """The report a reader opens: the radars, each approach in plain words, the round's questions answered, and how sure the answers are. `iso` is - the ISO reading where the round draws that radar.""" + the ISO reading where the round draws that radar; `tasks`, a named + round's reading of each task with its images, each read on its own.""" names = ordered(trials) active = active_contrasts(trials) arms = by_cost(table, [pair[0] for pair in active if pair[1] == BARE]) @@ -2568,22 +2590,26 @@ def plain_report_lines(root, trials, table, results, radar, appendix, k, times(runs, [BARE]), BARE, BARE), ""] if iso and is_round5(trials): lines.extend(posthoc_iso_lines(iso)) - if radar: - for theme, image in sorted(radar.items()): - lines.append("![Radar per approach](%s#gh-%s-mode-only)" - % (image, theme)) - lines.append("") - lines.extend([ISO_PLAIN_READING if iso else - "How to read it: the dashed ring is `%s`. A point outside " - "the ring means the approach did better on that axis, " - "inside it means worse. Each axis groups several " - "measurements; the appendix lists them." % BARE, "", - "## Each approach", "", - PLAIN_ISO_VERDICT_RULE if iso else PLAIN_VERDICT_RULE, ""]) - for arm in arms: - lines.extend(plain_arm_lines(trials, table, results, arm, - context_lines(arm), iso)) - lines.append("") + if tasks: + lines.extend(plain_task_lines(tasks, results)) + else: + if radar: + for theme, image in sorted(radar.items()): + lines.append("![Radar per approach](%s#gh-%s-mode-only)" + % (image, theme)) + lines.append("") + lines.extend([ + ISO_PLAIN_READING if iso else + "How to read it: the dashed ring is `%s`. A point outside the " + "ring means the approach did better on that axis, inside it " + "means worse. Each axis groups several measurements; the " + "appendix lists them." % BARE, "", + "## Each approach", "", + PLAIN_ISO_VERDICT_RULE if iso else PLAIN_VERDICT_RULE, ""]) + for arm in arms: + lines.extend(plain_arm_lines(trials, table, results, arm, + context_lines(arm), iso)) + lines.append("") present = {arm_of(name) for name in trials} if later_rules_of(trials): # The latest round's questions are the run's: a round-5e root @@ -2635,6 +2661,30 @@ def plain_report_lines(root, trials, table, results, radar, appendix, k, return lines +def plain_task_lines(tasks, results): + """A named round's radars in plain words, one task at a time: its + images, its cost per trial, and each approach on that task, read + against `none` on the same task.""" + lines = [] + for (_, label, view, table, iso), images in tasks: + arms = by_cost(table, [treatment for treatment, baseline + in active_contrasts(view) if baseline == BARE]) + lines.extend(["## The %s" % label, ""]) + for theme, image in sorted(images.items()): + lines.append("![Radar per approach, %s](%s#gh-%s-mode-only)" + % (label, image, theme)) + lines.extend(["", ISO_PLAIN_READING, "", + task_cost_line(table, arms, label), "", + "Each approach on the %s, against `%s` on the same " + "task. %s" % (label, BARE, PLAIN_ISO_VERDICT_RULE), + ""]) + for arm in arms: + lines.extend(plain_arm_lines(view, table, results, arm, + context_lines(arm), iso)) + lines.append("") + return lines + + def rerun_lines(lost): """What happened to the runs that were stopped, in plain words: those run again, and those still missing.""" @@ -2656,10 +2706,11 @@ def rerun_lines(lost): def appendix_lines(trials, table, results, k, seed, generation, report, - record, iso=None): + record, iso=None, tasks=()): """The technical appendix: what produced the results, the radar's axes row by row, and the verdict vector. `iso` is the ISO reading where the - round draws that radar, whose axes come as tables of sub-scores.""" + round draws that radar, whose axes come as tables of sub-scores; a + named round's `tasks` each get their own tables, named for the task.""" names = ordered(trials) arms = [arm for arm in ARMS if arm in {arm_of(name) for name in names}] active = active_contrasts(trials) @@ -2672,7 +2723,15 @@ def appendix_lines(trials, table, results, k, seed, generation, report, lines.extend([DESCRIPTIVE_NOTE % k, ""]) lines.extend(["## What produced the results", ""]) lines.extend(provenance_lines(trials, names, arms, k, seed, generation)) - if iso: + for (_, label, view, view_table, reading), _ in tasks: + lines.extend(["", "## The %s's radar axes, row by row" % label, "", + ISO_TABLE_READING, ""] + method_lines(reading[1], k) + + [DEGENERATE_NOTE, ""]) + lines.extend(iso_axis_lines(view, reading[0], [BARE] + by_cost( + view_table, [treatment for treatment, baseline + in active_contrasts(view) if baseline == BARE]), + reading[1], reading[2], k, reading[3])) + if iso and not tasks: # The ISO tables show the ISO results, read unpaired across rounds # on their own, so their method is read from them, not from the raw # rows. @@ -2683,7 +2742,7 @@ def appendix_lines(trials, table, results, k, seed, generation, report, [BARE] + by_cost(table, [ pair[0] for pair in against]), iso[1], iso[2], k, iso[3])) - else: + elif not tasks: lines.extend(["", "## The radar's axes, row by row", "", "Each table is one axis of the radar: every " "measurement it groups, each approach's mean, and each " @@ -5596,6 +5655,109 @@ def reading(interfaces, data_upgrade, install=True): return checks +def task_radar_checks(seed): + """A named round draws the ISO radar and gives each arm's verdict once a + task, each against the bare arm on the same task, its cost the task's + own; a pilot round draws one radar over its trials as they are.""" + def reading(value): + return {"value": value, "missing": None} + + def tree(installs, cost, debug): + return {"install": reading(installs), + "boot": reading({"factory": True, "index_status": 200}), + "cost": reading({"cost_usd": cost})}, { + "probes": {"debug": {"passed": debug}}} + + trials = {} + for arm in (BARE, "inline"): + for block in range(1, 6): + build, security = tree(True, 2.0 if arm == BARE else 3.0, True) + change, changed = tree(arm == BARE, 0.5 if arm == BARE else 0.8, + arm == BARE) + change.update(name=trial_name(arm, block), change_suite=reading( + 1.0 if arm == BARE else 0.5)) + trials[trial_name(arm, block)] = { + "round": "C1", "scores": dict(build, name=trial_name( + arm, block)), "judge": None, "judgings": [], + "security": security, "quality": None, "change": change, + "change_security": changed} + tasks = task_readings(trials, seed) + by_task = {task: reading for task, _, _, _, reading in tasks} + tables = {task: table for task, _, _, table, _ in tasks} + name = "inline-%s" % BARE + checks = [ + ("a named round reads the ISO radar once a task, the build's first", + [task for task, _, _, _, _ in tasks] == ["build", "change"]), + ("each task's radar reads that task's trees against `none` on the " + "same task", + arm_mean(by_task["build"][0], "iso:Reliability", "inline") == 100.0 + and arm_mean(by_task["change"][0], "iso:Reliability", + "inline") < 100.0 + and arm_mean(by_task["change"][0], "iso:Reliability", BARE) == 100.0 + and iso_answer(by_task["build"], name) == "No" + and iso_answer(by_task["change"], name) == "Worse"), + ("the change task's radar reads its own security, not the build's", + target_met(task_trials(trials, "change")["inline-1"], + "probe:debug", AT_LEAST, 1.0) is False + and target_met(task_trials(trials, "build")["inline-1"], + "probe:debug", AT_LEAST, 1.0) is True), + ("a named round's build radar leaves the change targets to the " + "change task's", + target_met(task_trials(trials, "build")["inline-1"], + "change_success", AT_LEAST, 0.9) is None + and target_met(task_trials(trials, "change")["inline-1"], + "change_success", AT_LEAST, 0.9) is False), + ("each task's radar shows its own mean billed cost per trial", + "`none` $2.00; `inline` $3.00" in task_cost_line( + tables["build"], ["inline"], "build task") + and "`none` $0.50; `inline` $0.80" in task_cost_line( + tables["change"], ["inline"], "change task")), + ("a pilot round draws one radar, its trials as they are", + task_readings({key: dict(trial, round=None) + for key, trial in trials.items()}, seed) == []), + ] + + # Every task in the report, its radar, verdict and cost named for it. + scratch = tempfile.mkdtemp(prefix="efficacy-report-tasks-") + images = {"light": "radar-light.svg"} + table = collect(trials) + summary = "\n".join(executive_section( + trials, table, contrasts(table, seed), radar=images, + iso=by_task["build"], tasks=[(reading, images) for reading in tasks])) + plain = "\n".join(plain_task_lines( + [(reading, images) for reading in tasks], {})) + drawn = draw_radar(scratch, "stem-radar-change", iso_panels( + tables["change"], by_task["change"][0], by_task["change"][1], + active_contrasts(task_trials(trials, "change"))), iso_radar_svg) + out = os.path.join(scratch, "out") + write_report(os.path.join(scratch, "run"), trials, table, + contrasts(table, seed), seed, out) + written = sorted(os.listdir(out)) + with io.open(os.path.join(out, next(file for file in written + if file.endswith("appendix.md"))), + encoding="utf-8") as handle: + appendix = handle.read() + shutil.rmtree(scratch, ignore_errors=True) + checks.append(( + "a named round's report draws the change task's radar beside the " + "build's and tables each task's axes", + sum(1 for file in written if "-radar-change-" in file) == 2 + and "## The build task's radar axes, row by row" in appendix + and "## The change task's radar axes, row by row" in appendix)) + checks.append(( + "the summary gives a radar, a verdict and a cost for each task, " + "each named", + "## The build task" in summary and "## The change task" in summary + and "| inline | Worse | $0.80 |" in summary + and "| inline | No | $3.00 |" in summary + and "Verdict vs `none`, change task" in summary + and "## Arms against `none`, build task" in summary + and "Mean billed cost per trial on the change task" in plain + and "Each approach on the change task" in plain + and sorted(drawn) == sorted(RADAR_THEMES))) + return checks + + def change_only_checks(): """A named round's change task is read whether or not its build trial was scored or reached, on rows of its own; a pilot round's keeps @@ -6986,7 +7148,7 @@ def iso_rules(trials): def aggregate(seed, trials, table, results, withdrawn, check, iso, - uses=None): + uses=None, tasks=()): """What `aggregate.json` keeps beside the report: every row, contrast and method the documents cite, the ISO reading where the round draws that radar, and each trial's use of its map where the round reads it, @@ -6997,6 +7159,14 @@ def aggregate(seed, trials, table, results, withdrawn, check, iso, if iso: payload["iso"] = {"table": iso[0], "results": iso[1], "withdrawn": list(iso[2])} + + # A named round's every task, its ISO reading and the cost it shows. + if tasks: + payload["iso_tasks"] = { + task: {"table": reading[0], "results": reading[1], + "withdrawn": list(reading[2]), + "cost_usd": table_of["cost_usd"]} + for task, _, _, table_of, reading in tasks} if uses is not None: payload["map_use"] = { name: {"first_write": use["first_write"], @@ -7019,6 +7189,98 @@ def iso_reading(trials, seed, withdrawn=(), axes=None): axes) +# A named round reads the ISO radar once a task: its build trials on the +# build, and each change task's tree on the change, each against the bare +# arm on the same task, so neither task's readings stand in for the other's. +# Each radar shows its own task's mean billed cost per trial, not scored. +TASKS = (("build", "build task"), ("change", "change task")) + + +def build_view(trial): + """A named round's trial as its build alone, its change task left to a + radar of its own.""" + return drop_change(dict(trial)) + + +def change_view(trial): + """A trial as its change task's tree: the change score in place of the + build's, the build suite it ran in place of the hidden suite, and the + change task's own security and quality readings and judgings.""" + change = trial.get("change") or {} + scores = dict(change) + if "build_suite" in change: + scores["hidden_suite"] = change["build_suite"] + judgings = list(trial.get("change_judgings") or []) + return {"scores": scores, "judge": judgings[0] if judgings else None, + "judgings": judgings, "change": change, + "security": trial.get("change_security"), + "quality": trial.get("change_quality"), + "change_quality": trial.get("change_quality"), + "round": trial.get("round"), "task": "change"} + + +def task_trials(trials, task): + """A named round's trials as one task reads them: every build, or every + change task that has a change score.""" + if task == "build": + return {name: build_view(trial) for name, trial in trials.items() + if not trial.get("change_only")} + return {name: change_view(trial) for name, trial in trials.items() + if trial.get("change") is not None} + + +def task_readings(trials, seed, withdrawn=(), axes=None): + """A named round's ISO reading of each task, as (task, label, trials, + metric table, ISO reading); empty for a pilot round, which draws one + radar over its trials as they are.""" + if named_round(trials) is None: + return [] + readings = [] + for task, label in TASKS: + view = task_trials(trials, task) + if view: + readings.append((task, label, view, collect(view), + iso_reading(view, seed, withdrawn, axes))) + return readings + + +def task_cost_line(table, arms, label): + """The mean billed cost per trial of each arm on one task, the bare arm + first; shown beside the task's radar, never scored.""" + cells = [] + for arm in [BARE] + [arm for arm in arms if arm != BARE]: + mean = arm_mean(table, "cost_usd", arm) + cells.append("`%s` %s" % (arm, NOT_MEASURED if mean is None + else "$%.2f" % mean)) + return ("Mean billed cost per trial on the %s, shown and not scored: %s." + % (label, "; ".join(cells))) + + +def task_lines(reading, images): + """One task's radar of a named round: its images, how to read it, the + mean billed cost per trial on the task, its axes as a table and each + arm's verdict against the bare arm on the same task.""" + _, label, view, table, iso = reading + arms = by_cost(table, [treatment for treatment, baseline + in active_contrasts(view) if baseline == BARE]) + lines = ["## The %s" % label, ""] + for theme, image in sorted(images.items()): + lines.append("![ISO radar per arm, %s](%s#gh-%s-mode-only)" + % (label, image, theme)) + lines.extend(["", ISO_READING, "", task_cost_line(table, arms, label), + ""]) + lines.extend(iso_radar_table(iso, arms)) + lines.extend(["", "| Arm | Verdict vs `%s`, %s | Mean billed cost per " + "trial |" % (BARE, label), "| --- | --- | --- |"]) + for arm in [BARE] + arms: + mean = arm_mean(table, "cost_usd", arm) + lines.append("| %s | %s | %s |" % ( + arm, "—" if arm == BARE else iso_answer(iso, "%s-%s" + % (arm, BARE)), + NOT_MEASURED if mean is None else "$%.2f" % mean)) + return lines + + # How the plain report reads the ISO radar, under it. ISO_PLAIN_READING = ( "How to read it: each axis is one quality of the software, from the " @@ -7042,17 +7304,27 @@ def iso_reading(trials, seed, withdrawn=(), axes=None): def executive_section(trials, table, results, withdrawn=None, lost=(), - scans=(), radar=None, iso=None): + scans=(), radar=None, iso=None, tasks=()): """The report's first sections: the summary, a radar per file arm read against no file where `radar` names its two images, light and dark; then the arms against no file: the finding table, one line per file on why it scored so, the reading, the contrasts between files scored, and - the caveats. `iso` is the ISO reading where the round draws that radar. + the caveats. `iso` is the ISO reading where the round draws that radar; + `tasks`, for a named round, holds each task's reading and its images, + and each task gets a radar and a verdict of its own. Like the score, it digests the verdict vector and decides nothing. """ active = active_contrasts(trials) lines = ["## Executive summary", ""] + if tasks: + for reading, images in tasks: + lines.extend(task_lines(reading, images) + [""]) + lines.extend(finding_lines(trials, table, results, active, iso, + tasks[0][0][1])) + lines.extend(["", caveats_line(trials, withdrawn or {}, lost, + scans)]) + return lines if radar: for theme, image in sorted(radar.items()): lines.append("![Radar per arm](%s#gh-%s-mode-only)" @@ -7070,13 +7342,14 @@ def executive_section(trials, table, results, withdrawn=None, lost=(), return lines -def finding_lines(trials, table, results, active, iso=None): +def finding_lines(trials, table, results, active, iso=None, task=None): """The finding table, its why-lines and its reading. With `iso`, each - verdict reads the ISO radar's axes.""" + verdict reads the ISO radar's axes; `task` names the task they read.""" + named = ", %s" % task if task else "" names = ["%s-%s" % (treatment, baseline) for treatment, baseline in active if baseline == BARE] if not names: - return ["## Arms against `%s`" % BARE, "", + return ["## Arms against `%s`%s" % (BARE, named), "", "No file arm has a trial to read against `%s`, which has " "none in this run yet." % BARE] arms = [name.split("-")[0] for name in names] @@ -7087,12 +7360,12 @@ def finding_lines(trials, table, results, active, iso=None): # One row per arm, the bare arm first as the line every other is read # against, then the files from the cheapest to the dearest. ranked = by_cost(table, arms) - lines = ["## Arms against `%s`" % BARE, ""] + lines = ["## Arms against `%s`%s" % (BARE, named), ""] lines.extend(iso_radar_table(iso, ranked) if iso else radar_table(results, ranked)) lines.extend(["", - "| Arm | File | Verdict vs `%s` | %s |" - % (BARE, " | ".join(heading + "| Arm | File | Verdict vs `%s`%s | %s |" + % (BARE, named, " | ".join(heading for heading, _, _ in FINDING_COLUMNS)), "| --- | --- | --- | %s |" % " | ".join("---" for _ in FINDING_COLUMNS)]) @@ -9148,6 +9421,7 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in round_identity_checks()) checks.extend((label, ok, ok) for label, ok in change_only_checks()) checks.extend((label, ok, ok) for label, ok in change_reading_checks()) + checks.extend((label, ok, ok) for label, ok in task_radar_checks(seed)) for label, ok, got in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) @@ -9347,15 +9621,22 @@ def main(argv): iso = (iso_reading(trials, options.seed, withdrawn, iso_axes_of(trials, options.round6_targets)) if iso_rules(trials) or posthoc_iso else None) + + # A named round's radar is read once a task, the build's standing as + # the round's own. + tasks = task_readings(trials, options.seed, withdrawn, + iso[3] if iso else None) + if tasks and tasks[0][0] == "build": + iso = tasks[0][4] uses = map_uses(options.root, trials) if is_round5e(trials) else None target = write_report(options.root, trials, table, results, options.seed, - out_dir, withdrawn, check, iso, uses) + out_dir, withdrawn, check, iso, uses, tasks) with io.open(os.path.join(scoring_area(options.root), aggregate_name(posthoc_iso)), "w", encoding="utf-8") as handle: json.dump(aggregate(options.seed, trials, table, results, withdrawn, - check, iso, uses), handle, indent=2, + check, iso, uses, tasks), handle, indent=2, sort_keys=True) print("Report: %s" % target) From e9b5523a2683dbafc5baade50a7aac3843f36333 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:16:55 +0200 Subject: [PATCH 04/18] feat(efficacy): round C1's registered readings, per task - the check loop: lazyref against lazyrefold, paired by block; kept only where the mean billed cost per trial drops by 10 % or more on each task, its interval beside it, and no ISO axis reads worse on either - an axis is worse only with its whole interval past the margin downward; none flagged reads "no degradation detected under the registered rule" - non-inferior only where every measured axis's lower bound clears minus its margin, an interval crossing it inconclusive; read apart from kept - the section files against lazyref and reference: the same words and the cost, no gate - H7: an on-demand arm delivers on demand only reading fewer templates per trial than reference and non-inferior to it on every measured axis - templates read are counted per task from that task's transcripts, section files included; contrasts take any pair - FR-16-09, FR-16-10 and ch. 8 Refs #169, #178. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/08-crosscutting-concepts.md | 17 + docs/coverage.md | 2 + docs/requirements.md | 2 + tests/efficacy/report.py | 439 +++++++++++++++++- 4 files changed, 448 insertions(+), 12 deletions(-) diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index cb8c874..8f2c670 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -690,6 +690,23 @@ each reads. Neither task's readings stand in for the other's, so a build that broke says nothing of the change it never started. A pilot round draws one radar over its trials as they are. +**Round C1's registered readings** (FR-16-09, FR-16-10). Each pairs two +arms by block on each task, on the ISO axes and on the mean billed cost per +trial: + +| Question | Pair | Answer | +| -------- | ---- | ------ | +| Is the check loop kept? | `lazyref` against `lazyrefold` | Kept where the point estimate of the cost drops by 10 % or more on each task, its interval shown beside it, and no axis reads worse on either | +| Is an axis worse? | Each pair | The whole interval past the margin downward; none flagged reads "no degradation detected under the registered rule" | +| Non-inferior? | Each pair | Every measured axis's lower bound above minus its margin, on each task; an interval crossing the margin is inconclusive | +| Do the section files hold? | `lazysections` against `lazyref` and `reference` | The worse and non-inferior readings, with the cost; no gate | +| Does an arm deliver on demand? | `lazyref`, `lazyskills`, `lazysections` against `reference` | Fewer templates read per trial than `reference`'s and non-inferior on every measured axis; otherwise not shown | + +Keeping the check loop is reported apart from any non-inferiority claim: +a gate passed says nothing got clearly worse, not that nothing got worse. +Templates read are counted from each trial's transcripts, every template +file, section file or skill read or loaded, once. + **Each approach in plain words** (FR-12-07): - What it did better and worse than `none`, by radar axis. diff --git a/docs/coverage.md b/docs/coverage.md index cd7c034..5f16676 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -244,3 +244,5 @@ when: | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes" | +| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a round running none of the registered pairs prints none of them" | +| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command" | diff --git a/docs/requirements.md b/docs/requirements.md index c13dd90..3bf4b9a 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -257,6 +257,8 @@ | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | +| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where the point estimate of the mean billed cost per trial drops by at least 10 % on each task, its interval printed beside it, and no ISO axis reads worse on either; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | +| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from each trial's transcripts on that task, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | ## Quality requirements diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index cc1b0b2..a980d11 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -41,7 +41,8 @@ from generate_arm import RECORDED, record_path # noqa: E402 from harness import (ARMS, ARMS_DIR, PROMPT, REGISTRATIONS, # noqa: E402 ROUND5_ARMS, ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, - ROUND5E_ARMS, SCORABLE, TEMPLATES_ENV, VENDORED, VOIDING, + ROUND5E_ARMS, SCORABLE, SECTIONS_INTO, TEMPLATES_ENV, + VENDORED, VOIDING, TrialError, canonical, git, reach, read_transcripts, read_change_prompt, recorded_round, registration_digest, scoring_area, split_name, @@ -1220,13 +1221,14 @@ def margined(key, direction, interval, baseline_mean, margins): def contrasts(table, seed, crossed=(), margins=None, strict=False, - resamples=RESAMPLES, only=None): + resamples=RESAMPLES, only=None, pairs=None): """The paired differences, their intervals and their verdicts, with each held against `margins`, by default the shared ones. `strict` reads them by round 5d's rules, as `strict_contrast` states, and a contrast in `crossed` unpaired. `only` limits the contrasts - computed to the labels it names. + computed to the labels it names, and `pairs` names the (treatment, + baseline) pairs read, by default the declared contrasts. A contrast in `crossed` pairs an arm judged in an earlier round with one judged in this one, so its difference carries the day as well as the arm. @@ -1237,7 +1239,7 @@ def contrasts(table, seed, crossed=(), margins=None, strict=False, results = {} for key, entry in table.items(): per_contrast = {} - for treatment, baseline in CONTRASTS: + for treatment, baseline in pairs or CONTRASTS: label = "%s-%s" % (treatment, baseline) if only and label not in only: continue @@ -1931,6 +1933,13 @@ def write_report(root, trials, table, results, seed, out_dir, lost, scans, radar, iso, drawn)) lines.append("") + # A named round prints the readings it registered, each per task, the + # templates read on each counted from that task's own transcripts. + registered = (registered_lines(tasks, seed, { + task: map_uses(root, trials, task) for task, _ in TASKS}) + if tasks else []) + lines.extend(registered) + lines.extend(["## What produced these numbers", ""]) lines.extend(provenance_lines(trials, names, arms, k, seed, generation)) @@ -2077,7 +2086,8 @@ def write_report(root, trials, table, results, seed, out_dir, appendix: appendix_lines(trials, table, results, k, seed, generation, report, record, iso, drawn), report: plain_report_lines(root, trials, table, results, radar, - appendix, k, iso, uses, drawn)} + appendix, k, iso, uses, drawn, + registered)} for document, text in documents.items(): with io.open(os.path.join(out_dir, document), "w", encoding="utf-8", newline="\n") as handle: @@ -2569,11 +2579,12 @@ def sureness_lines(trials, k): def plain_report_lines(root, trials, table, results, radar, appendix, k, - iso=None, uses=None, tasks=()): + iso=None, uses=None, tasks=(), registered=()): """The report a reader opens: the radars, each approach in plain words, the round's questions answered, and how sure the answers are. `iso` is the ISO reading where the round draws that radar; `tasks`, a named - round's reading of each task with its images, each read on its own.""" + round's reading of each task with its images, each read on its own, + and `registered` the lines of the readings it registered.""" names = ordered(trials) active = active_contrasts(trials) arms = by_cost(table, [pair[0] for pair in active if pair[1] == BARE]) @@ -2592,6 +2603,7 @@ def plain_report_lines(root, trials, table, results, radar, appendix, k, lines.extend(posthoc_iso_lines(iso)) if tasks: lines.extend(plain_task_lines(tasks, results)) + lines.extend(registered) else: if radar: for theme, image in sorted(radar.items()): @@ -3549,6 +3561,11 @@ def mapped_templates(arm): if entry.get("vendor"): record = generation_records().get(arm) or {} return list(record.get("resolved_files") or []) + if entry.get("sections"): + folder = os.path.join(ARMS_DIR, entry["sections"]) + return sorted(os.path.relpath(os.path.join(base, name), folder) + .replace(os.sep, "/") + for base, _, names in os.walk(folder) for name in names) return [] @@ -3634,6 +3651,10 @@ def map_use(files, arm, templates=None, delegated=()): marker = VENDORED["into"] + "/" named = re.compile(re.escape(marker) + r"(templates/[\w./-]+\.md)") + # A section file is named by its path under the folder the arm's map + # points at, wherever a read or a shell command names it. + section = re.compile(re.escape(SECTIONS_INTO) + r"/([\w./-]+\.md)") + def mapped(templates): """Those of the templates that are on the arm's map.""" return [template for template in templates @@ -3683,6 +3704,10 @@ def mapped(templates): elif name == "Read" and entry.get("vendor"): path = str(given.get("file_path") or "").replace("\\", "/") found = mapped(named.findall(path)) + elif name in SHELLS + ("Read",) and entry.get("sections"): + text = (command if name in SHELLS + else str(given.get("file_path") or "").replace("\\", "/")) + found = mapped(section.findall(text)) elif name == "Skill" and entry.get("skills"): skill = str(given.get("skill") or "").strip() found = [skill] if skill in known else [] @@ -3698,15 +3723,19 @@ def mapped(templates): else None, "by_subagent": by_subagent} -def map_uses(root, trials): - """Every trial's map use, by name, for the arms whose file points at - the templates and whose transcripts the root still holds.""" +def map_uses(root, trials, task="build"): + """Every trial's map use on `task`, by name, for the arms whose file + points at the templates and whose transcripts the root still holds.""" home = os.path.join(root, "home") uses = {} for record in run_records(root): - if record.get("outcome") not in SCORABLE: + if (record.get("outcome") not in SCORABLE + or (record.get("task") or "build") != task): continue - name = name_of(record) + + # A change task shares its build trial's name: the task, read + # above, is what tells their uses apart. + name = trial_of(record) if name not in trials: continue arm = arm_of(name) @@ -5758,6 +5787,161 @@ def tree(installs, cost, debug): return checks +def registered_checks(seed): + """Round C1's registered readings: the check loop kept only on a cost + drop of 10 % on each task and no axis worse on either, nothing flagged + read as no degradation and never as non-inferior, an interval crossing + the margin inconclusive, and an arm delivering on demand only where it + reads fewer templates than the one that reads them all up front.""" + def reading(value): + return {"value": value, "missing": None} + + def tree(installs, cost): + return {"install": reading(installs), + "boot": reading({"factory": True, "index_status": 200}), + "cost": reading({"cost_usd": cost})} + + def plant(costs, broken=(), flaky=()): + """Five blocks of each arm, `costs` mapping (arm, task) to its cost + per trial; a changed tree of an arm in `broken` never installs, and + one in `flaky` fails on the first block alone.""" + trials = {} + for arm in ("lazyref", "lazyrefold", "lazysections", "reference", + "lazyskills"): + for block in range(1, 7): + name = trial_name(arm, block) + change = tree(arm not in broken and not ( + arm in flaky and block == 1), costs.get( + (arm, "change"), 1.0)) + change["name"] = name + trials[name] = { + "round": "C1", "judge": None, "judgings": [], + "scores": dict(tree(True, costs.get((arm, "build"), + 2.0)), name=name), + "security": None, "quality": None, "change": change} + return trials + + def text(trials, uses=None): + return "\n".join(registered_lines(task_readings(trials, seed), seed, + uses or {})) + + cheaper = {("lazyref", "build"): 1.6, ("lazyref", "change"): 0.8} + kept = text(plant(cheaper)) + slight = text(plant(dict(cheaper) | {("lazyref", "change"): 0.95})) + broken = text(plant(cheaper, broken=("lazyref",))) + flaky = text(plant(cheaper, flaky=("lazysections",))) + + def counted(arm, reads): + return {trial_name(arm, block): {"uses": [(1, "t%d" % index) + for index in range(reads)]} + for block in range(1, 7)} + uses = counted("reference", 10) | counted("lazyref", 3) + uses.update(counted("lazyskills", 12)) + uses.update(counted("lazysections", 2)) + demand = text(plant(cheaper, flaky=("lazysections",)), + {"build": uses, "change": uses}) + + # Both documents a reader opens carry the readings. + scratch = tempfile.mkdtemp(prefix="efficacy-report-registered-") + planted = plant(cheaper) + table = collect(planted) + write_report(os.path.join(scratch, "run"), planted, table, + contrasts(table, seed), seed, scratch) + documents = [] + for suffix in ("efficacy.md", "efficacy-record.md"): + with io.open(next(os.path.join(scratch, file) + for file in os.listdir(scratch) + if file.endswith(suffix)), + encoding="utf-8") as handle: + documents.append(handle.read()) + shutil.rmtree(scratch, ignore_errors=True) + return [ + ("the check loop is kept on a 10 % cost drop on each task with no " + "axis worse", + "**Kept.**" in kept and "| build task | 20 % |" in kept + and "| change task | 20 % |" in kept), + ("a cost drop under 10 % on one task does not keep the check loop", + "**Not kept.**" in slight and "| change task | 5 % |" in slight), + ("an axis worse on either task does not keep the check loop", + "**Not kept.**" in broken and "worse on Reliability" in broken), + ("nothing flagged worse reads no degradation detected, beside the " + "non-inferiority read apart", + "| %s | non-inferior on every measured axis |" % NO_DEGRADATION + in kept and "read apart" in kept), + ("an interval crossing the margin is inconclusive, never " + "non-inferior", + "| %s | inconclusive on Reliability |" % NO_DEGRADATION in flaky + and "`lazysections` against `lazyref`" in flaky + and "`lazysections` against `reference`" in flaky), + ("an arm delivers on demand only reading fewer templates than " + "reference and non-inferior to it", + "| build task | `lazyref` | 3.0 | 10.0 | non-inferior on every " + "measured axis | yes |" in demand + and "| build task | `lazyskills` | 12.0 | 10.0 |" in demand + and "`lazyskills` | 12.0 | 10.0 | non-inferior on every measured " + "axis | not shown |" in demand + and "| change task | `lazysections` | 2.0 | 10.0 | inconclusive " + "on Reliability | not shown |" in demand), + ("an arm whose reads were not counted is not shown on demand", + "| build task | `lazyref` | %s | %s |" % (NOT_MEASURED, NOT_MEASURED) + in kept and "| yes |" not in kept.split("On demand against")[-1]), + ("the report and its full record print the registered readings", + all("## The registered readings" in document + and "**Kept.**" in document for document in documents)), + ("a round running none of the registered pairs prints none of them", + registered_lines(task_readings({ + name: trial for name, trial in plant(cheaper).items() + if arm_of(name) in ("lazyref", "lazyskills")}, seed), seed, + {}) == []), + ] + + +def task_use_checks(): + """Each task's templates read are counted from that task's own + transcripts, a section file named by a read or a shell command.""" + from harness import project_folder + scratch = tempfile.mkdtemp(prefix="efficacy-report-task-uses-") + root = os.path.join(scratch, "run") + sections = mapped_templates("lazysections")[:2] + + def call(name, **given): + return {"type": "tool_use", "id": "t", "name": name, "input": given} + + def line(message_id, block): + return json.dumps({"type": "assistant", "message": { + "id": message_id, "content": [block]}}) + "\n" + calls = {"build": [call("Read", file_path="C:\\pen\\%s\\%s" % ( + SECTIONS_INTO.replace("/", "\\"), sections[0].replace("/", "\\")))], + "change": [call("Read", file_path="/pen/%s/%s" % ( + SECTIONS_INTO, sections[0])), call( + "Bash", command="cat %s/%s | head" % ( + SECTIONS_INTO, sections[1])), + call("Read", file_path="/pen/src/app.py")]} + records = [] + for task, made in calls.items(): + workspace = os.path.join(scratch, "pen-%s" % task) + folder = os.path.join(root, "home", ".claude", "projects", + project_folder(workspace)) + os.makedirs(folder) + with io.open(os.path.join(folder, "t.jsonl"), "w", + encoding="utf-8") as handle: + for index, block in enumerate(made): + handle.write(line("m%d" % index, block)) + records.append({"arm": "lazysections", "trial": 1, "task": task, + "outcome": "completed", "workspace": workspace}) + with io.open(os.path.join(root, "run-1.json"), "w", + encoding="utf-8") as handle: + json.dump({"trials": records}, handle) + trials = {"lazysections-1": {}} + counted = {task: templates_read(map_uses(root, trials, task), + "lazysections") for task in calls} + shutil.rmtree(scratch, ignore_errors=True) + return [("each task's templates read are counted from its own " + "transcripts, a section file by a read or a shell command", + len(sections) == 2 and counted == {"build": 1.0, + "change": 2.0})] + + def change_only_checks(): """A named round's change task is read whether or not its build trial was scored or reached, on rows of its own; a pilot round's keeps @@ -7281,6 +7465,235 @@ def task_lines(reading, images): return lines +# Round C1's registered readings, each paired by block on each task. The +# check loop is read at the templates commit that cuts it to one command +# against that commit's parent; the section files against the same rules +# read whole on demand and all up front; and each arm that reads on demand +# against the one that reads every template up front. +CHECK_LOOP = ("lazyref", "lazyrefold") +PACKAGING = (("lazysections", "lazyref"), ("lazysections", "reference")) +ON_DEMAND = ("lazyref", "lazyskills", "lazysections") +UP_FRONT = "reference" + +# The check loop is kept only where the mean billed cost per trial drops by +# at least this share on each task, the drop read from the paired mean +# difference over the baseline's mean on the same blocks; its interval is +# shown beside it and decides nothing. +COST_DROP = 0.10 + +# What no axis flagged worse reads as: the absence of a flag, never a claim +# that nothing got worse. +NO_DEGRADATION = "no degradation detected under the registered rule" + + +def registered_pairs(): + """Every pair the registered readings read, each once.""" + pairs = [CHECK_LOOP] + list(PACKAGING) + pairs += [(arm, UP_FRONT) for arm in ON_DEMAND] + return list(dict.fromkeys(pairs)) + + +def axis_states(iso_results, label): + """Each ISO axis of one pair on one task, as (axis, state): `worse` + where the whole interval lies past the margin downward, + `non-inferior` where its lower bound clears minus the margin, + `inconclusive` where it crosses the margin, None where unread.""" + states = [] + for axis, _ in ISO_AXES: + contrast = iso_results.get("iso:" + axis, {}).get(label) or {} + held = contrast.get("non_inferior") or {} + if contrast.get("verdict") == "worse": + state = "worse" + elif contrast.get("verdict") not in COUNTED_VERDICTS: + state = None + elif held.get("within"): + state = "non-inferior" + else: + state = "inconclusive" + states.append((axis, state)) + return states + + +def cost_drop(table, seed, pair): + """The share the treatment's mean billed cost per trial drops by against + the baseline's, paired by block, with its interval: (drop, low, high), + each None where no pair was measured.""" + label = "%s-%s" % pair + contrast = contrasts({"cost_usd": table["cost_usd"]}, seed, + pairs=[pair])["cost_usd"][label] + right = table["cost_usd"]["values"].get(pair[1], {}) + left = table["cost_usd"]["values"].get(pair[0], {}) + paired = [right[index] for index in sorted(set(left) & set(right)) + if left[index] is not None and right[index] is not None] + base = statistics.fmean(paired) if paired else None + interval = contrast.get("interval") or {} + if not base or contrast.get("mean") is None: + return None, None, None + low, high = interval.get("low"), interval.get("high") + return (-contrast["mean"] / base, + None if high is None else -high / base, + None if low is None else -low / base) + + +def pair_reading(reading, seed, pair): + """One pair's registered reading on one task: its cost drop, the axes + read worse, inconclusive and unread, and whether every measured axis is + non-inferior.""" + _, _, _, table, iso = reading + label = "%s-%s" % pair + results = contrasts(iso[0], seed, margins=iso_margins(iso[0]), + strict=True, pairs=[pair]) + states = axis_states(results, label) + measured = [state for _, state in states if state is not None] + return {"cost": cost_drop(table, seed, pair), + "worse": [axis for axis, state in states if state == "worse"], + "inconclusive": [axis for axis, state in states + if state == "inconclusive"], + "unread": [axis for axis, state in states if state is None], + "non_inferior": bool(measured) and all( + state == "non-inferior" for state in measured)} + + +def worse_words(read): + """Whether an axis reads worse, in the registered words.""" + if read["worse"]: + return "worse on %s" % spoken(read["worse"]) + return NO_DEGRADATION + + +def non_inferior_words(read): + """Whether the pair is non-inferior, in the registered words: claimed + only where every measured axis's lower bound clears minus its margin.""" + if read["non_inferior"]: + return "non-inferior on every measured axis" + if read["worse"]: + return "not non-inferior: worse on %s" % spoken(read["worse"]) + if read["inconclusive"]: + return "inconclusive on %s" % spoken(read["inconclusive"]) + return "not measured" + + +def percent(share): + """A share as a whole percentage, or a dash.""" + return "—" if share is None else "%d %%" % round(100 * share) + + +def check_loop_kept(reads): + """Whether the check loop is kept: its mean billed cost per trial drops + by at least COST_DROP on each task, and no axis reads worse on either; + None where a task's cost or axes were not read.""" + if not reads or any(read["cost"][0] is None for read in reads.values()): + return None + return all(read["cost"][0] >= COST_DROP and not read["worse"] + for read in reads.values()) + + +def templates_read(uses, arm): + """The mean count of templates each of an arm's trials read, or None + where no trial's reads were counted.""" + counts = [len({template for _, template in use["uses"]}) + for name, use in uses.items() if arm_of(name) == arm] + return statistics.fmean(counts) if counts else None + + +def on_demand(read, uses, arm): + """Whether an arm is read as delivering on demand on one task: it reads + fewer templates per trial than the arm that reads them all up front, + and is non-inferior to it on every measured axis.""" + ours, theirs = templates_read(uses, arm), templates_read(uses, UP_FRONT) + if ours is None or theirs is None: + return False + return ours < theirs and read["non_inferior"] + + +def registered_lines(tasks, seed, uses_by_task): + """Round C1's registered readings in its own words, one table each, per + task: the check loop and whether it is kept, the section files against + the same rules packaged otherwise, and each on-demand arm against the + templates read up front. `uses_by_task` holds each task's map use.""" + present = {arm_of(name) for reading in tasks for name in reading[2]} + if not any(set(pair) <= present for pair in registered_pairs()): + return [] + lines = ["## The registered readings", "", + "Each reading pairs two arms by block on each task. An axis " + "reads worse only where its whole interval lies past the " + "margin downward; with none flagged the reading is \"%s\". An " + "arm is non-inferior only where every measured axis's interval " + "has its lower bound above minus the margin; one crossing the " + "margin is inconclusive." % NO_DEGRADATION, ""] + reads = {(reading[0], pair): pair_reading(reading, seed, pair) + for reading in tasks for pair in registered_pairs() + if set(pair) <= present} + if set(CHECK_LOOP) <= present: + lines.extend([ + "### Is the check loop kept? `%s` against `%s`" % CHECK_LOOP, "", + "| Task | Mean billed cost per trial drops by | 95 %% interval " + "| %d %% or more | Is an axis worse? | Non-inferior? |" + % round(100 * COST_DROP), "| --- | --- | --- | --- | --- | --- |"]) + loop = {} + for task, label, _, _, _ in tasks: + read = reads[(task, CHECK_LOOP)] + loop[task] = read + drop, low, high = read["cost"] + lines.append("| %s | %s | %s to %s | %s | %s | %s |" % ( + label, percent(drop), percent(low), percent(high), + "—" if drop is None else + ("yes" if drop >= COST_DROP else "no"), + worse_words(read), non_inferior_words(read))) + kept = check_loop_kept(loop) + lines.extend(["", "**%s.** %s Keeping the loop is no claim that " + "nothing got worse: that is the non-inferiority " + "column, read apart." % ( + {True: "Kept", False: "Not kept", + None: "Not decided"}[kept], + "The registered gate: the mean billed cost per " + "trial drops by at least %d %% on each task, and " + "no ISO axis reads worse on either; a negative " + "drop is a rise." % round(100 * COST_DROP)), ""]) + packaged = [pair for pair in PACKAGING if set(pair) <= present] + if packaged: + lines.extend([ + "### The section files: the same rules, packaged otherwise", "", + "| Task | Against | Mean billed cost per trial drops by | " + "95 % interval | Is an axis worse? | Non-inferior? |", + "| --- | --- | --- | --- | --- | --- |"]) + for task, label, _, _, _ in tasks: + for pair in packaged: + read = reads[(task, pair)] + drop, low, high = read["cost"] + lines.append("| %s | `%s` against `%s` | %s | %s to %s | %s " + "| %s |" % (label, pair[0], pair[1], + percent(drop), percent(low), + percent(high), worse_words(read), + non_inferior_words(read))) + lines.append("") + lazy = [arm for arm in ON_DEMAND if {arm, UP_FRONT} <= present] + if lazy: + lines.extend([ + "### On demand against up front", "", + "An arm delivers on demand only where it reads fewer templates " + "per trial than `%s`, which is handed them all, and is " + "non-inferior to it on every measured axis. Templates are " + "counted from each trial's transcripts: every template file or " + "skill it read or loaded, once." % UP_FRONT, "", + "| Task | Arm | Templates read per trial | `%s`'s | " + "Non-inferior? | Delivers on demand |" % UP_FRONT, + "| --- | --- | --- | --- | --- | --- |"]) + for task, label, _, _, _ in tasks: + uses = uses_by_task.get(task) or {} + for arm in lazy: + read = reads[(task, (arm, UP_FRONT))] + ours, theirs = (templates_read(uses, arm), + templates_read(uses, UP_FRONT)) + lines.append("| %s | `%s` | %s | %s | %s | %s |" % ( + label, arm, NOT_MEASURED if ours is None + else "%.1f" % ours, NOT_MEASURED if theirs is None + else "%.1f" % theirs, non_inferior_words(read), + "yes" if on_demand(read, uses, arm) else "not shown")) + lines.append("") + return lines + + # How the plain report reads the ISO radar, under it. ISO_PLAIN_READING = ( "How to read it: each axis is one quality of the software, from the " @@ -9422,6 +9835,8 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in change_only_checks()) checks.extend((label, ok, ok) for label, ok in change_reading_checks()) checks.extend((label, ok, ok) for label, ok in task_radar_checks(seed)) + checks.extend((label, ok, ok) for label, ok in registered_checks(seed)) + checks.extend((label, ok, ok) for label, ok in task_use_checks()) for label, ok, got in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) From edc00ae19c19f5ed6e36940b70f9c36c7efeb2ba Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:44:35 +0200 Subject: [PATCH 05/18] fix(efficacy): Codex round 1 on the changed-tree scoring - contrasts keep the pairs asked for apart from each contrast's differences, so a second metric no longer reads numbers as arm names - the check loop is kept only with both tasks read; a build alone leaves it not decided - a changed tree's bundle carries the pinned change prompt, and its judge is told the change extends the spec; the build's prompt is unchanged - a section file is read only by a read or a reading command, a wildcard standing for each file it matches; a listing reads none - a named round with no build reads its finding table from the change task's own trials, cost and contrasts Refs #178, #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/08-crosscutting-concepts.md | 4 +- docs/coverage.md | 6 +- docs/requirements.md | 8 +- tests/efficacy/judge.py | 122 ++++++++++-- tests/efficacy/report.py | 177 ++++++++++++++---- 5 files changed, 257 insertions(+), 60 deletions(-) diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 8f2c670..d59a29e 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -365,7 +365,9 @@ of a block starts from one fixture, a qualifying `none` build of round 5e, so the changed tree is read on every ISO axis the build is. It gets the same scoring, security and quality readings and judge, each filed apart from the build's under a `-change` folder of its own (FR-16-01, FR-16-03, -FR-16-05). A changed tree that does not install loses its probes and goes +FR-16-05). The judge reads a changed tree against the specification and +the pinned change prompt, told that the change extends the specification, +so the API the change adds is not counted as surface beyond it. A changed tree that does not install loses its probes and goes unjudged, as a build does; a reading the reader could not take is missing. Two readings compare the changed tree with its fixture, each counted on one diff --git a/docs/coverage.md b/docs/coverage.md index 5f16676..0f09317 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -240,9 +240,9 @@ when: | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | | FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | -| FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks" | +| FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks"
`judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
`judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
`judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | -| FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes" | -| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a round running none of the registered pairs prints none of them" | +| FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
`report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
`report.py` "named pairs are read for every metric of a table" | +| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "the check loop is not kept on the build task's readings alone"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a round running none of the registered pairs prints none of them" | | FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command" | diff --git a/docs/requirements.md b/docs/requirements.md index 3bf4b9a..49aa728 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -253,12 +253,12 @@ | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | | FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | -| FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, and not judge one that did not install. | Judge | +| FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | -| FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | -| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where the point estimate of the mean billed cost per trial drops by at least 10 % on each task, its interval printed beside it, and no ISO axis reads worse on either; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | -| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from each trial's transcripts on that task, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | +| FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | +| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial drops by at least 10 % on each, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | +| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from each trial's transcripts on that task, a file read by a read or a reading command, a wildcard standing for each file it matches, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | ## Quality requirements diff --git a/tests/efficacy/judge.py b/tests/efficacy/judge.py index 470712e..25d59e1 100644 --- a/tests/efficacy/judge.py +++ b/tests/efficacy/judge.py @@ -33,8 +33,8 @@ import lib # noqa: E402 import score # noqa: E402 from harness import (LiveRunError, TrialError, canonical, # noqa: E402 - claim_area, claim_refusal_check, release_area, - task_folder) + claim_area, claim_refusal_check, read_change_prompt, + release_area, task_folder) HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPT = os.path.basename(__file__) @@ -259,6 +259,26 @@ Answer with JSON only, in the shape the schema requires. """ +# Where a changed tree's bundle carries the change it was asked for: the +# change prompt as pinned, unmasked, since every arm was given the same one. +CHANGE_FILE = "CHANGE.md" + +# What a changed tree's judge is told besides, after the build's prompt, +# which stays as it is: the change extends the specification, so the API +# it adds is required and the isp row does not count it against the tree. +CHANGE_NOTE = """ +This submission was then changed to meet CHANGE.md, also in the directory. +CHANGE.md extends SPEC.md: every name, route and field it adds is part of +the specification, and the isp dimension reads them as required, not as +surface beyond what the specification asks for. +""" + + +def prompt_for(task): + """The judging prompt for a tree of `task`: the build's alone, or the + build's with the change's note after it.""" + return PROMPT if task == "build" else PROMPT + CHANGE_NOTE + def schema(): """The rubric as a JSON Schema, so the CLI enforces the shape. @@ -344,9 +364,10 @@ def copied_dir(base, name): for cache, inner in USER_CACHE_DIRS) -def build_bundle(tree, target, trial=None): +def build_bundle(tree, target, trial=None, change=None): """Copy one trial's tree into a blind bundle and return what was stripped; - `trial` names the trial where the tree's own folder does not. + `trial` names the trial where the tree's own folder does not, and + `change`, a changed tree's, the change requirements it carries. The context file is the loudest marker but not the only one: a README that credits its conventions names the arm just as clearly, so the text files @@ -387,13 +408,21 @@ def build_bundle(tree, target, trial=None): if spec: with io.open(os.path.join(target, "SPEC.md"), "wb") as handle: handle.write(spec.pop("text")) + if change is not None: + with io.open(os.path.join(target, CHANGE_FILE), "w", + encoding="utf-8", newline="") as handle: + handle.write(change) # A changed tree's folder carries the task beside the trial's name, and # a path through its scoring area the trial's name alone. names = {os.path.basename(tree), trial or os.path.basename(tree)} leaks = [leak for name in sorted(names) for leak in surviving_markers(target, name)] - return {"removed": removed, "markers_masked": masked, "spec": spec, - "leaks": leaks, "digest": digest(target)} + stripped = {"removed": removed, "markers_masked": masked, "spec": spec, + "leaks": leaks, "digest": digest(target)} + if change is not None: + stripped["change"] = {"file": CHANGE_FILE, "sha256": hashlib.sha256( + change.encode("utf-8")).hexdigest()} + return stripped def spec_text(path): @@ -548,8 +577,8 @@ def codex_version(executable): return version -def judge_bundle(bundle, options, schema_path): - """Run the judge over one bundle and return its answer. +def judge_bundle(bundle, options, schema_path, prompt=PROMPT): + """Run the judge over one bundle with `prompt` and return its answer. Read-only and ephemeral: the judge inspects a tree and writes nothing, and no session file carries one trial's reading into the next. @@ -558,7 +587,7 @@ def judge_bundle(bundle, options, schema_path): os.path.basename(bundle) + "-message.json") if options.cli == "claude": - return judge_through_claude(bundle, options, schema_path) + return judge_through_claude(bundle, options, schema_path, prompt) # The prompt goes on standard input, named by `-`, never as an argument: # the Windows shim runs through `cmd.exe`, which ends a command at a @@ -576,7 +605,7 @@ def judge_bundle(bundle, options, schema_path): if options.dry_run: return {"argv": argv, "dry_run": True} outcome = score.run(argv, cwd=bundle, timeout=options.timeout, - stdin=PROMPT) + stdin=prompt) if not os.path.exists(last): return {"argv": argv, "error": "the judge wrote no final message: %s" % cli_said(outcome)} @@ -600,7 +629,7 @@ def cli_said(outcome): return (outcome["stderr"] or outcome["stdout"] or "").strip()[-400:] -def judge_through_claude(bundle, options, schema_path): +def judge_through_claude(bundle, options, schema_path, judging=PROMPT): """Run the judge through the `claude` CLI, the rounds' judge. A reading is recorded under its own CLI and model and is never meaned @@ -632,7 +661,7 @@ def judge_through_claude(bundle, options, schema_path): "prose before or after it, no code fence, no summary. It must " "match this schema exactly:\n\n%s\n\n%s\n\nThe submission is the " "tree at %s. Read it, then reply with the JSON object alone." - % (shape, PROMPT, bundle)) + % (shape, judging, bundle)) # On standard input, as the other backend does: the schema carries the # prompt past the command-line length this platform allows. @@ -902,18 +931,21 @@ def judge_trials(options, available, wanted): with io.open(schema_path, "w", encoding="utf-8") as handle: json.dump(schema(), handle, indent=2) + # A changed tree is judged against the change it was asked for too. + change = read_change_prompt() if options.task == "change" else None results, failures = [], 0 for position, name in enumerate(order): label = labels[position] repeats.setdefault(name, []).append(label) print("%s as %s" % (name, label)) bundle = os.path.join(bundles, label) - stripped = build_bundle(available[name], bundle, name) + stripped = build_bundle(available[name], bundle, name, change) refused = refusal(stripped) if refused: answer = {"argv": None, "error": refused} else: - answer = judge_bundle(bundle, options, schema_path) + answer = judge_bundle(bundle, options, schema_path, + prompt_for(options.task)) record = {"trial": name, "task": options.task, "blind_id": label, "model": options.model, @@ -1174,6 +1206,37 @@ def refused(label): """ +def change_run(scratch): + """Judge one planted changed tree through `main` with the CLI on PATH: + whether the judge read the change's note on stdin, beside a bundle + carrying the change requirements.""" + root = os.path.join(scratch, "change-run") + tree = os.path.join(score.scoring_area(root), "scoring-change", "none-1", + "tree", "change-none-1") + os.makedirs(tree) + with io.open(SPEC, "rb") as source, io.open( + os.path.join(tree, "SPEC.md"), "wb") as target: + target.write(source.read()) + saved, sys.stdout = sys.stdout, io.StringIO() + try: + main(["--root", root, "--task", "change", "--repeat", "1"]) + finally: + sys.stdout = saved + judging = os.path.join(score.scoring_area(root), "judge-change") + try: + with io.open(os.path.join(judging, "T1.json"), + encoding="utf-8") as handle: + record = json.load(handle) + told = ((record.get("answer") or {}).get("stdin") or "").replace( + "\r\n", "\n") + except (OSError, ValueError): + return False + return (told == prompt_for("change") and os.path.isfile(os.path.join( + judging, BUNDLES, "T1", CHANGE_FILE)) + and (record.get("bundle") or {}).get("change", {}).get("file") + == CHANGE_FILE) + + def launch_checks(scratch): """Prove the judge launches through a shim, with the prompt on stdin. @@ -1229,12 +1292,17 @@ def refuses(call): effort="high", dry_run=False, cli="codex", timeout=120) answer = judge_bundle(bundle, options, os.path.join(scratch, "s.json")) + changed = judge_bundle(bundle, options, + os.path.join(scratch, "s.json"), + prompt_for("change")) # The refusal leaves the message file empty, so the failure is read # from the branch that finds a file and no JSON in it. os.environ["FAKE_CODEX_REFUSES"] = REFUSAL refused = judge_bundle(bundle, options, os.path.join(scratch, "s.json")) + os.environ.pop("FAKE_CODEX_REFUSES", None) + judged_change = change_run(scratch) finally: os.environ["PATH"] = saved os.environ.pop("FAKE_CODEX_REFUSES", None) @@ -1243,6 +1311,15 @@ def refuses(call): stdin = (received.get("stdin") or "").replace("\r\n", "\n") checks.append(("the prompt reaches the CLI whole, on stdin", stdin == PROMPT and PROMPT not in answer["argv"])) + told = ((changed.get("payload") or {}).get("stdin") or "").replace( + "\r\n", "\n") + checks.append(("a change task's judging run hands the judge the change's " + "note and the bundle its requirements", judged_change)) + checks.append(("a changed tree's judge is told the change extends the " + "spec, after the build's prompt unchanged", + told == PROMPT + CHANGE_NOTE and told.startswith(PROMPT) + and "CHANGE.md extends SPEC.md" in told + and prompt_for("build") == PROMPT)) checks.append(("every argument reaches the CLI intact", received.get("argv") == answer["argv"][1:])) message = bundle + "-message.json" @@ -1395,13 +1472,26 @@ def change_checks(scratch): plant(changed, {"notes.txt": "built under %s\n" % changed.replace( "change-none-1", "x")}) stripped = build_bundle(changed, os.path.join(scratch, "change-bundle"), - "none-1") + "none-1", read_change_prompt()) + carried = None + if os.path.isfile(os.path.join(scratch, "change-bundle", CHANGE_FILE)): + with io.open(os.path.join(scratch, "change-bundle", CHANGE_FILE), + encoding="utf-8", newline="") as handle: + carried = handle.read() + plain = build_bundle(built, os.path.join(scratch, "build-bundle")) return [("a change task's trees are found by their trial, apart from " "the build's", trees(root, "change") == {"none-1": changed} and trees(root) == {"none-1": built}), ("a changed tree's bundle naming its trial in a path leaks", - any(leak[1] == "none-1" for leak in stripped["leaks"]))] + any(leak[1] == "none-1" for leak in stripped["leaks"])), + ("a changed tree's bundle carries the pinned change requirements, " + "a build's none", + carried == read_change_prompt() + and stripped["change"]["file"] == CHANGE_FILE + and "change" not in plain + and not os.path.exists(os.path.join(scratch, "build-bundle", + CHANGE_FILE)))] def claim_checks(scratch): diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index a980d11..51a8363 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -1236,10 +1236,13 @@ def contrasts(table, seed, crossed=(), margins=None, strict=False, reader can see the number and what produced it, and nothing downstream counts it as a win, a fail or a finding. """ + # The pairs read are kept apart from each contrast's differences, which + # are worked out afresh for every metric. + selected = list(pairs or CONTRASTS) results = {} for key, entry in table.items(): per_contrast = {} - for treatment, baseline in pairs or CONTRASTS: + for treatment, baseline in selected: label = "%s-%s" % (treatment, baseline) if only and label not in only: continue @@ -1252,19 +1255,19 @@ def contrasts(table, seed, crossed=(), margins=None, strict=False, key, entry["direction"], left, right, seed, margins or MARGINS, resamples, label in crossed) continue - pairs = [] + differences = [] for index in sorted(set(left) & set(right)): if left[index] is None or right[index] is None: continue - pairs.append(left[index] - right[index]) - if not pairs: + differences.append(left[index] - right[index]) + if not differences: per_contrast[label] = { "pairs": [], "mean": None, "interval": {"low": None, "high": None, "method": "no complete pair was measured"}, "verdict": "not computed", "non_inferior": None} continue - interval = bca_interval(pairs, seed) + interval = bca_interval(differences, seed) observed = [value for value in right.values() if value is not None] across = label in crossed read = verdict(interval, entry["direction"]) @@ -1275,8 +1278,8 @@ def contrasts(table, seed, crossed=(), margins=None, strict=False, band[1] * abs(statistics.fmean( observed))) per_contrast[label] = { - "pairs": pairs, - "mean": round(statistics.fmean(pairs), 4), + "pairs": differences, + "mean": round(statistics.fmean(differences), 4), "interval": interval, "verdict": CROSSING_VERDICT if across else read, "non_inferior": None if across else non_inferior( @@ -1930,7 +1933,10 @@ def write_report(root, trials, table, results, seed, out_dir, active_contrasts(reading[2])), iso_radar_svg)) for reading in tasks] lines.extend(executive_section(trials, table, results, withdrawn or {}, - lost, scans, radar, iso, drawn)) + lost, scans, radar, iso, drawn, + finding_reading(tasks, trials, table, + results, iso, seed, + withdrawn))) lines.append("") # A named round prints the readings it registered, each per task, the @@ -2095,6 +2101,22 @@ def write_report(root, trials, table, results, seed, out_dir, return os.path.join(out_dir, report) +def finding_reading(tasks, trials, table, results, iso, seed, withdrawn=None): + """What a named round's finding table reads, as (trials, table, + contrasts, ISO reading, task): the run's own where its first task is + the build, and the change task's own view, read afresh, where it has no + build; None for a pilot round.""" + if not tasks: + return None + task, label, view, view_table, reading = tasks[0] + if task == "build": + return trials, table, results, iso, label + view_results = round_contrasts(view, view_table, seed) + if withdrawn: + withdraw(withdrawn, view_table, view_results) + return view, view_table, view_results, reading, label + + def draw_radar(out_dir, stem, panels, draw): """Each theme's radar of `panels` written to `out_dir` under `stem`; the images by theme, none where there is no panel.""" @@ -3233,6 +3255,11 @@ def round5d_section(trials, table, results, seed, margins, TEMPLATE_OPERAND = re.compile(re.escape(VENDORED["into"] + "/") + r"(templates/[\w./*?\[\]-]+)") +# The same for a section file, named by its path under the folder the +# `lazysections` arm's map points at. +SECTION_OPERAND = re.compile(re.escape(SECTIONS_INTO + "/") + + r"([\w./*?\[\]-]+)") + # A redirection that writes no file: to the null device, or of one stream # into another. Taken out of a command before it is read for a write. NULL_REDIRECT = re.compile( @@ -3436,11 +3463,11 @@ def shell_writes(command): return first_writing_command(command) is not None -def shell_reads(command, known=()): +def shell_reads(command, known=(), operand_of=TEMPLATE_OPERAND): """The templates a shell command reads, as (index of its simple command, template) in order: every one a reading command names under - the vendored copy, a wildcard operand standing for each template of the - map it matches.""" + the vendored copy, or where `operand_of` finds them, a wildcard operand + standing for each template of the map it matches.""" found = [] directory = "" commands = simple_commands(command, keep_quotes=True) @@ -3457,12 +3484,12 @@ def named(tokens): templates = [] for token in itertools.chain.from_iterable(map(brace_expanded, tokens)): - matched = TEMPLATE_OPERAND.findall(token) + matched = operand_of.findall(token) # A path with no vendored copy in it may be relative to the # directory an earlier command of the call moved into. if not matched and directory and not token.startswith("-"): - matched = TEMPLATE_OPERAND.findall(posixpath.normpath( + matched = operand_of.findall(posixpath.normpath( posixpath.join(directory, token.strip("'\"")))) for operand in matched: if any(mark in operand for mark in "*?["): @@ -3517,7 +3544,8 @@ def named(tokens): if word in SHELL_PROGRAMS: for piece in program_code(text, bodies).split("\n"): found.extend((index, template) for _, template - in shell_reads(unquoted(piece), known)) + in shell_reads(unquoted(piece), known, + operand_of)) continue if word not in READ_COMMANDS: continue @@ -3651,8 +3679,8 @@ def map_use(files, arm, templates=None, delegated=()): marker = VENDORED["into"] + "/" named = re.compile(re.escape(marker) + r"(templates/[\w./-]+\.md)") - # A section file is named by its path under the folder the arm's map - # points at, wherever a read or a shell command names it. + # A section file a read names, by its path under the folder the arm's + # map points at. section = re.compile(re.escape(SECTIONS_INTO) + r"/([\w./-]+\.md)") def mapped(templates): @@ -3694,8 +3722,13 @@ def mapped(templates): # writing one came before the write. if name in SHELLS: writes_at = first_writing_command(command) - if name in SHELLS and entry.get("vendor"): - for index, template in shell_reads(command, sorted(known)): + # A section file is read by a shell command as a vendored template + # is: only by a reading command, a wildcard standing for each one. + if name in SHELLS and (entry.get("vendor") or entry.get("sections")): + operand_of = (SECTION_OPERAND if entry.get("sections") + else TEMPLATE_OPERAND) + for index, template in shell_reads(command, sorted(known), + operand_of): if template in known or not known: found.append(template) if first_write is None and (writes_at is None @@ -3704,10 +3737,9 @@ def mapped(templates): elif name == "Read" and entry.get("vendor"): path = str(given.get("file_path") or "").replace("\\", "/") found = mapped(named.findall(path)) - elif name in SHELLS + ("Read",) and entry.get("sections"): - text = (command if name in SHELLS - else str(given.get("file_path") or "").replace("\\", "/")) - found = mapped(section.findall(text)) + elif name == "Read" and entry.get("sections"): + path = str(given.get("file_path") or "").replace("\\", "/") + found = mapped(section.findall(path)) elif name == "Skill" and entry.get("skills"): skill = str(given.get("skill") or "").strip() found = [skill] if skill in known else [] @@ -5840,6 +5872,8 @@ def counted(arm, reads): uses.update(counted("lazysections", 2)) demand = text(plant(cheaper, flaky=("lazysections",)), {"build": uses, "change": uses}) + builds_alone = text({name: dict(trial, change=None) + for name, trial in plant(cheaper).items()}) # Both documents a reader opens carry the readings. scratch = tempfile.mkdtemp(prefix="efficacy-report-registered-") @@ -5860,6 +5894,9 @@ def counted(arm, reads): "axis worse", "**Kept.**" in kept and "| build task | 20 % |" in kept and "| change task | 20 % |" in kept), + ("the check loop is not kept on the build task's readings alone", + "**Not decided.**" in builds_alone + and "| build task | 20 % |" in builds_alone), ("a cost drop under 10 % on one task does not keep the check loop", "**Not kept.**" in slight and "| change task | 5 % |" in slight), ("an axis worse on either task does not keep the check loop", @@ -5902,7 +5939,13 @@ def task_use_checks(): from harness import project_folder scratch = tempfile.mkdtemp(prefix="efficacy-report-task-uses-") root = os.path.join(scratch, "run") - sections = mapped_templates("lazysections")[:2] + every = mapped_templates("lazysections") + sections = every[:2] + + # A listing reads nothing; a wildcard read reads each file it matches. + folder = sections[0].split("/")[0] + last = every[-1].split("/")[0] + matched = [name for name in every if name.startswith(last + "/")] def call(name, **given): return {"type": "tool_use", "id": "t", "name": name, "input": given} @@ -5914,8 +5957,9 @@ def line(message_id, block): SECTIONS_INTO.replace("/", "\\"), sections[0].replace("/", "\\")))], "change": [call("Read", file_path="/pen/%s/%s" % ( SECTIONS_INTO, sections[0])), call( - "Bash", command="cat %s/%s | head" % ( - SECTIONS_INTO, sections[1])), + "Bash", command="ls %s/%s" % (SECTIONS_INTO, folder)), + call("Bash", command="cat %s/%s/*.md | head" % ( + SECTIONS_INTO, last)), call("Read", file_path="/pen/src/app.py")]} records = [] for task, made in calls.items(): @@ -5938,8 +5982,57 @@ def line(message_id, block): shutil.rmtree(scratch, ignore_errors=True) return [("each task's templates read are counted from its own " "transcripts, a section file by a read or a shell command", - len(sections) == 2 and counted == {"build": 1.0, - "change": 2.0})] + len(sections) == 2 and folder != last and matched + and counted == {"build": 1.0, "change": 1.0 + len(matched)})] + + +def pair_contrast_checks(seed): + """Contrasts read for named pairs, over several metrics: the pairs asked + for stay the pairs read for every metric.""" + table = {key: {"label": key, "direction": UP, "values": { + "lazyskills": {1: 1.0, 2: 2.0}, "short": {1: 0.5, 2: 1.0}}} + for key in ("first", "second")} + try: + got = contrasts(table, seed, pairs=[("lazyskills", "short")]) + read = [got[key]["lazyskills-short"]["mean"] + for key in ("first", "second")] + except (TypeError, KeyError): + read = None + return [("named pairs are read for every metric of a table", + read == [0.75, 0.75])] + + +def change_finding_checks(seed): + """A named round with change tasks and no build reads its finding table + from the change task's own view, cost and contrasts.""" + def reading(value): + return {"value": value, "missing": None} + + trials = {} + for arm, cost in ((BARE, 0.5), ("inline", 0.8)): + for block in range(1, 6): + name = trial_name(arm, block) + trials[name] = change_only({"round": "C1", "change": { + "name": name, "install": reading(True), + "boot": reading({"factory": True, "index_status": 200}), + "cost": reading({"cost_usd": cost})}}) + scratch = tempfile.mkdtemp(prefix="efficacy-report-change-finding-") + table = collect(trials) + write_report(os.path.join(scratch, "run"), trials, table, + contrasts(table, seed), seed, scratch) + with io.open(next(os.path.join(scratch, file) + for file in os.listdir(scratch) + if file.endswith("efficacy-record.md")), + encoding="utf-8") as handle: + record = handle.read() + shutil.rmtree(scratch, ignore_errors=True) + finding = record.split("## Arms against `none`, change task")[-1] + rows = [line for line in finding.splitlines() + if line.startswith("| `inline` |")] + return [("a named round with no build reads its finding table from the " + "change task's own trials and cost", + "## Arms against `none`, change task" in record + and len(rows) == 1 and "$0.80" in rows[0])] def change_only_checks(): @@ -7580,12 +7673,17 @@ def percent(share): def check_loop_kept(reads): """Whether the check loop is kept: its mean billed cost per trial drops - by at least COST_DROP on each task, and no axis reads worse on either; - None where a task's cost or axes were not read.""" - if not reads or any(read["cost"][0] is None for read in reads.values()): + by at least COST_DROP on each task, and no axis reads worse on either. + A task that misses either is enough to refuse it; keeping it needs both + tasks read, so it is None while one is not.""" + if any(read["worse"] or (read["cost"][0] is not None + and read["cost"][0] < COST_DROP) + for read in reads.values()): + return False + if set(reads) != {task for task, _ in TASKS} or any( + read["cost"][0] is None for read in reads.values()): return None - return all(read["cost"][0] >= COST_DROP and not read["worse"] - for read in reads.values()) + return True def templates_read(uses, arm): @@ -7717,14 +7815,16 @@ def registered_lines(tasks, seed, uses_by_task): def executive_section(trials, table, results, withdrawn=None, lost=(), - scans=(), radar=None, iso=None, tasks=()): + scans=(), radar=None, iso=None, tasks=(), finding=None): """The report's first sections: the summary, a radar per file arm read against no file where `radar` names its two images, light and dark; then the arms against no file: the finding table, one line per file on why it scored so, the reading, the contrasts between files scored, and the caveats. `iso` is the ISO reading where the round draws that radar; `tasks`, for a named round, holds each task's reading and its images, - and each task gets a radar and a verdict of its own. + and each task gets a radar and a verdict of its own; `finding` is what + the finding table reads, as (trials, table, contrasts, ISO reading, + task), by default the run's own under the first task's name. Like the score, it digests the verdict vector and decides nothing. """ @@ -7733,8 +7833,10 @@ def executive_section(trials, table, results, withdrawn=None, lost=(), if tasks: for reading, images in tasks: lines.extend(task_lines(reading, images) + [""]) - lines.extend(finding_lines(trials, table, results, active, iso, - tasks[0][0][1])) + view, view_table, view_results, view_iso, label = ( + finding or (trials, table, results, iso, tasks[0][0][1])) + lines.extend(finding_lines(view, view_table, view_results, + active_contrasts(view), view_iso, label)) lines.extend(["", caveats_line(trials, withdrawn or {}, lost, scans)]) return lines @@ -9837,6 +9939,9 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in task_radar_checks(seed)) checks.extend((label, ok, ok) for label, ok in registered_checks(seed)) checks.extend((label, ok, ok) for label, ok in task_use_checks()) + checks.extend((label, ok, ok) for label, ok in pair_contrast_checks(seed)) + checks.extend((label, ok, ok) for label, ok + in change_finding_checks(seed)) for label, ok, got in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) From 1a26e84ddaaca7c7e2daf3dc1f811663fec276d1 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:23:27 +0200 Subject: [PATCH 06/18] fix(efficacy): Codex round 2 on the changed-tree scoring - the data upgrade keeps each seeded record's row as the fixture's list page shows it, prices and rates included, and fails a field the upgraded tree no longer shows; a column the change adds is no loss - each task's template use is read over that task's own trials, so a reading the report leaves out counts on neither task - the check loop's 10 % gate reads the unrounded paired differences; the rounded mean is for display only Refs #178, #158, #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/08-crosscutting-concepts.md | 2 +- docs/coverage.md | 6 +- docs/requirements.md | 6 +- tests/efficacy/quality.py | 101 ++++++++++++++---- tests/efficacy/report.py | 62 +++++++++-- 5 files changed, 141 insertions(+), 36 deletions(-) diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index d59a29e..6f0d0e9 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -382,7 +382,7 @@ axis only: failed is the fixture's, not the change's, and counts neither way (FR-16-02). - **Values, not counts.** Each record is read back as the fixture showed - it: the list pages, each invoice's JSON and CSV exports, the customer's + it: every field of its row on the list pages, each invoice's JSON and CSV exports, the customer's export, and the old invoice priced again. A key or column only the changed tree has is the change's own, and is no loss (FR-16-04). - **Lost and missing.** A changed tree that will not open the file, or diff --git a/docs/coverage.md b/docs/coverage.md index 0f09317..d2d305f 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,10 +239,10 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks"
`judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
`judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
`judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
`report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
`report.py` "named pairs are read for every metric of a table" | -| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "the check loop is not kept on the build task's readings alone"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a round running none of the registered pairs prints none of them" | -| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command" | +| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "the check loop is not kept on the build task's readings alone"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
`report.py` "a round running none of the registered pairs prints none of them" | +| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
`report.py` "a task's reading left out of the report counts no template use on that task" | diff --git a/docs/requirements.md b/docs/requirements.md index 49aa728..724caec 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,13 +252,13 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | -| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial drops by at least 10 % on each, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | -| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from each trial's transcripts on that task, a file read by a read or a reading command, a wildcard standing for each file it matches, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | +| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | +| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | ## Quality requirements diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 847680a..0a2d94d 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -966,6 +966,45 @@ def invoice_reading(path): "csv": csv_text.get_data(as_text=True)} +ROW_OPEN = re.compile(r"<(?:tr|li|p)\b[^>]*>", re.IGNORECASE) +ROW_CLOSE = re.compile(r"", re.IGNORECASE) +CELL_OPEN = re.compile(r"]*>", re.IGNORECASE) +TAG = re.compile(r"<[^>]+>") + + +def row_cells(text, key): + """The text of each cell of the first row a page shows `key` in, as the + page writes it, a row being a table row, a list item or a paragraph; + None where no row shows it.""" + for chunk in ROW_OPEN.split(text)[1:]: + chunk = ROW_CLOSE.split(chunk)[0] + cells = [" ".join(html.unescape(TAG.sub(" ", cell)).split()) + for cell in CELL_OPEN.split(chunk)] + cells = [cell for cell in cells if cell] + if any(key in cell for cell in cells): + return cells + return None + + +def row_keys(): + """The value each seeded record's row is found by, on each list page.""" + return { + "/products": [item["sku"] for item in UPGRADE_PRODUCTS], + "/customers": [UPGRADE_CUSTOMER["email"]], + "/rules": [item["rule_id"] for item in UPGRADE_RULES], + "/jurisdictions": [UPGRADE_JURISDICTION["code"]]} + + +def shown_rows(): + """Every seeded record's row as its list page shows it: each field the + page writes, its price, rate or kind among them, by page and key.""" + rows = {} + for path, keys in row_keys().items(): + text = page(client, path).get_data(as_text=True) + rows[path] = {key: row_cells(text, key) for key in keys} + return rows + + def seed_upgrade(): """Seed the records through the fixture's forms and read each back as the fixture shows it; the readings, or why the fixture could not.""" @@ -1021,7 +1060,7 @@ def seed_upgrade(): customer_export = json.loads(export.get_data(as_text=True)) except ValueError: return None, "the seeded customer's export is not JSON" - return {"invoices": invoices, "pages": pages, + return {"invoices": invoices, "pages": pages, "rows": shown_rows(), "customer": {"id": customer, "export": customer_export}}, None @@ -1078,6 +1117,17 @@ def data_upgrade(seeded): continue failures += ["%s no longer lists %s" % (path, value) for value in values if value not in shown] + + # Each field the fixture's page wrote of a seeded record, its price + # or rate as much as its name, still shows in that record's row; a + # column the change adds is its own, and is no loss. + text = answer.get_data(as_text=True) + for key, cells in (seeded.get("rows") or {}).get(path, {}).items(): + now = row_cells(text, key) + if not cells or now is None: + continue + failures += ["%s no longer shows %r for %s" % (path, cell, key) + for cell in cells if cell not in " ".join(now)] for old in seeded["invoices"]: now = invoice_reading(old["path"]) if not 200 <= now["status"] < 300: @@ -1901,7 +1951,9 @@ def create_app(database): # all of that. Each other mode plants one fault in version 2 alone: # `unmigrated` adds the columns to new files only and then reads them, # `dropping` rebuilds an old file empty, `rewriting` migrates and resets every -# jurisdiction's rate, rows all kept, `fragile` cannot read an old +# jurisdiction's rate, rows all kept, `rerating` migrates and clears every +# jurisdiction's listed rates, which no invoice prices with and only its page +# shows, `fragile` cannot read an old # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` # links no customer, so nothing can be seeded. @@ -1968,7 +2020,7 @@ def __init__(self, database): "CREATE TABLE IF NOT EXISTS rules (rule_id TEXT PRIMARY KEY, " "kind TEXT, sku TEXT, detail TEXT%s);" "CREATE TABLE IF NOT EXISTS jurisdictions (code TEXT PRIMARY " - "KEY, name TEXT, default_rate TEXT%s);" + "KEY, name TEXT, default_rate TEXT, rates TEXT%s);" "CREATE TABLE IF NOT EXISTS invoices (id INTEGER PRIMARY KEY, " "jurisdiction TEXT, customer TEXT, coupons TEXT);" "CREATE TABLE IF NOT EXISTS lines (invoice INTEGER, position " @@ -1980,6 +2032,8 @@ def __init__(self, database): if MODE == "rewriting": connection.execute("UPDATE jurisdictions SET " "default_rate = '0'") + if MODE == "rerating": + connection.execute("UPDATE jurisdictions SET rates = ''") if not connection.execute("SELECT * FROM admin").fetchone(): connection.execute("INSERT INTO admin VALUES (?)", ( os.environ.get("TARIFF_ADMIN_PASSWORD"),)) @@ -1987,20 +2041,21 @@ def __init__(self, database): connection.executemany("INSERT INTO products VALUES " "(?, ?, ?, ?)", SEED) for code, rate in (("DE", "0.19"), ("IE", "0.23")): - self.add_jurisdiction(connection, code, code, rate) + self.add_jurisdiction(connection, code, code, rate, "") connection.commit() connection.close() def connect(self): return sqlite3.connect(self.database) - def add_jurisdiction(self, connection, code, name, rate): + def add_jurisdiction(self, connection, code, name, rate, rates): if VERSION == 2: connection.execute("INSERT INTO jurisdictions VALUES " - "(?, ?, ?, ?)", (code, name, rate, "{}")) + "(?, ?, ?, ?, ?)", (code, name, rate, rates, + "{}")) else: - connection.execute("INSERT INTO jurisdictions VALUES (?, ?, ?)", - (code, name, rate)) + connection.execute("INSERT INTO jurisdictions VALUES " + "(?, ?, ?, ?)", (code, name, rate, rates)) def test_client(self): return Client(self) @@ -2061,16 +2116,19 @@ def dispatch(self, connection, path, method, data): def listing(self, connection, table): if table == "products": - rows = connection.execute("SELECT sku, name FROM products") + rows = connection.execute("SELECT sku, name, unit_price FROM " + "products") elif table == "rules": rows = connection.execute("SELECT rule_id, kind FROM rules") elif VERSION == 2: - rows = connection.execute("SELECT code, name, caps FROM " - "jurisdictions") + rows = connection.execute("SELECT code, name, default_rate, " + "rates, caps FROM jurisdictions") else: - rows = connection.execute("SELECT code, name FROM jurisdictions") - return "".join("

%s

" % " ".join(str(value) for value in row) - for row in rows) + rows = connection.execute("SELECT code, name, default_rate, " + "rates FROM jurisdictions") + return "%s
" % "".join( + "%s" % "".join("%s" % value for value in row) + for row in rows) def create(self, connection, table, data): if table == "products": @@ -2090,7 +2148,8 @@ def create(self, connection, table, data): data.get("sku"), detail)) else: self.app.add_jurisdiction(connection, data["code"], data["name"], - data["default_rate"]) + data["default_rate"], + data.get("rates") or "") return Response(302, "", {"Location": "/" + table}) def customers(self, connection, parts, method, data): @@ -2125,7 +2184,7 @@ def priced(self, connection, jurisdiction, coupons, lines): raise LookupError(jurisdiction) rate = decimal.Decimal(found[2]) if VERSION == 2: - json.loads(found[3] if MODE == "fragile" else found[3] or "{}") + json.loads(found[4] if MODE == "fragile" else found[4] or "{}") rules = [(kind, sku, json.loads(detail)) for kind, sku, detail in connection.execute("SELECT kind, sku, detail FROM rules")] net = [] @@ -2201,8 +2260,8 @@ def create_app(database): ''' # The faults the data upgrade must catch at version 2, and what each loses. -UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "fragile", - "refusing") +UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", + "fragile", "refusing") def plant_upgrade(where, version, mode): @@ -2257,6 +2316,12 @@ def upgrade_self_checks(scratch): faults["rewriting"].get("passed") is False and any("no longer reads the same" in failure for failure in faults["rewriting"].get("failures") or [])), + ("a listed field changed by the migration, no invoice priced by it, " + "fails the upgrade", + faults["rerating"].get("passed") is False + and faults["rerating"].get("failures") == [ + "/jurisdictions no longer shows 'standard=0.2,reduced=0.05' " + "for UP"]), ("old invoices that break on the new field fail the upgrade", faults["fragile"].get("passed") is False and any("/invoices/" in failure for failure in diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 51a8363..8cda4ca 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -1941,9 +1941,8 @@ def write_report(root, trials, table, results, seed, out_dir, # A named round prints the readings it registered, each per task, the # templates read on each counted from that task's own transcripts. - registered = (registered_lines(tasks, seed, { - task: map_uses(root, trials, task) for task, _ in TASKS}) - if tasks else []) + registered = (registered_lines(tasks, seed, task_uses(root, tasks)) + if tasks else []) lines.extend(registered) lines.extend(["## What produced these numbers", ""]) @@ -2101,6 +2100,13 @@ def write_report(root, trials, table, results, seed, out_dir, return os.path.join(out_dir, report) +def task_uses(root, tasks): + """Each task's map use, read over that task's own trials, so a reading + left out of one task, as a reach leaves it, counts in none.""" + return {task: map_uses(root, view, task) + for task, _, view, _, _ in tasks} + + def finding_reading(tasks, trials, table, results, iso, seed, withdrawn=None): """What a named round's finding table reads, as (trials, table, contrasts, ISO reading, task): the run's own where its first task is @@ -5872,6 +5878,11 @@ def counted(arm, reads): uses.update(counted("lazysections", 2)) demand = text(plant(cheaper, flaky=("lazysections",)), {"build": uses, "change": uses}) + exact = cost_drop({"cost_usd": { + "label": "cost", "direction": DOWN, "values": { + CHECK_LOOP[0]: {block: 0.111105 for block in range(1, 6)}, + CHECK_LOOP[1]: {block: 0.12345 for block in range(1, 6)}}}}, + seed, CHECK_LOOP) builds_alone = text({name: dict(trial, change=None) for name, trial in plant(cheaper).items()}) @@ -5925,6 +5936,11 @@ def counted(arm, reads): ("the report and its full record print the registered readings", all("## The registered readings" in document and "**Kept.**" in document for document in documents)), + ("a cost drop of exactly 10 % keeps the gate, read from the " + "unrounded differences", + exact[0] >= COST_DROP and round(exact[0], 6) == COST_DROP + and check_loop_kept({task: {"cost": exact, "worse": []} + for task, _ in TASKS}) is True), ("a round running none of the registered pairs prints none of them", registered_lines(task_readings({ name: trial for name, trial in plant(cheaper).items() @@ -5962,16 +5978,16 @@ def line(message_id, block): SECTIONS_INTO, last)), call("Read", file_path="/pen/src/app.py")]} records = [] - for task, made in calls.items(): - workspace = os.path.join(scratch, "pen-%s" % task) + for block, (task, made) in itertools.product((1, 2), calls.items()): + workspace = os.path.join(scratch, "pen-%s-%d" % (task, block)) folder = os.path.join(root, "home", ".claude", "projects", project_folder(workspace)) os.makedirs(folder) with io.open(os.path.join(folder, "t.jsonl"), "w", encoding="utf-8") as handle: - for index, block in enumerate(made): - handle.write(line("m%d" % index, block)) - records.append({"arm": "lazysections", "trial": 1, "task": task, + for index, call_made in enumerate(made): + handle.write(line("m%d" % index, call_made)) + records.append({"arm": "lazysections", "trial": block, "task": task, "outcome": "completed", "workspace": workspace}) with io.open(os.path.join(root, "run-1.json"), "w", encoding="utf-8") as handle: @@ -5979,11 +5995,32 @@ def line(message_id, block): trials = {"lazysections-1": {}} counted = {task: templates_read(map_uses(root, trials, task), "lazysections") for task in calls} + + # Each task's uses are read over its own trials: the first trial's change + # reading left out, as a reach leaves it, counts on the change task + # nowhere, and its build left out counts on the build nowhere. + def standing(build, change): + def trial(name, kept_build, kept_change): + made = {"round": "C1", "scores": {"name": name}, "judge": None, + "judgings": [], "security": None, "quality": None, + "change": {"name": name} if kept_change else None} + return made if kept_build else change_only(made) + uses = task_uses(root, task_readings({ + "lazysections-1": trial("lazysections-1", build, change), + "lazysections-2": trial("lazysections-2", True, True)}, 1)) + return {task: sorted(found) for task, found in uses.items()} + dropped = (standing(True, False), standing(False, True)) shutil.rmtree(scratch, ignore_errors=True) return [("each task's templates read are counted from its own " "transcripts, a section file by a read or a shell command", len(sections) == 2 and folder != last and matched - and counted == {"build": 1.0, "change": 1.0 + len(matched)})] + and counted == {"build": 1.0, "change": 1.0 + len(matched)}), + ("a task's reading left out of the report counts no template " + "use on that task", + dropped == ({"build": ["lazysections-1", "lazysections-2"], + "change": ["lazysections-2"]}, + {"build": ["lazysections-2"], + "change": ["lazysections-1", "lazysections-2"]}))] def pair_contrast_checks(seed): @@ -7620,10 +7657,13 @@ def cost_drop(table, seed, pair): if left[index] is not None and right[index] is not None] base = statistics.fmean(paired) if paired else None interval = contrast.get("interval") or {} - if not base or contrast.get("mean") is None: + if not base or not contrast.get("pairs"): return None, None, None + + # The gate reads the paired differences as measured; the contrast's own + # mean is rounded for display, and a rounded mean can cross the gate. low, high = interval.get("low"), interval.get("high") - return (-contrast["mean"] / base, + return (-statistics.fmean(contrast["pairs"]) / base, None if high is None else -high / base, None if low is None else -low / base) From 2c953b5e36efe622606c108c462ef4930d95f540 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:45:18 +0200 Subject: [PATCH 07/18] fix(efficacy): Codex round 3 on the changed-tree scoring - the data upgrade compares each listed field as a whole cell, so a value kept only inside a longer one fails; extra columns stay allowed - a skill's SKILL.md read or shell-read counts as that skill used, once with its loading - C1's non-inferiority needs the lower bound strictly above minus the margin; the pilot rounds keep their own rule - the 10 % cost gate meets within 1e-9, the table's column and the decision reading the same test Refs #178, #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 6 +- docs/requirements.md | 6 +- tests/efficacy/quality.py | 20 +++++-- tests/efficacy/report.py | 119 +++++++++++++++++++++++++++++++++++--- 4 files changed, 132 insertions(+), 19 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index a0063a7..8ccf0b0 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,10 +239,10 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "a listed field kept only inside a longer one fails the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks"
`judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
`judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
`judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
`report.py` "each task's radar reads that task's trees against `none` on the same task"
`report.py` "the change task's radar reads its own security, not the build's"
`report.py` "a named round's build radar leaves the change targets to the change task's"
`report.py` "each task's radar shows its own mean billed cost per trial"
`report.py` "a pilot round draws one radar, its trials as they are"
`report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
`report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
`report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
`report.py` "named pairs are read for every metric of a table" | -| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "the check loop is not kept on the build task's readings alone"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
`report.py` "a round running none of the registered pairs prints none of them" | -| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
`report.py` "a task's reading left out of the report counts no template use on that task" | +| FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
`report.py` "the check loop is not kept on the build task's readings alone"
`report.py` "a cost drop under 10 % on one task does not keep the check loop"
`report.py` "an axis worse on either task does not keep the check loop"
`report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
`report.py` "an interval crossing the margin is inconclusive, never non-inferior"
`report.py` "the report and its full record print the registered readings"
`report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
`report.py` "a cost drop a float's error under 10 % meets the gate"
`report.py` "a cost drop a float's error under 10 % reads yes in the table and keeps the loop"
`report.py` "C1 reads an axis non-inferior only with its lower bound strictly above minus the margin"
`report.py` "a round running none of the registered pairs prints none of them" | +| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
`report.py` "an arm whose reads were not counted is not shown on demand"
`report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
`report.py` "a task's reading left out of the report counts no template use on that task"
`report.py` "a skill's file read or shell-read is that skill used, once with its loading" | diff --git a/docs/requirements.md b/docs/requirements.md index 92123cc..bfae58f 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,13 +252,13 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each compared as a whole cell, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | -| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound clears minus its margin, one crossing it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | -| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | +| FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, within 1e-9, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound lies strictly above minus its margin, one on or below it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | +| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, a skill's file read counted once with its loading, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | ## Quality requirements diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 0a2d94d..c456e9a 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1119,15 +1119,16 @@ def data_upgrade(seeded): for value in values if value not in shown] # Each field the fixture's page wrote of a seeded record, its price - # or rate as much as its name, still shows in that record's row; a - # column the change adds is its own, and is no loss. + # or rate as much as its name, still shows whole as a cell of that + # record's row, never only inside a longer one; a column the change + # adds is its own, and is no loss. text = answer.get_data(as_text=True) for key, cells in (seeded.get("rows") or {}).get(path, {}).items(): now = row_cells(text, key) if not cells or now is None: continue failures += ["%s no longer shows %r for %s" % (path, cell, key) - for cell in cells if cell not in " ".join(now)] + for cell in cells if cell not in now] for old in seeded["invoices"]: now = invoice_reading(old["path"]) if not 200 <= now["status"] < 300: @@ -1953,7 +1954,8 @@ def create_app(database): # `dropping` rebuilds an old file empty, `rewriting` migrates and resets every # jurisdiction's rate, rows all kept, `rerating` migrates and clears every # jurisdiction's listed rates, which no invoice prices with and only its page -# shows, `fragile` cannot read an old +# shows, `extending` appends a digit to them, the old rates still inside the +# new, `fragile` cannot read an old # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` # links no customer, so nothing can be seeded. @@ -2034,6 +2036,9 @@ def __init__(self, database): "default_rate = '0'") if MODE == "rerating": connection.execute("UPDATE jurisdictions SET rates = ''") + if MODE == "extending": + connection.execute("UPDATE jurisdictions SET rates = rates " + "|| '1' WHERE rates != ''") if not connection.execute("SELECT * FROM admin").fetchone(): connection.execute("INSERT INTO admin VALUES (?)", ( os.environ.get("TARIFF_ADMIN_PASSWORD"),)) @@ -2261,7 +2266,7 @@ def create_app(database): # The faults the data upgrade must catch at version 2, and what each loses. UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", - "fragile", "refusing") + "extending", "fragile", "refusing") def plant_upgrade(where, version, mode): @@ -2322,6 +2327,11 @@ def upgrade_self_checks(scratch): and faults["rerating"].get("failures") == [ "/jurisdictions no longer shows 'standard=0.2,reduced=0.05' " "for UP"]), + ("a listed field kept only inside a longer one fails the upgrade", + faults["extending"].get("passed") is False + and faults["extending"].get("failures") == [ + "/jurisdictions no longer shows 'standard=0.2,reduced=0.05' " + "for UP"]), ("old invoices that break on the new field fail the upgrade", faults["fragile"].get("passed") is False and any("/invoices/" in failure for failure in diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 805ea2f..e666a6a 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -41,7 +41,8 @@ from generate_arm import RECORDED, record_path # noqa: E402 from harness import (ARMS, ARMS_DIR, PROMPT, REGISTRATIONS, # noqa: E402 ROUND5_ARMS, ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, - ROUND5E_ARMS, SCORABLE, SECTIONS_INTO, TEMPLATES_ENV, + ROUND5E_ARMS, SCORABLE, SECTIONS_INTO, SKILLS_INTO, + TEMPLATES_ENV, VENDORED, VOIDING, TrialError, canonical, git, reach, read_transcripts, read_change_prompt, recorded_round, @@ -3295,6 +3296,12 @@ def round5d_section(trials, table, results, seed, margins, SECTION_OPERAND = re.compile(r"(" + re.escape(SECTIONS_INTO + "/") + r"[\w./*?\[\]-]+)") +# A skill's file named in an operand, by its path under the folder the arm +# installs its skills in: reading it reads the skill, as loading it does. +SKILL_OPERAND = re.compile(re.escape(SKILLS_INTO + "/") + + r"([\w.*?\[\]-]+/SKILL\.md)") +SKILL_FILE = "SKILL.md" + # A redirection that writes no file: to the null device, or of one stream # into another. Taken out of a command before it is read for a write. NULL_REDIRECT = re.compile( @@ -3774,6 +3781,12 @@ def mapped(templates): elif name == "Skill" and entry.get("skills"): skill = str(given.get("skill") or "").strip() found = [skill] if skill in known else [] + + # A skill's file read through a read or a shell command is that + # skill used, counted once with any loading of it. + elif name in SHELLS + ("Read",) and entry.get("skills"): + found = skill_reads(name, given, command, known, writes_at, + first_write, before) if name not in SHELLS and first_write is None: before.update(found) if first_write is None and (name in WRITES or writes_at is not None): @@ -3786,6 +3799,26 @@ def mapped(templates): else None, "by_subagent": by_subagent} +def skill_reads(name, given, command, known, writes_at, first_write, + before): + """The skills a read or a shell command reads the file of, by name, each + a shell command read before its first write added to `before`.""" + files = sorted("%s/%s" % (skill, SKILL_FILE) for skill in known) + if name == "Read": + path = str(given.get("file_path") or "").replace("\\", "/") + return [read.split("/")[0] for read in SKILL_OPERAND.findall(path) + if read.split("/")[0] in known] + found = [] + for index, read in shell_reads(command, files, SKILL_OPERAND): + skill = read.split("/")[0] + if skill in known: + found.append(skill) + if first_write is None and (writes_at is None + or index < writes_at): + before.add(skill) + return found + + def report_uses(root, trials, task="build"): """The map uses a report reads on `task`: every trial's, wherever the run holds an arm whose file points at a map, named round or not; None where @@ -5951,6 +5984,8 @@ def counted(arm, reads): CHECK_LOOP[0]: {block: 0.111105 for block in range(1, 6)}, CHECK_LOOP[1]: {block: 0.12345 for block in range(1, 6)}}}}, seed, CHECK_LOOP) + hairline = text(plant({("lazyref", "build"): 1.8, + ("lazyref", "change"): 0.9})) builds_alone = text({name: dict(trial, change=None) for name, trial in plant(cheaper).items()}) @@ -5973,6 +6008,10 @@ def counted(arm, reads): "axis worse", "**Kept.**" in kept and "| build task | 20 % |" in kept and "| change task | 20 % |" in kept), + ("a cost drop a float's error under 10 % reads yes in the table and " + "keeps the loop", + "**Kept.**" in hairline and hairline.count("| 10 % | 10 % to 10 % " + "| yes |") == 2), ("the check loop is not kept on the build task's readings alone", "**Not decided.**" in builds_alone and "| build task | 20 % |" in builds_alone), @@ -6160,6 +6199,56 @@ def planted_registry(repository, branch=REGISTRATION_BRANCH): return repository +def round3_checks(seed): + """A skill's file read is that skill used, once with its loading; C1's + non-inferiority needs the lower bound strictly above minus the margin; + and the cost gate meets 10 % within a float's error.""" + scratch = tempfile.mkdtemp(prefix="efficacy-report-skill-reads-") + planted = os.path.join(scratch, "skills.jsonl") + calls = [("Skill", {"skill": "base-quality"}), + ("Read", {"file_path": "C:\\pen\\.claude\\skills\\" + "base-quality\\SKILL.md"}), + ("Bash", {"command": "cat .claude/skills/backend-*/SKILL.md"}), + ("Bash", {"command": "ls .claude/skills"}), + ("Read", {"file_path": "/pen/.claude/skills/other/SKILL.md"})] + with io.open(planted, "w", encoding="utf-8", newline="\n") as handle: + for turn, (name, given) in enumerate(calls, 1): + handle.write(json.dumps({"type": "assistant", "message": { + "id": "m%d" % turn, "content": [{ + "type": "tool_use", "id": "t%d" % turn, "name": name, + "input": given}]}}) + "\n") + used = map_use([planted], "lazyskills", + ["base-quality", "backend-api", "backend-auth"]) + shutil.rmtree(scratch, ignore_errors=True) + + def states(low, high): + """The Reliability state of an interval at its margin.""" + return dict(axis_states({"iso:Reliability": {"a-b": { + "verdict": "held", "interval": {"low": low, "high": high}}}}, + "a-b"))["Reliability"] + margin = ISO_MARGINS["Reliability"] + hair = cost_drop({"cost_usd": { + "label": "cost", "direction": DOWN, "values": { + CHECK_LOOP[0]: {block: 0.90 for block in range(1, 6)}, + CHECK_LOOP[1]: {block: 1.00 for block in range(1, 6)}}}}, + seed, CHECK_LOOP) + return [ + ("a skill's file read or shell-read is that skill used, once with " + "its loading", + templates_read({"lazyskills-1": used}, "lazyskills") == 3.0 + and sorted({skill for _, skill in used["uses"]}) + == ["backend-api", "backend-auth", "base-quality"]), + ("C1 reads an axis non-inferior only with its lower bound strictly " + "above minus the margin", + states(-margin, -margin) == "inconclusive" + and states(-margin + 0.1, 0.0) == "non-inferior"), + ("a cost drop a float's error under 10 % meets the gate", + hair[0] < COST_DROP and meets_cost_drop(hair[0]) + and check_loop_kept({task: {"cost": hair, "worse": []} + for task, _ in TASKS}) is True), + ] + + def change_only_checks(): """A named round's change task is read whether or not its build trial was scored or reached, on rows of its own; a pilot round's keeps @@ -7722,6 +7811,16 @@ def task_lines(reading, images): # shown beside it and decides nothing. COST_DROP = 0.10 +# How far under COST_DROP a drop may read and still meet it: a share worked +# out in floating point, as 0.90 against 1.00 is, lands a hair under. +COST_TOLERANCE = 1e-9 + + +def meets_cost_drop(drop): + """Whether a cost drop meets the check loop's gate, within the + tolerance; the table's column and the decision both read this.""" + return drop is not None and drop >= COST_DROP - COST_TOLERANCE + # What no axis flagged worse reads as: the absence of a flag, never a claim # that nothing got worse. NO_DEGRADATION = "no degradation detected under the registered rule" @@ -7737,17 +7836,20 @@ def registered_pairs(): def axis_states(iso_results, label): """Each ISO axis of one pair on one task, as (axis, state): `worse` where the whole interval lies past the margin downward, - `non-inferior` where its lower bound clears minus the margin, - `inconclusive` where it crosses the margin, None where unread.""" + `non-inferior` where its lower bound lies strictly above minus the + margin, `inconclusive` otherwise, None where unread.""" states = [] for axis, _ in ISO_AXES: contrast = iso_results.get("iso:" + axis, {}).get(label) or {} - held = contrast.get("non_inferior") or {} + low = (contrast.get("interval") or {}).get("low") + + # Round C1 registered the strict bound: a lower bound on minus the + # margin has not cleared it. The pilot rounds keep their own rule. if contrast.get("verdict") == "worse": state = "worse" - elif contrast.get("verdict") not in COUNTED_VERDICTS: + elif contrast.get("verdict") not in COUNTED_VERDICTS or low is None: state = None - elif held.get("within"): + elif low > -ISO_MARGINS[axis]: state = "non-inferior" else: state = "inconclusive" @@ -7828,7 +7930,7 @@ def check_loop_kept(reads): A task that misses either is enough to refuse it; keeping it needs both tasks read, so it is None while one is not.""" if any(read["worse"] or (read["cost"][0] is not None - and read["cost"][0] < COST_DROP) + and not meets_cost_drop(read["cost"][0])) for read in reads.values()): return False if set(reads) != {task for task, _ in TASKS} or any( @@ -7887,7 +7989,7 @@ def registered_lines(tasks, seed, uses_by_task): lines.append("| %s | %s | %s to %s | %s | %s | %s |" % ( label, percent(drop), percent(low), percent(high), "—" if drop is None else - ("yes" if drop >= COST_DROP else "no"), + ("yes" if meets_cost_drop(drop) else "no"), worse_words(read), non_inferior_words(read))) kept = check_loop_kept(loop) lines.extend(["", "**%s.** %s Keeping the loop is no claim that " @@ -10148,6 +10250,7 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in registered_checks(seed)) checks.extend((label, ok, ok) for label, ok in task_use_checks()) checks.extend((label, ok, ok) for label, ok in pair_contrast_checks(seed)) + checks.extend((label, ok, ok) for label, ok in round3_checks(seed)) checks.extend((label, ok, ok) for label, ok in change_finding_checks(seed)) for label, ok, got in checks: From a9eafa2f44939183dacd4071ff4e5864b8b8b52b Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:32:25 +0200 Subject: [PATCH 08/18] fix(efficacy): Codex round 4 on the changed-tree scoring - a changed tree's scope reads its index as the change task left it, captured before the install, the suites or churn's intent-to-add, so the scorer's own build output is no unasked artifact - a changed tree's public surface is read against the build's names and each the pinned change prompt calls on the package, ThresholdRule among them; the build is read as before Refs #178. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/probes.py | 7 +- tests/efficacy/score.py | 168 +++++++++++++++++++++++++++++++++++---- 4 files changed, 160 insertions(+), 19 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 8ccf0b0..059f969 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -236,7 +236,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is" | +| FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
`score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
`score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
`score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | | FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "a listed field kept only inside a longer one fails the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | diff --git a/docs/requirements.md b/docs/requirements.md index bfae58f..b8b80b8 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -249,7 +249,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, and its security reading filed beside its score. | Scorer | +| FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, its scope read from its index as the change task left it, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | | FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each compared as a whole cell, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | diff --git a/tests/efficacy/probes.py b/tests/efficacy/probes.py index 5d6a246..946b44f 100644 --- a/tests/efficacy/probes.py +++ b/tests/efficacy/probes.py @@ -680,13 +680,14 @@ def form_probe(): ''' -def structure(ctx, workspace, roots, seen): - """The structural design measures, as one probe inside the trial's venv.""" +def structure(ctx, workspace, roots, seen, required=REQUIRED_NAMES): + """The structural design measures, as one probe inside the trial's venv, + the public surface read against `required`.""" if not roots: return ctx.absent("no source roots were discovered", seen=seen) script = os.path.join(workspace, ".score-structure.py") with io.open(script, "w", encoding="utf-8") as handle: - handle.write(STRUCTURE_SCRIPT % {"required": list(REQUIRED_NAMES)}) + handle.write(STRUCTURE_SCRIPT % {"required": list(required)}) outcome = ctx.run([ctx.python, script, json.dumps(roots)], cwd=workspace) if outcome["failed"]: return ctx.absent("the structure probe %s" % outcome["failed"], diff --git a/tests/efficacy/score.py b/tests/efficacy/score.py index 71a3d45..55aa901 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -40,8 +40,9 @@ import probes # noqa: E402 from harness import (INTERFACE_MODULES, SCORABLE, LiveRunError, # noqa: E402 TrialError, canonical, claim_area, claim_refusal_check, - frozen_top, name_of, release_area, remove_tree, - scorable_trials, scoring_area, task_folder) + frozen_top, name_of, read_change_prompt, release_area, + remove_tree, scorable_trials, scoring_area, + task_folder) HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPT = os.path.basename(__file__) @@ -1095,13 +1096,23 @@ def kind_of(name): return None -def scope(workspace, roots): - """Files, lines, app and test code, and artifacts nobody asked for.""" +def tracked_files(workspace): + """The files the workspace's index holds, as the trial left it; or an + absent metric where it is no readable git checkout.""" tracked = run(["git", "-C", workspace, "ls-files"], timeout=120) if tracked["failed"] or tracked["status"] != 0: return absent("the workspace is not a readable git checkout: %s" % tracked["stderr"][:300]) - files = [line for line in tracked["stdout"].splitlines() if line.strip()] + return [line for line in tracked["stdout"].splitlines() if line.strip()] + + +def scope(workspace, roots, files=None): + """Files, lines, app and test code, and artifacts nobody asked for; + `files` the tracked files as read before scoring touched the index, by + default read now.""" + files = tracked_files(workspace) if files is None else files + if isinstance(files, dict): + return files unasked = [name for name in files if any(token in os.path.basename(name).upper() for token in UNASKED)] @@ -1244,9 +1255,11 @@ def score_trial(record, options, suite, lock): return scores -def measure_code(scores, venv, workspace, options, lock, source): +def measure_code(scores, venv, workspace, options, lock, source, + required=probes.REQUIRED_NAMES): """The static battery, the structure and web probes and adherence, read - into `scores` from the installed tree once its suites have run.""" + into `scores` from the installed tree once its suites have run; the + public surface is read against `required`.""" roots, seen = scores["discovery"]["roots"], scores["seen"] scores["battery"] = install_battery(venv, lock) @@ -1280,7 +1293,7 @@ def measure_code(scores, venv, workspace, options, lock, source): scores["web"] = absent(moved) else: scores["structure"] = probes.structure(context, workspace, roots, - seen) + seen, required) if options.web: scores["web"] = probes.web_quality(context, workspace) else: @@ -1347,6 +1360,10 @@ def score_change_trial(record, options, suite, lock): workspace = extract((record.get("frozen") or {}).get("tarball"), os.path.join(scoring, "tree"), frozen) files = python_files(workspace) + + # The index as the change task left it, before the install, the suites + # or churn's intent-to-add can put a file of their own in it. + tracked = tracked_files(workspace) venv = create_venv(os.path.join(scoring, "venv")) # The fixture is named by its hash and with the readings it qualified @@ -1392,14 +1409,29 @@ def score_change_trial(record, options, suite, lock): scores["churn"] = (churn(workspace, record["base"]) if record.get("base") else absent("the change record names no starting " "commit")) - measure_code(scores, venv, workspace, options, lock, source) - scores["scope"] = scope(workspace, roots) + measure_code(scores, venv, workspace, options, lock, source, + change_required_names()) + scores["scope"] = scope(workspace, roots, tracked) scores["cost"] = cost(record) scores["flagged"] = metric_flags(scores) drop_venv(venv) return scores +# A name the pinned change prompt has other software call, as +# `tariff.ThresholdRule(...)`. +PROMPTED_NAME = re.compile(r"\btariff\.([A-Za-z_]\w*)\(") + + +def change_required_names(prompt=None): + """The names a changed tree's public surface is read against: the + build's, then each the pinned change prompt calls on the package.""" + text = read_change_prompt() if prompt is None else prompt + added = [name for name in dict.fromkeys(PROMPTED_NAME.findall(text)) + if name not in probes.REQUIRED_NAMES] + return tuple(probes.REQUIRED_NAMES) + tuple(added) + + def module_whole(report, module): """Whether a suite report shows a module passed whole: some check passed and none failed, errored or was skipped; a module it does not @@ -1814,7 +1846,7 @@ def fixture(failed=()): ] -def change_breadth_checks(scratch): +def change_breadth_checks(scratch, folder="breadth"): """A change task is scored on every reading a build is, with its own suites and churn in place of the build's one suite.""" import argparse as _argparse @@ -1835,14 +1867,14 @@ def change_breadth_checks(scratch): "install_battery": lambda venv, lock: {"missing": "stubbed"}, "package_moved": lambda before, after: None, "adherence": lambda workspace, scores: measured(1.0), - "scope": lambda workspace, roots: measured({}), + "scope": lambda workspace, roots, files=None: measured({}), "churn": lambda workspace, base: measured({}), "drop_venv": lambda venv: None, } saved = {name: globals()[name] for name in stubs} record = {"arm": "none", "trial": 1, "base": "abc", "frozen": { "tarball": "none-1.tar"}, "fixture": None} - options = _argparse.Namespace(root=os.path.join(scratch, "breadth"), + options = _argparse.Namespace(root=os.path.join(scratch, folder), web=False) suite = {"revision": "stub", "path": scratch} globals().update(stubs) @@ -1858,6 +1890,113 @@ def change_breadth_checks(scratch): "churn"} <= set(change))] +def change_scope_checks(scratch): + """A changed tree's scope is its index as the change task left it, so a + file the scorer's own install or tests write is no unasked artifact.""" + import argparse as _argparse + tree = os.path.join(scratch, "change-scope", "tree") + os.makedirs(os.path.join(tree, "tariff")) + with io.open(os.path.join(tree, "tariff", "app.py"), "w", + encoding="utf-8") as handle: + handle.write("VALUE = 1\n") + for argv in (["init", "-q"], ["add", "-A"], + ["-c", "user.name=self-test", + "-c", "user.email=self-test@example.invalid", + "commit", "-q", "-m", "change"]): + run(["git", "-C", tree] + argv, timeout=120) + base = run(["git", "-C", tree, "rev-parse", "HEAD"])["stdout"].strip() + + def installed(venv, workspace): + """An install that leaves its build output in the tree, as pip's + does.""" + built = os.path.join(workspace, "build", "lib", "tariff") + os.makedirs(built, exist_ok=True) + with io.open(os.path.join(built, "app.py"), "w", + encoding="utf-8") as handle: + handle.write("VALUE = 1\n") + return measured(True) + stubs = { + "extract": lambda tarball, into, name: tree, + "python_files": lambda workspace: [], + "create_venv": lambda where: where, + "venv_version": lambda venv: "3.12.0", + "install_trial": installed, + "package_source": lambda venv: "site", + "boot_check": lambda venv, workspace: measured(True), + "discover_roots": lambda venv, workspace: { + "roots": [], "how": "stub", "installed": None}, + "pip": lambda venv, *args, **kwargs: None, + "run_hidden_suite": lambda venv, suite, workspace, which: measured( + 1.0, report={"modules": {}}), + "install_battery": lambda venv, lock: {"missing": "stubbed"}, + "package_moved": lambda before, after: None, + "adherence": lambda workspace, scores: measured(1.0), + "drop_venv": lambda venv: None, + } + saved = {name: globals()[name] for name in stubs} + record = {"arm": "none", "trial": 1, "base": base, "frozen": { + "tarball": "none-1.tar"}, "fixture": None} + options = _argparse.Namespace(root=os.path.join(scratch, "change-scope"), + web=False) + globals().update(stubs) + try: + change = score_change_trial(record, options, + {"revision": "stub", "path": scratch}, + "lock") + finally: + globals().update(saved) + read = (change.get("scope") or {}).get("value") or {} + return [("a file the scorer's install writes is no unasked artifact of a " + "changed tree", + read.get("unasked_artifacts") == 0 + and read.get("tracked_files") == 1)] + + +def change_surface_checks(scratch): + """A changed tree's public surface is read against the build's names and + the change's own, the build's left as it was.""" + def surface(names): + workspace = os.path.join(scratch, "surface-%d" % len(names)) + package = os.path.join(workspace, "tariff") + os.makedirs(package) + with io.open(os.path.join(package, "__init__.py"), "w", + encoding="utf-8") as handle: + handle.write("".join("def %s():\n pass\n\n\n" % name + for name in names)) + reading = probes.structure(probes.planted_context(), workspace, + [package], {"files": 1}, + change_required_names()) + return (reading.get("value") or {}).get("surface") or {} + built = list(probes.REQUIRED_NAMES) + changed = surface(built + ["ThresholdRule"]) + unchanged = surface(built) + + # The required names each task hands the structure probe, as scored. + handed = {} + real = probes.structure + + def recording(ctx, workspace, roots, seen, required=None): + handed.setdefault("calls", []).append(required) + return real(ctx, workspace, roots, seen, required) + probes.structure = recording + try: + change_breadth_checks(scratch, "surface-breadth") + finally: + probes.structure = real + calls = handed.get("calls") or [] + return [ + ("a changed tree with the change's names exports no extra one, and " + "one without them misses each", + changed.get("extra") == [] and changed.get("missing") == [] + and unchanged.get("missing") == ["ThresholdRule"]), + ("the build is read against the build's names, the change against " + "the change's too", + len(calls) == 2 and tuple(calls[0]) == probes.REQUIRED_NAMES + and tuple(calls[1]) == change_required_names() + and "ThresholdRule" in calls[1]), + ] + + PLANTED_SEEDING_APP = '''\ import os @@ -2240,7 +2379,8 @@ def self_test(): + adherence_checks(scratch) + python_files_checks(scratch) + scope_checks(scratch) + revision_checks(scratch) - + interface_checks() + change_breadth_checks(scratch)) + + interface_checks() + change_breadth_checks(scratch) + + change_scope_checks(scratch) + change_surface_checks(scratch)) dropped = create_venv(os.path.join(scratch, "dropped")) drop_venv(dropped) checks.append(("a scored trial's environment is dropped", From 685e37dd0c2a3cfe589d92f1e5df00c7bdf0a6d4 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:58:17 +0200 Subject: [PATCH 09/18] fix(efficacy): Codex round 5 on the data upgrade - after the upgrade the probe also posts a capped jurisdiction and a threshold rule through the changed app's forms and reads them back, so a schema changed for new files alone fails on an old one - each seeded row is read as whole values, split on white space and `,;|`, the same for table rows, list items and paragraphs; every old value must still show whole, and a value the change adds is allowed Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 127 ++++++++++++++++++++++++-------------- 3 files changed, 82 insertions(+), 49 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 059f969..5ffff39 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,7 +239,7 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
`score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
`score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
`score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
`score.py` "an interface module the change broke reads 0 and is named"
`score.py` "a skipped or unrun interface module is not kept"
`score.py` "a module the fixture already failed is inherited, not the change's"
`score.py` "a module the change repaired reads repaired"
`score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
`harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
`security.py` "a changed tree that does not install loses its probes, as a build's does"
`quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "a listed field kept only inside a longer one fails the upgrade"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
`quality.py` "a schema change shipped without a migration fails the upgrade"
`quality.py` "an old database rebuilt empty fails the upgrade"
`quality.py` "rows all kept with their values changed fail the upgrade"
`quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
`quality.py` "a listed field kept only inside a longer one fails the upgrade"
`quality.py` "a list-item row with a value the change adds keeps every old one"
`quality.py` "a schema changed for new files alone fails on the change's own fields"
`quality.py` "old invoices that break on the new field fail the upgrade"
`quality.py` "a version 2 that will not open the old database loses the upgrade"
`quality.py` "every planted upgrade fault fails"
`quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
`quality.py` "a change task with no starting commit leaves the upgrade missing"
`quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
`judge.py` "a change task's trees are found by their trial, apart from the build's"
`judge.py` "a changed tree's bundle naming its trial in a path leaks"
`judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
`judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
`judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
`report.py` "a change reading left out takes its own readings along"
`report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
`report.py` "a pilot round's table reads no change-task target"
`report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
`report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
`reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
`reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | diff --git a/docs/requirements.md b/docs/requirements.md index b8b80b8..2d3d5ea 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,7 +252,7 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, its scope read from its index as the change task left it, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each compared as a whole cell, an old invoice does not open or price as it did, or the upgraded file refuses new records; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, however the row is marked up, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index c456e9a..083554b 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -972,17 +972,21 @@ def invoice_reading(path): TAG = re.compile(r"<[^>]+>") -def row_cells(text, key): - """The text of each cell of the first row a page shows `key` in, as the - page writes it, a row being a table row, a list item or a paragraph; - None where no row shows it.""" +# What a row's text is split into whole values on: white space and the +# separators a page writes a list in, so `standard=0.2` stays one value. +TOKEN_SPLIT = re.compile(r"[\s,;|]+") + + +def row_tokens(text, key): + """The whole values the first row a page shows `key` in writes, in + order, a row being a table row, a list item or a paragraph, however its + cells are marked up; None where no row shows it.""" for chunk in ROW_OPEN.split(text)[1:]: chunk = ROW_CLOSE.split(chunk)[0] - cells = [" ".join(html.unescape(TAG.sub(" ", cell)).split()) - for cell in CELL_OPEN.split(chunk)] - cells = [cell for cell in cells if cell] - if any(key in cell for cell in cells): - return cells + tokens = [token for token in TOKEN_SPLIT.split(html.unescape( + TAG.sub(" ", chunk))) if token] + if key in tokens: + return tokens return None @@ -1001,7 +1005,7 @@ def shown_rows(): rows = {} for path, keys in row_keys().items(): text = page(client, path).get_data(as_text=True) - rows[path] = {key: row_cells(text, key) for key in keys} + rows[path] = {key: row_tokens(text, key) for key in keys} return rows @@ -1118,17 +1122,17 @@ def data_upgrade(seeded): failures += ["%s no longer lists %s" % (path, value) for value in values if value not in shown] - # Each field the fixture's page wrote of a seeded record, its price - # or rate as much as its name, still shows whole as a cell of that - # record's row, never only inside a longer one; a column the change - # adds is its own, and is no loss. + # Each value the fixture's page wrote of a seeded record, its price + # or rate as much as its name, still shows whole in that record's + # row, never only inside a longer one; a value the change adds is + # its own, and is no loss. text = answer.get_data(as_text=True) - for key, cells in (seeded.get("rows") or {}).get(path, {}).items(): - now = row_cells(text, key) - if not cells or now is None: + for key, tokens in (seeded.get("rows") or {}).get(path, {}).items(): + now = row_tokens(text, key) + if not tokens or now is None: continue - failures += ["%s no longer shows %r for %s" % (path, cell, key) - for cell in cells if cell not in now] + failures += ["%s no longer shows %r for %s" % (path, token, key) + for token in tokens if token not in now] for old in seeded["invoices"]: now = invoice_reading(old["path"]) if not 200 <= now["status"] < 300: @@ -1186,7 +1190,16 @@ def data_upgrade(seeded): "rates": "standard=0.1"}), ("/rules", "rule_id", {"rule_id": "u-pct-after", "kind": "percentage", "sku": "UPG-2", - "percent": "3"})) + "percent": "3"}), + + # And through the fields the change added, which a schema changed + # for new files alone refuses on an old one. + ("/jurisdictions", "code", { + "code": "U3", "name": "Upgradia Capped", "default_rate": "0.2", + "rates": "standard=0.2,reduced=0.05", "caps": "reduced=50.00"}), + ("/rules", "rule_id", {"rule_id": "u-threshold", + "kind": "threshold", "sku": "", + "percent": "5", "minimum": "200.00"})) for path, key, body in written: created(path, body) if body[key] not in text_of(page(client, path)): @@ -1955,10 +1968,13 @@ def create_app(database): # jurisdiction's rate, rows all kept, `rerating` migrates and clears every # jurisdiction's listed rates, which no invoice prices with and only its page # shows, `extending` appends a digit to them, the old rates still inside the -# new, `fragile` cannot read an old +# new, `fresh` adds the columns to new files alone and reads an old one +# without them, refusing only a record that sets one, `fragile` cannot read +# an old # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` -# links no customer, so nothing can be seeded. +# links no customer, so nothing can be seeded. `items`, at either version, +# lists jurisdictions as list items rather than table rows, and is sound. UPGRADE_APP = '''import decimal import json import os @@ -2027,7 +2043,7 @@ def __init__(self, database): "jurisdiction TEXT, customer TEXT, coupons TEXT);" "CREATE TABLE IF NOT EXISTS lines (invoice INTEGER, position " "INTEGER, sku TEXT, quantity INTEGER);" % (added, capped)) - if stale and MODE not in ("unmigrated", "dropping"): + if stale and MODE not in ("unmigrated", "dropping", "fresh"): for table, column in ADDED: connection.execute("ALTER TABLE %s ADD COLUMN %s TEXT" % (table, column)) @@ -2053,14 +2069,16 @@ def __init__(self, database): def connect(self): return sqlite3.connect(self.database) - def add_jurisdiction(self, connection, code, name, rate, rates): - if VERSION == 2: - connection.execute("INSERT INTO jurisdictions VALUES " - "(?, ?, ?, ?, ?)", (code, name, rate, rates, - "{}")) - else: - connection.execute("INSERT INTO jurisdictions VALUES " - "(?, ?, ?, ?)", (code, name, rate, rates)) + def add_jurisdiction(self, connection, code, name, rate, rates, + caps=None): + names, values = ["code", "name", "default_rate", "rates"], [ + code, name, rate, rates] + if VERSION == 2 and (caps is not None or "caps" in columns( + connection, "jurisdictions")): + names.append("caps") + values.append(caps or "{}") + connection.execute("INSERT INTO jurisdictions (%s) VALUES (%s)" % ( + ", ".join(names), ", ".join("?" for _ in names)), values) def test_client(self): return Client(self) @@ -2125,12 +2143,16 @@ def listing(self, connection, table): "products") elif table == "rules": rows = connection.execute("SELECT rule_id, kind FROM rules") - elif VERSION == 2: + elif VERSION == 2 and "caps" in columns(connection, "jurisdictions"): rows = connection.execute("SELECT code, name, default_rate, " "rates, caps FROM jurisdictions") else: rows = connection.execute("SELECT code, name, default_rate, " "rates FROM jurisdictions") + if MODE == "items": + return "
    %s
" % "".join( + "
  • %s
  • " % " ".join(str(value) for value in row) + for row in rows) return "%s
    " % "".join( "%s" % "".join("%s" % value for value in row) for row in rows) @@ -2143,18 +2165,19 @@ def create(self, connection, table, data): elif table == "rules": detail = json.dumps({key: data.get(key) for key in ( "percent", "buy", "pay", "code", "amount")}) - if VERSION == 2: - connection.execute("INSERT INTO rules VALUES (?, ?, ?, ?, ?)", - (data["rule_id"], data["kind"], - data.get("sku"), detail, None)) - else: - connection.execute("INSERT INTO rules VALUES (?, ?, ?, ?)", - (data["rule_id"], data["kind"], - data.get("sku"), detail)) + names, values = ["rule_id", "kind", "sku", "detail"], [ + data["rule_id"], data["kind"], data.get("sku"), detail] + if VERSION == 2 and (data.get("minimum") or "minimum" in columns( + connection, "rules")): + names.append("minimum") + values.append(data.get("minimum")) + connection.execute("INSERT INTO rules (%s) VALUES (%s)" % ( + ", ".join(names), ", ".join("?" for _ in names)), values) else: self.app.add_jurisdiction(connection, data["code"], data["name"], data["default_rate"], - data.get("rates") or "") + data.get("rates") or "", + data.get("caps")) return Response(302, "", {"Location": "/" + table}) def customers(self, connection, parts, method, data): @@ -2189,7 +2212,8 @@ def priced(self, connection, jurisdiction, coupons, lines): raise LookupError(jurisdiction) rate = decimal.Decimal(found[2]) if VERSION == 2: - json.loads(found[4] if MODE == "fragile" else found[4] or "{}") + caps = found[4] if len(found) > 4 else "{}" + json.loads(caps if MODE == "fragile" else caps or "{}") rules = [(kind, sku, json.loads(detail)) for kind, sku, detail in connection.execute("SELECT kind, sku, detail FROM rules")] net = [] @@ -2266,7 +2290,7 @@ def create_app(database): # The faults the data upgrade must catch at version 2, and what each loses. UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", - "extending", "fragile", "refusing") + "extending", "fresh", "fragile", "refusing") def plant_upgrade(where, version, mode): @@ -2303,6 +2327,7 @@ def upgrade_self_checks(scratch): faults = {mode: upgrade_reading(scratch, "sound", mode) for mode in UPGRADE_FAULTS} unseeded = upgrade_reading(scratch, "unlisting", "sound") + items = upgrade_reading(scratch, "items", "items") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) return [ @@ -2325,13 +2350,21 @@ def upgrade_self_checks(scratch): "fails the upgrade", faults["rerating"].get("passed") is False and faults["rerating"].get("failures") == [ - "/jurisdictions no longer shows 'standard=0.2,reduced=0.05' " - "for UP"]), + "/jurisdictions no longer shows 'standard=0.2' for UP", + "/jurisdictions no longer shows 'reduced=0.05' for UP"]), ("a listed field kept only inside a longer one fails the upgrade", faults["extending"].get("passed") is False and faults["extending"].get("failures") == [ - "/jurisdictions no longer shows 'standard=0.2,reduced=0.05' " - "for UP"]), + "/jurisdictions no longer shows 'reduced=0.05' for UP"]), + ("a list-item row with a value the change adds keeps every old one", + items.get("passed") is True and not items.get("failures")), + ("a schema changed for new files alone fails on the change's own " + "fields", + faults["fresh"].get("passed") is False + and faults["fresh"].get("failures") == [ + "a record posted to /jurisdictions after the upgrade is not " + "listed", + "a record posted to /rules after the upgrade is not listed"]), ("old invoices that break on the new field fail the upgrade", faults["fragile"].get("passed") is False and any("/invoices/" in failure for failure in From 520c3010daf9f0b9486e629bc49e2d481480df84 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:11:35 +0200 Subject: [PATCH 10/18] fix(efficacy): Codex round 6 on the changed-tree scoring - a seeded record whose row no key finds, on the old page or on a new page that still shows it, leaves the data upgrade missing, never passed: "row for not found" - the boot check keeps its database, and whatever the app writes beside it, in a folder of its own outside the tree, removed after - a changed tree's churn is read before the install, the boot or the suites write into it, beside its scope Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +-- docs/requirements.md | 4 +-- tests/efficacy/quality.py | 28 ++++++++++++--- tests/efficacy/score.py | 76 +++++++++++++++++++++++++++++++++------ 4 files changed, 94 insertions(+), 18 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 5ffff39..5092b03 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -236,10 +236,10 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | +| FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | diff --git a/docs/requirements.md b/docs/requirements.md index 2d3d5ea..63a0154 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -249,10 +249,10 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn taken before the battery writes into the tree, its scope read from its index as the change task left it, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | +| FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, however the row is marked up, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, however the row is marked up, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 083554b..eecbea6 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1112,7 +1112,7 @@ def data_upgrade(seeded): """The changed tree on a copy of the fixture's database: every record seeded is still there and reads the same, every old invoice opens and prices as it did, and the upgraded database takes new records.""" - failures = [] + failures, unfound = [], [] for path, values in seeded["pages"].items(): answer = page(client, path) shown = text_of(answer) @@ -1126,10 +1126,16 @@ def data_upgrade(seeded): # or rate as much as its name, still shows whole in that record's # row, never only inside a longer one; a value the change adds is # its own, and is no loss. + # A row neither page marks so it can be found by its key leaves the + # values unread, never kept; a key gone from the page is a loss, as + # the listing above reads it. text = answer.get_data(as_text=True) for key, tokens in (seeded.get("rows") or {}).get(path, {}).items(): now = row_tokens(text, key) - if not tokens or now is None: + if tokens is None or (now is None and key in shown): + unfound.append(key) + continue + if now is None: continue failures += ["%s no longer shows %r for %s" % (path, token, key) for token in tokens if token not in now] @@ -1205,6 +1211,9 @@ def data_upgrade(seeded): if body[key] not in text_of(page(client, path)): failures.append("a record posted to %s after the upgrade is not " "listed" % path) + if not failures and unfound: + return {"passed": None, + "missing": "row for %s not found" % unfound[0]} return passed(not failures, failures=failures[:20]) @@ -1974,14 +1983,16 @@ def create_app(database): # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` # links no customer, so nothing can be seeded. `items`, at either version, -# lists jurisdictions as list items rather than table rows, and is sound. +# lists jurisdictions as list items rather than table rows, and is sound. A +# mode ending `+divs` lists its records in bare `
    `s, which no row is +# found in. UPGRADE_APP = '''import decimal import json import os import sqlite3 VERSION = __VERSION__ -MODE = "__MODE__" +MODE, _, MARKUP = "__MODE__".partition("+") TOKEN = '' CENT = decimal.Decimal("0.01") SEED = (("WID-1", "Widget", "10.00", "standard"), @@ -2149,6 +2160,10 @@ def listing(self, connection, table): else: rows = connection.execute("SELECT code, name, default_rate, " "rates FROM jurisdictions") + if MARKUP == "divs": + return "".join("
    %s
    " % " ".join(str(value) + for value in row) + for row in rows) if MODE == "items": return "
      %s
    " % "".join( "
  • %s
  • " % " ".join(str(value) for value in row) @@ -2328,6 +2343,7 @@ def upgrade_self_checks(scratch): for mode in UPGRADE_FAULTS} unseeded = upgrade_reading(scratch, "unlisting", "sound") items = upgrade_reading(scratch, "items", "items") + hidden = upgrade_reading(scratch, "sound+divs", "rerating+divs") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) return [ @@ -2356,6 +2372,10 @@ def upgrade_self_checks(scratch): faults["extending"].get("passed") is False and faults["extending"].get("failures") == [ "/jurisdictions no longer shows 'reduced=0.05' for UP"]), + ("a row found by no key leaves the upgrade missing, never passed", + hidden.get("passed") is None + and hidden.get("missing", "").startswith("row for ") + and hidden["missing"].endswith(" not found")), ("a list-item row with a value the change adds keeps every old one", items.get("passed") is True and not items.get("failures")), ("a schema changed for new files alone fails on the change's own " diff --git a/tests/efficacy/score.py b/tests/efficacy/score.py index 55aa901..64f049d 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -336,7 +336,12 @@ def boot_check(venv, workspace): have no application factory. The factory's name and signature are fixed by the specification, so this reaches only what every arm owes. """ - database = os.path.join(workspace, ".score-boot.sqlite") + + # The database, and whatever the app keeps beside it, such as a secret + # it persists, go to a folder of their own outside the tree, so booting + # the app changes nothing a later reading of the tree counts. + folder = tempfile.mkdtemp(prefix="score-boot-") + database = os.path.join(folder, "boot.sqlite") code = ( "import json, sys\n" "result = {'import': False, 'factory': False, 'index_status': None}\n" @@ -359,7 +364,11 @@ def boot_check(venv, workspace): " result['serve_error'] = repr(error)[:300]\n" "print(json.dumps(result))\n" % (PACKAGE, database) ) - outcome = run([python_in(venv), "-c", code], cwd=workspace, timeout=300) + try: + outcome = run([python_in(venv), "-c", code], cwd=workspace, + timeout=300) + finally: + remove_tree(folder) try: payload = json.loads(outcome["stdout"].strip().splitlines()[-1]) except (ValueError, IndexError): @@ -1361,9 +1370,12 @@ def score_change_trial(record, options, suite, lock): os.path.join(scoring, "tree"), frozen) files = python_files(workspace) - # The index as the change task left it, before the install, the suites - # or churn's intent-to-add can put a file of their own in it. + # The index as the change task left it, and what it changed, both read + # before the install, the boot or the suites can put a file of their own + # in the tree; churn's intent-to-add comes after the index is read. tracked = tracked_files(workspace) + changed = (churn(workspace, record["base"]) if record.get("base") + else absent("the change record names no starting commit")) venv = create_venv(os.path.join(scoring, "venv")) # The fixture is named by its hash and with the readings it qualified @@ -1404,11 +1416,7 @@ def score_change_trial(record, options, suite, lock): scores["interfaces"] = interfaces(scores["build_suite"], record.get("fixture")) - # Before the battery, whose tools leave reports and caches in the tree - # that the agent never wrote. - scores["churn"] = (churn(workspace, record["base"]) if record.get("base") - else absent("the change record names no starting " - "commit")) + scores["churn"] = changed measure_code(scores, venv, workspace, options, lock, source, change_required_names()) scores["scope"] = scope(workspace, roots, tracked) @@ -2046,6 +2054,53 @@ def boot_checks(scratch, venv): and booted.get("index_status") == 200)] +# An app that keeps a secret beside its database the first time it boots, +# as a generated key persisted to a file does. +PLANTED_SECRET_APP = """\ +import io + + +class App(object): + def test_client(self): + return self + + def get(self, path): + return type("Answer", (), {"status_code": 200})() + + +def create_app(database): + with io.open(database, "w") as handle: + handle.write("") + with io.open(database + ".secretkey", "w") as handle: + handle.write("generated") + return App() +""" + + +def boot_churn_checks(scratch, venv): + """Booting an unchanged app that writes a secret beside its database + leaves the tree as it was: no churn, and nothing new in it.""" + tree = os.path.join(scratch, "boot-churn") + os.makedirs(os.path.join(tree, PACKAGE)) + with io.open(os.path.join(tree, PACKAGE, "__init__.py"), "w", + encoding="utf-8") as handle: + handle.write(PLANTED_SECRET_APP) + for argv in (["init", "-q"], ["add", "-A"], + ["-c", "user.name=self-test", + "-c", "user.email=self-test@example.invalid", + "commit", "-q", "-m", "build"]): + run(["git", "-C", tree] + argv, timeout=120) + base = run(["git", "-C", tree, "rev-parse", "HEAD"])["stdout"].strip() + booted = boot_check(venv, tree)["value"] or {} + changed = churn(tree, base)["value"] or {} + left = run(["git", "-C", tree, "status", "--porcelain", + "--untracked-files=all"])["stdout"] + return [("an unchanged app that writes a secret beside its database at " + "boot shows no churn", + booted.get("index_status") == 200 and changed.get("files") == 0 + and ".secretkey" not in left and ".score-boot" not in left)] + + PLANTED_TEST_DEPENDENCIES = '''[project] name = "pkg" version = "0" @@ -2386,7 +2441,8 @@ def self_test(): checks.append(("a scored trial's environment is dropped", not os.path.exists(dropped))) venv = create_venv(os.path.join(scratch, "venv")) - checks += boot_checks(scratch, venv) + interpreter_checks(scratch, venv) + checks += (boot_checks(scratch, venv) + boot_churn_checks(scratch, venv) + + interpreter_checks(scratch, venv)) empty = os.path.join(scratch, "empty") os.makedirs(empty) From 62d74c4b991b53f977874b37fa321f7499a39187 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:29:53 +0200 Subject: [PATCH 11/18] fix(efficacy): Codex round 7 on the data upgrade's rows - a page's rows are read by the outermost kind it holds, table rows, then list items, then paragraphs, each with everything inside it, so a paragraph in a table cell no longer cuts its row in two Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 69 +++++++++++++++++++++++++++++++-------- 3 files changed, 58 insertions(+), 15 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 5092b03..e6bf56f 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,7 +239,7 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | diff --git a/docs/requirements.md b/docs/requirements.md index 63a0154..85c1e04 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,7 +252,7 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, however the row is marked up, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index eecbea6..18f6a89 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -966,25 +966,58 @@ def invoice_reading(path): "csv": csv_text.get_data(as_text=True)} -ROW_OPEN = re.compile(r"<(?:tr|li|p)\b[^>]*>", re.IGNORECASE) -ROW_CLOSE = re.compile(r"", re.IGNORECASE) -CELL_OPEN = re.compile(r"]*>", re.IGNORECASE) -TAG = re.compile(r"<[^>]+>") - +# The kinds of element a page may write a record's row as, outermost first: +# a page is read by the first kind it holds, so a paragraph inside a table +# cell stays part of its row. +ROW_KINDS = ("tr", "li", "p") +ROW_TAG = re.compile(r"<(tr|li|p)\b", re.IGNORECASE) # What a row's text is split into whole values on: white space and the # separators a page writes a list in, so `standard=0.2` stays one value. TOKEN_SPLIT = re.compile(r"[\s,;|]+") +class Rows(HTMLParser): + """The text of each outermost `kind` element on a page, every tag inside + it included, a `kind` nested inside it part of it.""" + + def __init__(self, kind): + HTMLParser.__init__(self, convert_charrefs=True) + self.kind, self.depth, self.rows = kind, 0, [] + + def handle_starttag(self, tag, attrs): + if tag == self.kind: + if not self.depth: + self.rows.append([]) + self.depth += 1 + if self.depth: + self.rows[-1].append(" ") + + def handle_endtag(self, tag): + if self.depth: + self.rows[-1].append(" ") + if tag == self.kind and self.depth: + self.depth -= 1 + + def handle_data(self, data): + if self.depth: + self.rows[-1].append(data) + + def row_tokens(text, key): """The whole values the first row a page shows `key` in writes, in - order, a row being a table row, a list item or a paragraph, however its - cells are marked up; None where no row shows it.""" - for chunk in ROW_OPEN.split(text)[1:]: - chunk = ROW_CLOSE.split(chunk)[0] - tokens = [token for token in TOKEN_SPLIT.split(html.unescape( - TAG.sub(" ", chunk))) if token] + order, a row being the outermost of a table row, a list item or a + paragraph the page holds, however its cells are marked up; None where + no row shows it.""" + present = {tag.lower() for tag in ROW_TAG.findall(text)} + kind = next((kind for kind in ROW_KINDS if kind in present), None) + if kind is None: + return None + parser = Rows(kind) + parser.feed(text) + parser.close() + for row in parser.rows: + tokens = [token for token in TOKEN_SPLIT.split("".join(row)) if token] if key in tokens: return tokens return None @@ -1985,7 +2018,7 @@ def create_app(database): # links no customer, so nothing can be seeded. `items`, at either version, # lists jurisdictions as list items rather than table rows, and is sound. A # mode ending `+divs` lists its records in bare `
    `s, which no row is -# found in. +# found in, and one ending `+pcells` wraps each table cell in a paragraph. UPGRADE_APP = '''import decimal import json import os @@ -2168,8 +2201,9 @@ def listing(self, connection, table): return "
      %s
    " % "".join( "
  • %s
  • " % " ".join(str(value) for value in row) for row in rows) + cell = "

    %s

    " if MARKUP == "pcells" else "%s" return "%s
    " % "".join( - "%s" % "".join("%s" % value for value in row) + "%s" % "".join(cell % value for value in row) for row in rows) def create(self, connection, table, data): @@ -2344,6 +2378,8 @@ def upgrade_self_checks(scratch): unseeded = upgrade_reading(scratch, "unlisting", "sound") items = upgrade_reading(scratch, "items", "items") hidden = upgrade_reading(scratch, "sound+divs", "rerating+divs") + wrapped = upgrade_reading(scratch, "sound+pcells", "sound+pcells") + rewrapped = upgrade_reading(scratch, "sound+pcells", "rerating+pcells") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) return [ @@ -2372,6 +2408,13 @@ def upgrade_self_checks(scratch): faults["extending"].get("passed") is False and faults["extending"].get("failures") == [ "/jurisdictions no longer shows 'reduced=0.05' for UP"]), + ("a table row whose cells are paragraphs is read whole: kept when " + "sound, its cleared values named", + wrapped.get("passed") is True + and rewrapped.get("passed") is False + and rewrapped.get("failures") == [ + "/jurisdictions no longer shows 'standard=0.2' for UP", + "/jurisdictions no longer shows 'reduced=0.05' for UP"]), ("a row found by no key leaves the upgrade missing, never passed", hidden.get("passed") is None and hidden.get("missing", "").startswith("row for ") From 0031c8126ed4a0ae99a6be2e5a98a28fff8dc4a1 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:07:24 +0200 Subject: [PATCH 12/18] fix(efficacy): Codex round 8 on the changed-tree scoring - the data upgrade reads back the values its new-field records were posted with, the cap and the minimum, whole in their rows; an app that drops a field it has no column for fails - an archive's verify compares each task's ISO reading and cost and the registered C1 results too, so a change task's reading that changes, its data upgrade among them, refuses the verify - C1's new arms, from the base's declared contrasts, get a verdict and a cost on each task Refs #178, #158, #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +-- docs/requirements.md | 4 +-- tests/efficacy/archive.py | 27 ++++++++++++++++++ tests/efficacy/quality.py | 50 ++++++++++++++++++++++----------- tests/efficacy/report.py | 58 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 20 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 5301639..2390326 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -242,7 +242,7 @@ when: | FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | -| FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | -| FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
    `report.py` "each task's radar reads that task's trees against `none` on the same task"
    `report.py` "the change task's radar reads its own security, not the build's"
    `report.py` "a named round's build radar leaves the change targets to the change task's"
    `report.py` "each task's radar shows its own mean billed cost per trial"
    `report.py` "a pilot round draws one radar, its trials as they are"
    `report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
    `report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
    `report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
    `report.py` "named pairs are read for every metric of a table" | +| FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | +| FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
    `report.py` "a C1 run gives lazysections and lazyrefold a verdict and a cost on each task, against none"
    `report.py` "each task's radar reads that task's trees against `none` on the same task"
    `report.py` "the change task's radar reads its own security, not the build's"
    `report.py` "a named round's build radar leaves the change targets to the change task's"
    `report.py` "each task's radar shows its own mean billed cost per trial"
    `report.py` "a pilot round draws one radar, its trials as they are"
    `report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
    `report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
    `report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
    `report.py` "named pairs are read for every metric of a table" | | FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
    `report.py` "the check loop is not kept on the build task's readings alone"
    `report.py` "a cost drop under 10 % on one task does not keep the check loop"
    `report.py` "an axis worse on either task does not keep the check loop"
    `report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
    `report.py` "an interval crossing the margin is inconclusive, never non-inferior"
    `report.py` "the report and its full record print the registered readings"
    `report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
    `report.py` "a cost drop a float's error under 10 % meets the gate"
    `report.py` "a cost drop a float's error under 10 % reads yes in the table and keeps the loop"
    `report.py` "C1 reads an axis non-inferior only with its lower bound strictly above minus the margin"
    `report.py` "a round running none of the registered pairs prints none of them" | | FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
    `report.py` "an arm whose reads were not counted is not shown on demand"
    `report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
    `report.py` "a task's reading left out of the report counts no template use on that task"
    `report.py` "a skill's file read or shell-read is that skill used, once with its loading" | diff --git a/docs/requirements.md b/docs/requirements.md index 22c4b70..decdde3 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,10 +252,10 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them, each value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | -| FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | +| FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | | FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, within 1e-9, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound lies strictly above minus its margin, one on or below it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | | FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, a skill's file read counted once with its loading, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index ffd2e4b..98f55db 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -311,7 +311,18 @@ def figures(root, seed): results = report.round_contrasts(trials, table, seed) withdrawn = report.withdrawals(trials) report.withdraw(withdrawn, table, results) + + # A named round's every task is read on its own radar, and its + # registered readings from those, so a change task's reading that + # changes, its data upgrade among them, shows as its figures do. + tasks = report.task_readings(trials, seed, withdrawn) + per_task = {task: {"iso": reading[0], "results": reading[1], + "cost_usd": task_table["cost_usd"]} + for task, _, _, task_table, reading in tasks} + registered = (report.registered_figures( + tasks, seed, report.task_uses(root, tasks)) if tasks else None) return {"table": table, "results": results, "withdrawn": withdrawn, + "iso_tasks": per_task, "registered": registered, "owed_blocks": report.owed_blocks(trials), "reach": report.reaches(root), "lost": [{key: value for key, value in loss.items() @@ -574,6 +585,10 @@ def self_test(): dump_json(os.path.join(scoring_area(named), "scores-change", "none-1.json"), {"name": "none-1", "change_suite": {"value": 0.9}}) + dump_json(os.path.join(scoring_area(named), "quality-scores-change", + "none-1.json"), + {"name": "none-1", "probes": {"data_upgrade": { + "passed": True}}}) named_into = os.path.join(scratch, "runs", "c1") archive(named, named_into) clean = verify(named, named_into, seed) == [] @@ -585,6 +600,18 @@ def self_test(): "the verify", clean and "table" in verify(named, named_into, seed))) + # A change task's quality reading flipped in the archive moves only its + # task's radar, never the combined table, and the verify still refuses. + dump_json(archived, dict(load_json(archived), + change_suite={"value": 0.9})) + upgraded = os.path.join(scoring_area(named_into), "quality-scores-change", + "none-1.json") + dump_json(upgraded, {"name": "none-1", "probes": {"data_upgrade": { + "passed": False}}}) + checks.append(("a C1 change task's quality reading flipped in the " + "archive fails the verify", + verify(named, named_into, seed) == ["iso_tasks"])) + # A round-5d root is verified by round 5d's rules, so reliability's # interval is Newcombe's there as it is in the report. later = os.path.join(scratch, "round-5d") diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 92980d5..b8166ee 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1365,24 +1365,39 @@ def data_upgrade(seeded): "total"))) written = (("/jurisdictions", "code", { "code": "U2", "name": "Upgradia Nova", "default_rate": "0.1", - "rates": "standard=0.1"}), + "rates": "standard=0.1"}, ()), ("/rules", "rule_id", {"rule_id": "u-pct-after", "kind": "percentage", "sku": "UPG-2", - "percent": "3"}), + "percent": "3"}, ()), # And through the fields the change added, which a schema changed - # for new files alone refuses on an old one. + # for new files alone refuses on an old one, or drops. Each must be + # read back whole in the record's row, as any of the ways a page + # may write it. ("/jurisdictions", "code", { "code": "U3", "name": "Upgradia Capped", "default_rate": "0.2", - "rates": "standard=0.2,reduced=0.05", "caps": "reduced=50.00"}), + "rates": "standard=0.2,reduced=0.05", "caps": "reduced=50.00"}, + ("reduced=50.00", "50.00")), ("/rules", "rule_id", {"rule_id": "u-threshold", "kind": "threshold", "sku": "", - "percent": "5", "minimum": "200.00"})) - for path, key, body in written: + "percent": "5", "minimum": "200.00"}, + ("200.00",))) + for path, key, body, shown_as in written: created(path, body) - if body[key] not in text_of(page(client, path)): + text = text_of(page(client, path)) + if body[key] not in text: failures.append("a record posted to %s after the upgrade is not " "listed" % path) + continue + if not shown_as: + continue + tokens = row_tokens(page(client, path).get_data(as_text=True), + body[key]) + if tokens is None: + unfound.append(body[key]) + elif not any(token in tokens for token in shown_as): + failures.append("%s lists %s without the %s it was posted with" + % (path, body[key], shown_as[0])) if not failures and unfound: return {"passed": None, "missing": "row for %s not found" % unfound[0]} @@ -2216,8 +2231,8 @@ def create_app(database): # jurisdiction's listed rates, which no invoice prices with and only its page # shows, `extending` appends a digit to them, the old rates still inside the # new, `fresh` adds the columns to new files alone and reads an old one -# without them, refusing only a record that sets one, `fragile` cannot read -# an old +# without them, silently dropping the field a new record sets, `fragile` +# cannot read an old # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` # links no customer, so nothing can be seeded. `items`, at either version, @@ -2322,8 +2337,7 @@ def add_jurisdiction(self, connection, code, name, rate, rates, caps=None): names, values = ["code", "name", "default_rate", "rates"], [ code, name, rate, rates] - if VERSION == 2 and (caps is not None or "caps" in columns( - connection, "jurisdictions")): + if VERSION == 2 and "caps" in columns(connection, "jurisdictions"): names.append("caps") values.append(caps or "{}") connection.execute("INSERT INTO jurisdictions (%s) VALUES (%s)" % ( @@ -2390,6 +2404,10 @@ def listing(self, connection, table): if table == "products": rows = connection.execute("SELECT sku, name, unit_price FROM " "products") + elif table == "rules" and VERSION == 2 and "minimum" in columns( + connection, "rules"): + rows = connection.execute("SELECT rule_id, kind, minimum FROM " + "rules") elif table == "rules": rows = connection.execute("SELECT rule_id, kind FROM rules") elif VERSION == 2 and "caps" in columns(connection, "jurisdictions"): @@ -2421,8 +2439,7 @@ def create(self, connection, table, data): "percent", "buy", "pay", "code", "amount")}) names, values = ["rule_id", "kind", "sku", "detail"], [ data["rule_id"], data["kind"], data.get("sku"), detail] - if VERSION == 2 and (data.get("minimum") or "minimum" in columns( - connection, "rules")): + if VERSION == 2 and "minimum" in columns(connection, "rules"): names.append("minimum") values.append(data.get("minimum")) connection.execute("INSERT INTO rules (%s) VALUES (%s)" % ( @@ -2630,9 +2647,10 @@ def upgrade_self_checks(scratch): "fields", faults["fresh"].get("passed") is False and faults["fresh"].get("failures") == [ - "a record posted to /jurisdictions after the upgrade is not " - "listed", - "a record posted to /rules after the upgrade is not listed"]), + "/jurisdictions lists U3 without the reduced=50.00 it was " + "posted with", + "/rules lists u-threshold without the 200.00 it was posted " + "with"]), ("old invoices that break on the new field fail the upgrade", faults["fragile"].get("passed") is False and any("/invoices/" in failure for failure in diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 5a4cabd..ade39e0 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -6261,6 +6261,43 @@ def states(low, high): ] +def c1_arm_checks(seed): + """Round C1's new arms are read on each task against `none`: each gets + a verdict and a cost per task from the contrasts the round declares.""" + def reading(value): + return {"value": value, "missing": None} + + def tree(cost): + return {"install": reading(True), + "boot": reading({"factory": True, "index_status": 200}), + "cost": reading({"cost_usd": cost})} + costs = {BARE: (2.0, 1.0), "lazysections": (1.5, 0.75), + "lazyrefold": (2.5, 1.25)} + trials = {} + for arm, (built, changed) in costs.items(): + for block in range(1, 6): + name = trial_name(arm, block) + trials[name] = { + "round": "C1", "judge": None, "judgings": [], + "scores": dict(tree(built), name=name), "security": None, + "quality": None, "change": dict(tree(changed), name=name)} + tasks = task_readings(trials, seed) + text = "\n".join(line for reading in tasks + for line in task_lines(reading, {})) + sections = {task: text.split("## The %s" % label)[1].split("## The ")[0] + for task, label in TASKS} + rows = {task: [line for line in section.splitlines() + if line.startswith(("| lazysections |", + "| lazyrefold |"))] + for task, section in sections.items()} + return [("a C1 run gives lazysections and lazyrefold a verdict and a " + "cost on each task, against none", + rows["build"] == ["| lazysections | No | $1.50 |", + "| lazyrefold | No | $2.50 |"] + and rows["change"] == ["| lazysections | No | $0.75 |", + "| lazyrefold | No | $1.25 |"])] + + def change_only_checks(): """A named round's change task is read whether or not its build trial was scored or reached, on rows of its own; a pilot round's keeps @@ -7978,6 +8015,26 @@ def on_demand(read, uses, arm): return ours < theirs and read["non_inferior"] +def registered_figures(tasks, seed, uses_by_task): + """Round C1's registered results as figures, for a verify to compare: + each pair's reading on each task, whether the check loop is kept, and + each on-demand arm's answer on each task.""" + present = {arm_of(name) for reading in tasks for name in reading[2]} + reads = {(reading[0], pair): pair_reading(reading, seed, pair) + for reading in tasks for pair in registered_pairs() + if set(pair) <= present} + loop = {task: read for (task, pair), read in reads.items() + if pair == CHECK_LOOP} + return { + "reads": {"%s %s-%s" % (task, pair[0], pair[1]): read + for (task, pair), read in sorted(reads.items())}, + "check_loop_kept": check_loop_kept(loop) if loop else None, + "on_demand": {"%s %s" % (task, arm): on_demand( + reads[(task, (arm, UP_FRONT))], uses_by_task.get(task) or {}, + arm) for task, _, _, _, _ in tasks for arm in ON_DEMAND + if (task, (arm, UP_FRONT)) in reads}} + + def registered_lines(tasks, seed, uses_by_task): """Round C1's registered readings in its own words, one table each, per task: the check loop and whether it is kept, the section files against @@ -10388,6 +10445,7 @@ def self_test(seed): checks.extend((label, ok, ok) for label, ok in task_use_checks()) checks.extend((label, ok, ok) for label, ok in pair_contrast_checks(seed)) checks.extend((label, ok, ok) for label, ok in round3_checks(seed)) + checks.extend((label, ok, ok) for label, ok in c1_arm_checks(seed)) checks.extend((label, ok, ok) for label, ok in change_finding_checks(seed)) for label, ok, got in checks: From e76ca3021f240692238e23e7fdc590cde6c18f6c Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:46:33 +0200 Subject: [PATCH 13/18] fix(efficacy): Codex round 9 on the data upgrade - one rule reads a row's values, kept ones and those read back alike: equal as text, or the same amount once a leading currency is set aside, a key=value with the same key and such a value; 0.05 still fails against 0.051 - every export the upgrade reads must answer a success before its body counts, the JSON exports and the customer's alike, at the seed too; one that does not fails the upgrade, naming its status Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 85 ++++++++++++++++++++++++++++++++++----- 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 2390326..61caf26 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,7 +239,7 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | diff --git a/docs/requirements.md b/docs/requirements.md index decdde3..7207b5d 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,7 +252,7 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, or the upgraded file refuses new records, ones setting the fields the change added among them, each value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, or the upgraded file refuses new records, ones setting the fields the change added among them, each value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index b8166ee..f58586f 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1206,6 +1206,7 @@ def seed_upgrade(): answer.status_code) reading = invoice_reading(path) if not (200 <= reading["status"] < 300 + and 200 <= reading["export_status"] < 300 and isinstance(reading["export"], dict) and 200 <= reading["csv_status"] < 300): return None, "the fixture does not show the invoice it saved" @@ -1232,6 +1233,9 @@ def seed_upgrade(): if missing: return None, "%s does not list %s" % (path, missing[0]) export = page(client, "/customers/%s/export.json" % customer) + if not ok(export): + return None, "the seeded customer's export answered %d" % ( + export.status_code) try: customer_export = json.loads(export.get_data(as_text=True)) except ValueError: @@ -1240,6 +1244,31 @@ def seed_upgrade(): "customer": {"id": customer, "export": customer_export}}, None +# A currency a page may write before an amount, as a sign or a code. +CURRENCY = re.compile(r"^(?:€|\$|£|EUR|USD|GBP)\s*", re.IGNORECASE) + + +def same_token(old, new): + """Whether a value a page wrote reads as another: equal as text, or as + amounts once a leading currency is set aside, `50.00` as `€50`; a + `key=value` reads so only with the same key and a value that does.""" + if old == new: + return True + if "=" in old and "=" in new: + old_key, _, old_value = old.partition("=") + new_key, _, new_value = new.partition("=") + return old_key == new_key and same_token(old_value, new_value) + try: + return Decimal(CURRENCY.sub("", old)) == Decimal(CURRENCY.sub("", new)) + except (InvalidOperation, ValueError): + return False + + +def has_token(tokens, wanted): + """Whether a row's values hold one that reads as `wanted`.""" + return any(same_token(wanted, token) for token in tokens) + + def unkept(old, new, where="$"): """The first place `new` no longer holds what `old` did, or None: every key `old` had with the same value, a list as long, item by item. A key @@ -1310,17 +1339,23 @@ def data_upgrade(seeded): if now is None: continue failures += ["%s no longer shows %r for %s" % (path, token, key) - for token in tokens if token not in now] + for token in tokens if not has_token(now, token)] for old in seeded["invoices"]: now = invoice_reading(old["path"]) if not 200 <= now["status"] < 300: failures.append("%s answered %d" % (old["path"], now["status"])) continue - place = unkept(old["export"], now["export"]) - if place: - failures.append("%s/export.json no longer reads the same at %s" - % (old["path"], place)) - if now["csv_status"] != old["csv_status"]: + # An export is read only where it answers as a success; a body + # served with an error is no export, whatever it holds. + if not 200 <= now["export_status"] < 300: + failures.append("%s/export.json answered %d" % ( + old["path"], now["export_status"])) + else: + place = unkept(old["export"], now["export"]) + if place: + failures.append("%s/export.json no longer reads the same at " + "%s" % (old["path"], place)) + if not 200 <= now["csv_status"] < 300: failures.append("%s/export.csv answered %d" % ( old["path"], now["csv_status"])) else: @@ -1343,7 +1378,10 @@ def data_upgrade(seeded): except ValueError: export = None place = unkept(customer["export"], export) - if place: + if not ok(answer): + failures.append("the customer's export answered %d" + % answer.status_code) + elif place: failures.append("the customer's export no longer reads the same at %s" % place) @@ -1395,7 +1433,7 @@ def data_upgrade(seeded): body[key]) if tokens is None: unfound.append(body[key]) - elif not any(token in tokens for token in shown_as): + elif not any(has_token(tokens, token) for token in shown_as): failures.append("%s lists %s without the %s it was posted with" % (path, body[key], shown_as[0])) if not failures and unfound: @@ -2238,7 +2276,10 @@ def create_app(database): # links no customer, so nothing can be seeded. `items`, at either version, # lists jurisdictions as list items rather than table rows, and is sound. A # mode ending `+divs` lists its records in bare `
    `s, which no row is -# found in, and one ending `+pcells` wraps each table cell in a paragraph. +# found in, one ending `+pcells` wraps each table cell in a paragraph, one +# ending `+terse` writes the minimum as 200, each price after the euro's +# sign and the cap as euro 50, and one +# ending `+erring` answers its JSON export 500 with a whole body. UPGRADE_APP = '''import decimal import json import os @@ -2268,6 +2309,17 @@ def get_data(self, as_text=False): return self._body if as_text else self._body.encode("utf-8") +def terse(value): + """A value as a terse page writes it: the minimum without its trailing + zeros, a price after the euro's sign, a cap with it.""" + text = str(value) + if text == "200.00": + return "200" + if text.replace(".", "", 1).isdigit() and "." in text: + return "\u20ac" + text + return text.replace("=50.00", "=\u20ac50") + + def form(action, body=""): return ('%s
    %s
    ' % (body, action, TOKEN)) @@ -2416,6 +2468,8 @@ def listing(self, connection, table): else: rows = connection.execute("SELECT code, name, default_rate, " "rates FROM jurisdictions") + if MARKUP == "terse": + rows = [tuple(terse(value) for value in row) for row in rows] if MARKUP == "divs": return "".join("
    %s
    " % " ".join(str(value) for value in row) @@ -2544,7 +2598,8 @@ def invoices(self, connection, parts, method, data): "total": total} if VERSION == 2: export["caps"] = {} - return Response(200, json.dumps(export)) + return Response(500 if MARKUP == "erring" else 200, + json.dumps(export)) if parts[2:] == ["export.csv"]: head = "sku,quantity,net" + (",cap" if VERSION == 2 else "") return Response(200, "\\n".join([head] + [ @@ -2602,6 +2657,8 @@ def upgrade_self_checks(scratch): hidden = upgrade_reading(scratch, "sound+divs", "rerating+divs") wrapped = upgrade_reading(scratch, "sound+pcells", "sound+pcells") rewrapped = upgrade_reading(scratch, "sound+pcells", "rerating+pcells") + terse_read = upgrade_reading(scratch, "sound", "sound+terse") + erring = upgrade_reading(scratch, "sound", "sound+erring") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) return [ @@ -2637,6 +2694,14 @@ def upgrade_self_checks(scratch): and rewrapped.get("failures") == [ "/jurisdictions no longer shows 'standard=0.2' for UP", "/jurisdictions no longer shows 'reduced=0.05' for UP"]), + ("a value written as another amount, a sign before it or no " + "trailing zeros, reads as the same value", + terse_read.get("passed") is True and not terse_read.get("failures")), + ("an export answering an error fails the upgrade, naming its status", + erring.get("passed") is False + and erring.get("failures") == [ + "/invoices/1/export.json answered 500", + "/invoices/2/export.json answered 500"]), ("a row found by no key leaves the upgrade missing, never passed", hidden.get("passed") is None and hidden.get("missing", "").startswith("row for ") From 38976b04b60f44ef0fc74473af50ba8424b84030 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:55:16 +0200 Subject: [PATCH 14/18] fix(efficacy): Codex round 10 on the changed-tree scoring - the data upgrade reads back every value its new records were posted with, by the rule kept values are read by, not only the cap and the minimum; a stand-in storing other values fails - a build suite that ran out of time fails every interface, report or none, as the radar reads such a suite, not leaving them unmeasured - a shell read of a skill's folder through a wildcard reads its skill, resolved against the skills' own files, once with its loading Refs #178, #158, #169. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 6 ++-- docs/requirements.md | 6 ++-- tests/efficacy/quality.py | 65 ++++++++++++++++++++++++++------------- tests/efficacy/report.py | 16 ++++++++-- tests/efficacy/score.py | 20 ++++++++++-- 5 files changed, 80 insertions(+), 33 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 61caf26..6a3b6bb 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -237,12 +237,12 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | -| FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | +| FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "a build suite that ran out of time fails every interface, not missing"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a new record stored with other values than it was posted with fails the upgrade"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
    `report.py` "a C1 run gives lazysections and lazyrefold a verdict and a cost on each task, against none"
    `report.py` "each task's radar reads that task's trees against `none` on the same task"
    `report.py` "the change task's radar reads its own security, not the build's"
    `report.py` "a named round's build radar leaves the change targets to the change task's"
    `report.py` "each task's radar shows its own mean billed cost per trial"
    `report.py` "a pilot round draws one radar, its trials as they are"
    `report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
    `report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
    `report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
    `report.py` "named pairs are read for every metric of a table" | | FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
    `report.py` "the check loop is not kept on the build task's readings alone"
    `report.py` "a cost drop under 10 % on one task does not keep the check loop"
    `report.py` "an axis worse on either task does not keep the check loop"
    `report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
    `report.py` "an interval crossing the margin is inconclusive, never non-inferior"
    `report.py` "the report and its full record print the registered readings"
    `report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
    `report.py` "a cost drop a float's error under 10 % meets the gate"
    `report.py` "a cost drop a float's error under 10 % reads yes in the table and keeps the loop"
    `report.py` "C1 reads an axis non-inferior only with its lower bound strictly above minus the margin"
    `report.py` "a round running none of the registered pairs prints none of them" | -| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
    `report.py` "an arm whose reads were not counted is not shown on demand"
    `report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
    `report.py` "a task's reading left out of the report counts no template use on that task"
    `report.py` "a skill's file read or shell-read is that skill used, once with its loading" | +| FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
    `report.py` "an arm whose reads were not counted is not shown on demand"
    `report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
    `report.py` "a task's reading left out of the report counts no template use on that task"
    `report.py` "a wildcard read of one skill's folder counts that skill once, another file there none"
    `report.py` "a skill's file read or shell-read is that skill used, once with its loading" | diff --git a/docs/requirements.md b/docs/requirements.md index 7207b5d..990e2e1 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -250,15 +250,15 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | -| FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | +| FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not met for every module where the build suite ran out of time; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, or the upgraded file refuses new records, ones setting the fields the change added among them, each value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, or the upgraded file refuses new records, ones setting the fields the change added among them, every value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | | FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, within 1e-9, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound lies strictly above minus its margin, one on or below it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | -| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, a skill's file read counted once with its loading, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | +| FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, a skill's file read, by its name or a wildcard, counted once with its loading, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | ## Quality requirements diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index f58586f..f72a6fa 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1401,41 +1401,48 @@ def data_upgrade(seeded): failures.append("the first invoice saved again totals %r, not %r" % (total, seeded["invoices"][0]["export"].get( "total"))) + # Every value posted is read back whole in the record's row, by the + # rule the kept values are read by; a cap may be written as its amount + # alone, so either form of it reads. written = (("/jurisdictions", "code", { "code": "U2", "name": "Upgradia Nova", "default_rate": "0.1", - "rates": "standard=0.1"}, ()), + "rates": "standard=0.1"}, {}), ("/rules", "rule_id", {"rule_id": "u-pct-after", "kind": "percentage", "sku": "UPG-2", - "percent": "3"}, ()), + "percent": "3"}, {}), # And through the fields the change added, which a schema changed - # for new files alone refuses on an old one, or drops. Each must be - # read back whole in the record's row, as any of the ways a page - # may write it. + # for new files alone refuses on an old one, or drops. ("/jurisdictions", "code", { "code": "U3", "name": "Upgradia Capped", "default_rate": "0.2", "rates": "standard=0.2,reduced=0.05", "caps": "reduced=50.00"}, - ("reduced=50.00", "50.00")), + {"caps": ("reduced=50.00", "50.00")}), ("/rules", "rule_id", {"rule_id": "u-threshold", "kind": "threshold", "sku": "", - "percent": "5", "minimum": "200.00"}, - ("200.00",))) - for path, key, body, shown_as in written: + "percent": "5", "minimum": "200.00"}, {})) + for path, key, body, forms in written: created(path, body) text = text_of(page(client, path)) if body[key] not in text: failures.append("a record posted to %s after the upgrade is not " "listed" % path) continue - if not shown_as: - continue tokens = row_tokens(page(client, path).get_data(as_text=True), body[key]) if tokens is None: unfound.append(body[key]) - elif not any(has_token(tokens, token) for token in shown_as): - failures.append("%s lists %s without the %s it was posted with" - % (path, body[key], shown_as[0])) + continue + for field, value in body.items(): + wanted = forms.get(field) + if wanted is None: + missed = [token for token in TOKEN_SPLIT.split(value) + if token and not has_token(tokens, token)] + else: + missed = [] if any(has_token(tokens, token) + for token in wanted) else [value] + if missed: + failures.append("%s lists %s without the %s it was posted " + "with" % (path, body[key], value)) if not failures and unfound: return {"passed": None, "missing": "row for %s not found" % unfound[0]} @@ -2269,7 +2276,8 @@ def create_app(database): # jurisdiction's listed rates, which no invoice prices with and only its page # shows, `extending` appends a digit to them, the old rates still inside the # new, `fresh` adds the columns to new files alone and reads an old one -# without them, silently dropping the field a new record sets, `fragile` +# without them, silently dropping the field a new record sets, `garbling` +# stores a new jurisdiction under another name and rates, `fragile` # cannot read an old # jurisdiction's empty cap, so old invoices break while new ones open, and # `refusing` will not open an old file at all. At version 1, `unlisting` @@ -2456,12 +2464,16 @@ def listing(self, connection, table): if table == "products": rows = connection.execute("SELECT sku, name, unit_price FROM " "products") - elif table == "rules" and VERSION == 2 and "minimum" in columns( - connection, "rules"): - rows = connection.execute("SELECT rule_id, kind, minimum FROM " - "rules") elif table == "rules": - rows = connection.execute("SELECT rule_id, kind FROM rules") + minimum = VERSION == 2 and "minimum" in columns(connection, + "rules") + rows = [] + for found in connection.execute( + "SELECT rule_id, kind, sku, detail%s FROM rules" + % (", minimum" if minimum else "")): + row = (found[0], found[1], found[2] or "", + json.loads(found[3]).get("percent") or "") + rows.append(row + ((found[4] or "",) if minimum else ())) elif VERSION == 2 and "caps" in columns(connection, "jurisdictions"): rows = connection.execute("SELECT code, name, default_rate, " "rates, caps FROM jurisdictions") @@ -2499,6 +2511,8 @@ def create(self, connection, table, data): connection.execute("INSERT INTO rules (%s) VALUES (%s)" % ( ", ".join(names), ", ".join("?" for _ in names)), values) else: + if MODE == "garbling": + data = dict(data, name="Garbled", rates="standard=0.9") self.app.add_jurisdiction(connection, data["code"], data["name"], data["default_rate"], data.get("rates") or "", @@ -2616,7 +2630,7 @@ def create_app(database): # The faults the data upgrade must catch at version 2, and what each loses. UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", - "extending", "fresh", "fragile", "refusing") + "extending", "fresh", "garbling", "fragile", "refusing") def plant_upgrade(where, version, mode): @@ -2706,6 +2720,15 @@ def upgrade_self_checks(scratch): hidden.get("passed") is None and hidden.get("missing", "").startswith("row for ") and hidden["missing"].endswith(" not found")), + ("a new record stored with other values than it was posted with " + "fails the upgrade", + faults["garbling"].get("passed") is False + and faults["garbling"].get("failures") == [ + "/jurisdictions lists %s without the %s it was posted with" + % (code, value) for code, value in ( + ("U2", "Upgradia Nova"), ("U2", "standard=0.1"), + ("U3", "Upgradia Capped"), + ("U3", "standard=0.2,reduced=0.05"))]), ("a list-item row with a value the change adds keeps every old one", items.get("passed") is True and not items.get("failures")), ("a schema changed for new files alone fails on the change's own " diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index ade39e0..8d9d522 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -3311,7 +3311,7 @@ def round5d_section(trials, table, results, seed, margins, # A skill's file named in an operand, by its path under the folder the arm # installs its skills in: reading it reads the skill, as loading it does. SKILL_OPERAND = re.compile(re.escape(SKILLS_INTO + "/") - + r"([\w.*?\[\]-]+/SKILL\.md)") + + r"([\w.*?\[\]-]+/[\w.*?\[\]-]+)") SKILL_FILE = "SKILL.md" # A redirection that writes no file: to the null device, or of one stream @@ -3815,15 +3815,18 @@ def skill_reads(name, given, command, known, writes_at, first_write, before): """The skills a read or a shell command reads the file of, by name, each a shell command read before its first write added to `before`.""" + # A read names a skill's file, or matches it through a wildcard, which + # the shell's reading resolves against the skills' own files; any other + # file in a skill's folder is no reading of the skill. files = sorted("%s/%s" % (skill, SKILL_FILE) for skill in known) if name == "Read": path = str(given.get("file_path") or "").replace("\\", "/") return [read.split("/")[0] for read in SKILL_OPERAND.findall(path) - if read.split("/")[0] in known] + if read in files] found = [] for index, read in shell_reads(command, files, SKILL_OPERAND): skill = read.split("/")[0] - if skill in known: + if read in files: found.append(skill) if first_write is None and (writes_at is None or index < writes_at): @@ -6222,6 +6225,8 @@ def round3_checks(seed): "base-quality\\SKILL.md"}), ("Bash", {"command": "cat .claude/skills/backend-*/SKILL.md"}), ("Bash", {"command": "ls .claude/skills"}), + ("Bash", {"command": "cat .claude/skills/base-quality/*.md"}), + ("Read", {"file_path": "/pen/.claude/skills/backend-api/x.md"}), ("Read", {"file_path": "/pen/.claude/skills/other/SKILL.md"})] with io.open(planted, "w", encoding="utf-8", newline="\n") as handle: for turn, (name, given) in enumerate(calls, 1): @@ -6250,6 +6255,11 @@ def states(low, high): templates_read({"lazyskills-1": used}, "lazyskills") == 3.0 and sorted({skill for _, skill in used["uses"]}) == ["backend-api", "backend-auth", "base-quality"]), + ("a wildcard read of one skill's folder counts that skill once, " + "another file there none", + [skill for turn, skill in used["uses"] if turn == 5] + == ["base-quality"] + and not any(turn == 6 for turn, _ in used["uses"])), ("C1 reads an axis non-inferior only with its lower bound strictly " "above minus the margin", states(-margin, -margin) == "inconclusive" diff --git a/tests/efficacy/score.py b/tests/efficacy/score.py index 64f049d..003f711 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -1466,13 +1466,17 @@ def interfaces(build_suite, fixture): for module in INTERFACE_MODULES): return absent("the change task names no fixture whose interface " "modules were frozen") - if build_suite.get("missing"): + # A suite that ran out of time was held there by the tree under it, so + # every interface fails, whether or not a report was left to read. + report = build_suite.get("report") or {} + timed_out = report.get("timed_out") is True + if build_suite.get("missing") and not timed_out: return absent("the build suite did not run on the changed tree: %s" % build_suite["missing"]) - report = build_suite.get("report") modules = {} for module in INTERFACE_MODULES: - before, after = baseline[module], module_whole(report, module) + before = baseline[module] + after = False if timed_out else module_whole(report, module) verdict = ({(True, True): "kept", (True, False): "broken", (False, True): "repaired", (False, False): "inherited"} [(before, after)]) @@ -1830,6 +1834,12 @@ def fixture(failed=()): inherited = interfaces(suite(failing=[api]), fixture(failed=[api])) repaired = interfaces(suite(), fixture(failed=[api])) none_held = interfaces(suite(), fixture(failed=INTERFACE_MODULES)) + + # Out of time before a report was written, and after one was begun. + stopped = interfaces(absent("the grader wrote no report", report={ + "timed_out": True}), fixture()) + partway = interfaces(measured(None, report=dict( + suite()["report"], timed_out=True)), fixture()) return [ ("a change keeping every interface the fixture passed reads 1", kept["value"] == 1.0 and not kept["broken"]), @@ -1844,6 +1854,10 @@ def fixture(failed=()): ("a module the change repaired reads repaired", repaired["value"] == 1.0 and repaired["modules"][api]["verdict"] == "repaired"), + ("a build suite that ran out of time fails every interface, not " + "missing", + stopped["value"] == 0.0 and stopped["broken"] + == list(INTERFACE_MODULES) and partway["value"] == 0.0), ("interfaces read missing with no frozen baseline, no build suite, " "or none the fixture passed", interfaces(suite(), None)["missing"] is not None From 6296338875c2eff81b1b193990957353c77bd13f Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:02:45 +0200 Subject: [PATCH 15/18] fix(efficacy): Codex round 11 on reuse and the new invoice's exports - reused change tasks join a target only where its change runs took the same fixture manifest and block mapping, refused before anything is copied - the invoice saved after the upgrade is read as the old ones are: its page and both exports must answer a success Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 ++-- docs/requirements.md | 4 ++-- tests/efficacy/quality.py | 24 ++++++++++++++++++++-- tests/efficacy/reuse.py | 42 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 67 insertions(+), 7 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 6a3b6bb..37569c8 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,10 +239,10 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "a build suite that ran out of time fails every interface, not missing"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a new record stored with other values than it was posted with fails the upgrade"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "an invoice saved after the upgrade whose CSV export errs fails it"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a new record stored with other values than it was posted with fails the upgrade"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | -| FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders" | +| FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders"
    `reuse.py` "change tasks join a target only from the manifest its change runs took" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
    `report.py` "a C1 run gives lazysections and lazyrefold a verdict and a cost on each task, against none"
    `report.py` "each task's radar reads that task's trees against `none` on the same task"
    `report.py` "the change task's radar reads its own security, not the build's"
    `report.py` "a named round's build radar leaves the change targets to the change task's"
    `report.py` "each task's radar shows its own mean billed cost per trial"
    `report.py` "a pilot round draws one radar, its trials as they are"
    `report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
    `report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
    `report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
    `report.py` "named pairs are read for every metric of a table" | | FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
    `report.py` "the check loop is not kept on the build task's readings alone"
    `report.py` "a cost drop under 10 % on one task does not keep the check loop"
    `report.py` "an axis worse on either task does not keep the check loop"
    `report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
    `report.py` "an interval crossing the margin is inconclusive, never non-inferior"
    `report.py` "the report and its full record print the registered readings"
    `report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
    `report.py` "a cost drop a float's error under 10 % meets the gate"
    `report.py` "a cost drop a float's error under 10 % reads yes in the table and keeps the loop"
    `report.py` "C1 reads an axis non-inferior only with its lower bound strictly above minus the margin"
    `report.py` "a round running none of the registered pairs prints none of them" | | FR-16-10 | Self-test | `report.py` "an arm delivers on demand only reading fewer templates than reference and non-inferior to it"
    `report.py` "an arm whose reads were not counted is not shown on demand"
    `report.py` "each task's templates read are counted from its own transcripts, a section file by a read or a shell command"
    `report.py` "a task's reading left out of the report counts no template use on that task"
    `report.py` "a wildcard read of one skill's folder counts that skill once, another file there none"
    `report.py` "a skill's file read or shell-read is that skill used, once with its loading" | diff --git a/docs/requirements.md b/docs/requirements.md index 990e2e1..c1fcc8f 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,10 +252,10 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not met for every module where the build suite ran out of time; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, or the upgraded file refuses new records, ones setting the fields the change added among them, every value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, that of the invoice saved after the upgrade included, or the upgraded file refuses new records, ones setting the fields the change added among them, every value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | -| FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, with every reading and judging of its own. | Archive, Reuse | +| FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, refused into a target whose change runs took another manifest or block mapping, with every reading and judging of its own. | Archive, Reuse | | FR-16-08 | From round 6 the benchmark shall draw the ISO radar and give each arm's verdict once a task: the build trials on the build, each change task's tree on the change, each against `none` on the same task, the change targets on the change task's radar alone, and a round with no build reading its finding table from the change task's own trials, cost and contrasts; name the task in the summary, its tables and the plain report; and show each task's mean billed cost per trial beside its radar, never scored. A pilot round draws one radar over its trials as they are. | Report | | FR-16-09 | For round C1 the benchmark shall read the check loop as `lazyref` against `lazyrefold`, paired by block on each task: kept only where both tasks are read, the point estimate of the mean billed cost per trial, read from the unrounded paired differences, drops by at least 10 % on each, within 1e-9, its interval printed beside it, and no ISO axis reads worse on either, and not decided while a task is unread; an axis worse only where its whole interval lies past the margin downward, nothing flagged reading "no degradation detected under the registered rule"; non-inferior only where every measured axis's lower bound lies strictly above minus its margin, one on or below it inconclusive; and read `lazysections` against `lazyref` and against `reference` the same way, with its cost, and no gate. | Report | | FR-16-10 | For round C1 the benchmark shall read an on-demand arm (`lazyref`, `lazyskills`, `lazysections`) as delivering on demand on a task only where its trials read fewer templates on average than `reference`'s, counted from the transcripts of that task's trials the report reads, a file read by a read or a reading command, a wildcard standing for each file it matches, a skill's file read, by its name or a wildcard, counted once with its loading, and it is non-inferior to `reference` on every measured axis; and as not shown otherwise. | Report | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index f72a6fa..26f5b7a 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1394,7 +1394,15 @@ def data_upgrade(seeded): if saved is None: failures.append("an invoice saved after the upgrade has no page") else: + # The new invoice is read as the old ones are: its page and both + # exports answering a success before its total counts. again = invoice_reading(saved) + for status, what in ((again["status"], saved), + (again["export_status"], + saved + "/export.json"), + (again["csv_status"], saved + "/export.csv")): + if not 200 <= status < 300: + failures.append("%s answered %d" % (what, status)) total = (again["export"] or {}).get("total") if isinstance( again["export"], dict) else None if str(total) != str(seeded["invoices"][0]["export"].get("total")): @@ -2287,7 +2295,9 @@ def create_app(database): # found in, one ending `+pcells` wraps each table cell in a paragraph, one # ending `+terse` writes the minimum as 200, each price after the euro's # sign and the cap as euro 50, and one -# ending `+erring` answers its JSON export 500 with a whole body. +# ending `+erring` answers its JSON export 500 with a whole body, and one +# ending `+newcsv` answers 500 for the CSV export of an invoice saved after +# the two the seed saves. UPGRADE_APP = '''import decimal import json import os @@ -2614,6 +2624,9 @@ def invoices(self, connection, parts, method, data): export["caps"] = {} return Response(500 if MARKUP == "erring" else 200, json.dumps(export)) + if parts[2:] == ["export.csv"] and MARKUP == "newcsv" \\ + and int(parts[1]) > 2: + return Response(500, "Internal Server Error") if parts[2:] == ["export.csv"]: head = "sku,quantity,net" + (",cap" if VERSION == 2 else "") return Response(200, "\\n".join([head] + [ @@ -2673,6 +2686,7 @@ def upgrade_self_checks(scratch): rewrapped = upgrade_reading(scratch, "sound+pcells", "rerating+pcells") terse_read = upgrade_reading(scratch, "sound", "sound+terse") erring = upgrade_reading(scratch, "sound", "sound+erring") + new_csv = upgrade_reading(scratch, "sound", "sound+newcsv") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) return [ @@ -2715,7 +2729,13 @@ def upgrade_self_checks(scratch): erring.get("passed") is False and erring.get("failures") == [ "/invoices/1/export.json answered 500", - "/invoices/2/export.json answered 500"]), + "/invoices/2/export.json answered 500", + "/invoices/3/export.json answered 500"]), + ("an invoice saved after the upgrade whose CSV export errs fails " + "it", + new_csv.get("passed") is False + and new_csv.get("failures") == ["/invoices/3/export.csv answered " + "500"]), ("a row found by no key leaves the upgrade missing, never passed", hidden.get("passed") is None and hidden.get("missing", "").startswith("row for ") diff --git a/tests/efficacy/reuse.py b/tests/efficacy/reuse.py index 4406434..e22532b 100644 --- a/tests/efficacy/reuse.py +++ b/tests/efficacy/reuse.py @@ -24,7 +24,8 @@ import lib # noqa: E402 from harness import (ARMS, PROMPT, REGISTRATIONS, TrialError, # noqa: E402 - assert_outside_repository, canonical, identity_problem, + assert_outside_repository, canonical, fixtures_problem, + identity_problem, now, project_folder, read_change_prompt, recorded_round, registration_digest, remove_tree, scorable_trials, scoring_area, task_folder, write_run) @@ -199,6 +200,16 @@ def reuse(source, target, arms): if clash: raise TrialError("%s already offers %s" % (target, ", ".join(clash))) changes, fixtures = change_tasks(source, arms) + + # Change tasks of one named round start every arm of a block from one + # fixture, so the source's must have taken the target's manifest and + # block mapping, as a change run joining the target must. + if changes and fixtures: + problem = fixtures_problem(target, dict( + fixtures, blocks=fixtures.get("blocks") or {})) + if problem: + raise TrialError("the change tasks cannot join %s: %s" + % (target, problem)) try: held = scorable_trials(target, task="change") except TrialError: @@ -395,9 +406,38 @@ def change_checks(scratch): and os.path.isfile(os.path.join(area, "judge-change", "T1.json")) and read_map(area, "change")["blind"] == {"inline-1": "T1"} and read_map(area)["blind"] == {"inline-1": "T2", "hand-1": "T1"}), + ("change tasks join a target only from the manifest its change " + "runs took", manifest_checks(scratch, identity)), ] +def manifest_checks(scratch, identity): + """Change tasks reused into a target whose change runs took another + fixture manifest are refused before anything is copied; into one that + took the same, they come along.""" + def target_with(name, manifest): + target = os.path.join(scratch, name) + os.makedirs(target) + write_run(os.path.join(target, "run-earlier-change.json"), + datetime.datetime(2026, 9, 17, 12, 0, 0), [], "change", + read_change_prompt(), + identity=dict(identity, fixtures={ + "manifest_sha256": manifest, "blocks": {}})) + return target + other = target_with("other-manifest", "0" * 64) + same = target_with("same-manifest", "f" * 64) + source = os.path.join(scratch, "changed") + try: + reuse(source, other, ["inline"]) + refused = False + except TrialError as error: + refused = "manifest" in str(error) + reuse(source, same, ["inline"]) + return (refused and not os.path.exists(os.path.join(other, + "inline-1.tar")) + and os.path.isfile(os.path.join(same, "change-inline-1.tar"))) + + def self_test(): """Prove a reuse copies the chosen arms' trials, and only those, under the words, and refuses to offer a trial twice.""" From e745f6c5ef3cbd0b8f0d496125f2921646a68434 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:18:16 +0200 Subject: [PATCH 16/18] feat(efficacy): the data upgrade claims exported values and exercised behaviour - values are read from the exports the spec fixes: each old invoice's JSON, every old key and value, lists in order, and its CSV by column, row by row; the customer's export; extra keys and columns allowed - every old invoice's body is saved again and must export as the fixture's did, its new id aside, in place of the total alone - the change's own fields are read by their effect: a capped jurisdiction and a threshold rule posted on the copy, invoices saved through the app opened afresh below, at and above the threshold and the cap, against the change's semantics; the seed's invoice percentage deleted first - list pages count for presence alone: a seeded code or rule id named whole, whatever the markup - removed: the row reading, same_token/has_token and currency handling, the preview total search, and missing for a row not found - the stand-in prices the spec's way; HTML-layout modes dropped, new modes for a customer rewritten and a rule that will not delete - FR-16-04, its coverage and ch. 8 state the narrowed claim Refs #178, #158. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/08-crosscutting-concepts.md | 23 +- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 929 +++++++++--------- 4 files changed, 466 insertions(+), 490 deletions(-) diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 4e173aa..8575812 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -376,15 +376,28 @@ axis only: | Reading | What it reads | Fails when | ISO place | | ------- | ------------- | ---------- | --------- | | Interfaces | The hidden suite's API, route and two export modules on the changed tree, against the fixture's frozen baseline | A module the fixture passed whole no longer does | Compatibility, Interoperability | -| Data upgrade | Products, customers, rules, a jurisdiction and invoices saved through the fixture's own forms, then the changed tree on a copy of that database | A record is gone or reads differently, an old invoice will not open or price as it did, or the file takes no new record | Flexibility, Adaptability | +| Data upgrade | Products, customers, rules, a jurisdiction and invoices saved through the fixture's own forms, then the changed tree on a copy of that database | An export no longer reads as it did, an old invoice saved again prices otherwise, a seeded code or rule id is gone from its list page, or the change's own fields do not price as the change says | Flexibility, Adaptability | - **Inherited is not broken.** An interface module the fixture already failed is the fixture's, not the change's, and counts neither way (FR-16-02). -- **Values, not counts.** Each record is read back as the fixture showed - it: every field of its row on the list pages, each invoice's JSON and CSV exports, the customer's - export, and the old invoice priced again. A key or column only the - changed tree has is the change's own, and is no loss (FR-16-04). +- **Exported values, exercised behaviour.** Values are read from the + exports the specification fixes, never from the pages' markup: each old + invoice's JSON, every old key and value, lists as long and in order, and + its CSV, every old column by name, row by row; the customer's export; and + each old invoice's body saved again, its export the fixture's but for + its id. A key or column only the changed tree has is the change's own, + and is no loss. The list pages count only for presence: a seeded code or + rule id named whole, whatever the markup (FR-16-04). +- **The change's own fields, by their effect.** A capped jurisdiction and + a threshold rule are posted on the upgraded copy, and invoices saved + through the application opened afresh on it must give the applied rules, + discount, tax and total the change's semantics give, below, at and above + the threshold and the cap. The seed's invoice percentage, which would + share the threshold's slot, is deleted first, on the copy alone. +- **Outside the claim.** A jurisdiction's name, a parameter no invoice + exercises and an equivalent internal form can change unread: the reading + claims exported values kept and exercised behaviour, not every field. - **Lost and missing.** A changed tree that will not open the file, or sign in on it, has lost the data and fails. A fixture that cannot seed is no arm's, so the reading is missing. Each reading names the fixture's diff --git a/docs/coverage.md b/docs/coverage.md index 37569c8..929efb1 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -239,7 +239,7 @@ when: | FR-16-01 | Self-test | `score.py` "a changed tree is scored on every reading a build is"
    `score.py` "a file the scorer's install writes is no unasked artifact of a changed tree"
    `score.py` "an unchanged app that writes a secret beside its database at boot shows no churn"
    `score.py` "a changed tree with the change's names exports no extra one, and one without them misses each"
    `score.py` "the build is read against the build's names, the change against the change's too" | | FR-16-02 | Self-test | `score.py` "a change keeping every interface the fixture passed reads 1"
    `score.py` "an interface module the change broke reads 0 and is named"
    `score.py` "a skipped or unrun interface module is not kept"
    `score.py` "a module the fixture already failed is inherited, not the change's"
    `score.py` "a module the change repaired reads repaired"
    `score.py` "a build suite that ran out of time fails every interface, not missing"
    `score.py` "interfaces read missing with no frozen baseline, no build suite, or none the fixture passed"
    `harness.py` "a fixture whose baseline leaves an interface module unread is refused" | | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | -| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "rows all kept with their values changed fail the upgrade"
    `quality.py` "a listed field changed by the migration, no invoice priced by it, fails the upgrade"
    `quality.py` "a listed field kept only inside a longer one fails the upgrade"
    `quality.py` "a table row whose cells are paragraphs is read whole: kept when sound, its cleared values named"
    `quality.py` "a value written as another amount, a sign before it or no trailing zeros, reads as the same value"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "an invoice saved after the upgrade whose CSV export errs fails it"
    `quality.py` "a row found by no key leaves the upgrade missing, never passed"
    `quality.py` "a new record stored with other values than it was posted with fails the upgrade"
    `quality.py` "a list-item row with a value the change adds keeps every old one"
    `quality.py` "a schema changed for new files alone fails on the change's own fields"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | +| FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "a rate the migration changes fails the invoices saved again too"
    `quality.py` "category rates cleared or changed by the migration fail the upgrade through the exports"
    `quality.py` "a customer the migration rewrites fails through the customer's export alone"
    `quality.py` "a change's field dropped on an old file fails through the invoices that exercise it"
    `quality.py` "a new jurisdiction stored with other rates fails through its invoices"
    `quality.py` "a seeded rule that will not be deleted stops the change's invoices, never passes"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "the list pages are read for the seeded identifiers alone, whatever their markup"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "an invoice saved after the upgrade whose CSV export errs fails it"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | | FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders"
    `reuse.py` "change tasks join a target only from the manifest its change runs took" | diff --git a/docs/requirements.md b/docs/requirements.md index c1fcc8f..bbc1cf7 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -252,7 +252,7 @@ | FR-16-01 | The benchmark shall score a change task's tree on every reading a build's is, with the build and change suites in place of the one suite, its churn and scope taken before the install, the boot or the battery write into the tree, the boot's database and what the app keeps beside it written outside the tree, its public surface read against the build's names and each the pinned change prompt calls on the package, and its security reading filed beside its score. | Scorer | | FR-16-02 | The benchmark shall read a change task's interfaces against its fixture's frozen baseline: met where every one of `test_api_contract.py`, `test_http_routes.py`, `test_export_json.py` and `test_export_csv.py` the fixture passed whole passes whole on the changed tree, not met where one does not, a module the fixture already failed inherited and counted neither way; not met for every module where the build suite ran out of time; not measured with no baseline, no build suite, or none the fixture passed; and refuse a fixture whose baseline does not say which of the four it passed. | Scorer, Harness | | FR-16-03 | The benchmark shall read the security and quality probes on a change task's tree from its own score into folders of its own, a tree that does not install losing them as a build's does. | Security reader, Quality reader | -| FR-16-04 | The benchmark shall read a change task's data upgrade: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a record is gone or reads differently, a field its list page showed, a price or rate among them, included, each value of its row compared whole, as text or, a leading currency set aside, as the same amount, a row being the outermost table row, list item or paragraph the page holds, all it contains included, an old invoice does not open or price as it did, an export it reads answers other than a success, that of the invoice saved after the upgrade included, or the upgraded file refuses new records, ones setting the fields the change added among them, every value posted read back whole in its row; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed, the change names no starting commit, or a seeded record's row is not found by its key on a page that still shows it; each reading naming the fixture's hash, the starting commit and the seeded database's hash. | Quality reader | +| FR-16-04 | The benchmark shall read a change task's data upgrade, a claim of exported values kept and exercised behaviour: products, customers, rules, a jurisdiction and invoices seeded through the forms of the application at the change's starting commit, then a copy of that database opened by the changed tree; failed where a list page answers other than a success or no longer names a seeded jurisdiction's code or rule's id as a whole identifier, whatever its markup; where an export answers other than a success, or an old invoice's JSON export no longer holds every old key and value, lists as long and in order, or its CSV export every old column's values, row by row, the total row's included, a key or column only the change has allowed; where the customer's export no longer reads the same; where an old invoice's body saved again no longer exports as the fixture's did, its new id aside; or where the change's own fields, posted on the upgraded copy and read through the application opened afresh on it, do not give the applied rules, discount, tax and total the change's semantics give below, at and above the threshold and the cap; lost where the changed tree does not install, open the file or sign in; missing where the fixture cannot seed or the change names no starting commit; each reading naming the fixture's hash, the starting commit and the seeded database's hash. A jurisdiction's name, a parameter no invoice exercises and an equivalent internal form are outside the claim. | Quality reader | | FR-16-05 | The benchmark shall judge a change task's tree blind, apart from the build's, with labels and a map of its own, against the specification and the pinned change prompt, carried in its bundle, the judge told that the change extends the specification, the build's prompt unchanged; and not judge one that did not install. | Judge | | FR-16-06 | From round 6 the benchmark shall read a change task's interfaces on Interoperability and its data upgrade on Adaptability, each once, whatever its build did, its security and quality readings and judgings going only with its change score; a pilot round reads neither. | Report | | FR-16-07 | The benchmark shall archive a change task's security and quality readings and judgings, verify an archive by each task's ISO reading and the registered readings too, and reuse a change task with its arm's build trials, in a change run of its own naming its round's fixtures, refused into a target whose change runs took another manifest or block mapping, with every reading and judging of its own. | Archive, Reuse | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 26f5b7a..ee97bc0 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -6,7 +6,8 @@ side, and the same build on another Python. Each passes or fails, except the latency, which is recorded as two repeats of its 95th percentile. A change task's tree is read on the same probes and on one more, the data upgrade: a -database its fixture seeded, opened by the changed tree with nothing lost. +database its fixture seeded, opened by the changed tree, its exported values +kept and the change's own fields pricing as the change says. Each trial is installed into a fresh environment of its own, on the spec's Python, and read there in one in-process run through the test client. A probe @@ -1006,23 +1007,6 @@ def fuzz_robustness(): statuses=[entry.get("status") for entry in answers]) -# An amount as a page may write it, which the data upgrade reads an old -# invoice's price back by: grouped by thousands with a comma, a point, a -# space, a no-break or narrow no-break space, or an apostrophe, and two -# decimals after a point or a comma. The page is read with its character -# references resolved, so ` ` and ` ` group as the characters do. -AMOUNT = re.compile(r"(?]+>") + +# The identifiers the list pages must still name after the upgrade. The +# pages are read for presence alone: what each record holds is read from +# the exports the specification fixes, never from the markup. +PRESENCE = {"/jurisdictions": [UPGRADE_JURISDICTION["code"]], + "/rules": [item["rule_id"] for item in UPGRADE_RULES]} def upgrade_body(jurisdiction, customer, lines, coupons): @@ -1054,13 +1045,29 @@ def upgrade_body(jurisdiction, customer, lines, coupons): "quantity": [str(quantity) for _, quantity in lines]} +def upgrade_bodies(customer): + """The invoices the fixture saves: one in the seeded jurisdiction with a + line under each seeded rule, the coupon, a category's own rate and the + default rate, and one on the seed's own data and rules.""" + return (upgrade_body("UP", customer, (("UPG-1", 3), ("UPG-2", 4), + ("SEE-5", 1)), "UPGRADE"), + upgrade_body("DE", "", WORKED, "WELCOME")) + + def text_of(answer): - return html.unescape(answer.get_data(as_text=True)) + """A page's text, its markup taken out and its references decoded.""" + return html.unescape(TAG.sub(" ", answer.get_data(as_text=True))) + + +def identified(answer, identifier): + """Whether a page names `identifier` whole, whatever markup holds it.""" + return re.search(r"(?`s, which no row is -# found in, one ending `+pcells` wraps each table cell in a paragraph, one -# ending `+terse` writes the minimum as 200, each price after the euro's -# sign and the cap as euro 50, and one -# ending `+erring` answers its JSON export 500 with a whole body, and one -# ending `+newcsv` answers 500 for the CSV export of an invoice saved after -# the two the seed saves. -UPGRADE_APP = '''import decimal +# A stand-in for the data upgrade, a fixture at version 1 and a changed tree at +# version 2 of one application on a real SQLite file. It prices an invoice the +# specification's way, closely enough to be read by it: a line's percentage and +# bulk rules, one invoice percentage, seeded as the specification seeds one, a +# coupon's amount, each category's rate or the default, and exports of the +# specification's keys and columns. Version 2 adds a threshold rule, sharing +# the invoice percentage's slot from its minimum on, and a cap on a category's +# rate, and adds the columns to an old file; its exports carry one key and one +# column more. `sound` does all of that. Each other mode plants one fault in +# version 2 alone: `unmigrated` adds the columns to new files only and then +# reads them, `dropping` rebuilds an old file empty, `rewriting` migrates and +# resets every jurisdiction's default rate, `rerating` clears every +# jurisdiction's category rates, `extending` appends a digit to them, +# `readdressing` rewrites every customer's address, `fresh` adds the columns to +# new files alone and silently drops the field a new record sets on an old one, +# `garbling` stores a new jurisdiction's rates as others, `undeletable` keeps a +# rule its delete names, `fragile` cannot read an old jurisdiction's empty cap, +# so old invoices break, and `refusing` will not open an old file at all. At +# version 1, `unlisting` links no customer, so nothing can be seeded. A mode +# ending `+divs` lists its records in bare `
    `s, one ending `+erring` +# answers its JSON exports 500 with a whole body, and one ending `+newcsv` +# answers 500 for the CSV export of an invoice saved after the two the seed +# saves. +UPGRADE_APP = r'''import decimal import json import os import sqlite3 @@ -2315,6 +2226,8 @@ def create_app(database): TABLES = ("products", "customers", "rules", "jurisdictions", "invoices", "lines") ADDED = (("rules", "minimum"), ("jurisdictions", "caps")) +CSV_HEAD = ("sku,name,quantity,unit_price,gross,line_discount,net," + "invoice_discount,taxable,tax,total") class Response(object): @@ -2327,17 +2240,6 @@ def get_data(self, as_text=False): return self._body if as_text else self._body.encode("utf-8") -def terse(value): - """A value as a terse page writes it: the minimum without its trailing - zeros, a price after the euro's sign, a cap with it.""" - text = str(value) - if text == "200.00": - return "200" - if text.replace(".", "", 1).isdigit() and "." in text: - return "\u20ac" + text - return text.replace("=50.00", "=\u20ac50") - - def form(action, body=""): return ('%s
    %s
    ' % (body, action, TOKEN)) @@ -2348,6 +2250,20 @@ def columns(connection, table): "PRAGMA table_info(%s)" % table)] +def pairs(text): + """A `category=value` list as a dict of Decimals.""" + found = {} + for item in (text or "").split(","): + if "=" in item: + key, _, value = item.partition("=") + found[key.strip()] = decimal.Decimal(value) + return found + + +def money(value): + return str(value.quantize(CENT, rounding=decimal.ROUND_HALF_EVEN)) + + class App(object): def __init__(self, database): self.database = database @@ -2389,6 +2305,8 @@ def __init__(self, database): if MODE == "extending": connection.execute("UPDATE jurisdictions SET rates = rates " "|| '1' WHERE rates != ''") + if MODE == "readdressing": + connection.execute("UPDATE customers SET address = 'moved'") if not connection.execute("SELECT * FROM admin").fetchone(): connection.execute("INSERT INTO admin VALUES (?)", ( os.environ.get("TARIFF_ADMIN_PASSWORD"),)) @@ -2397,6 +2315,10 @@ def __init__(self, database): "(?, ?, ?, ?)", SEED) for code, rate in (("DE", "0.19"), ("IE", "0.23")): self.add_jurisdiction(connection, code, code, rate, "") + connection.execute("INSERT INTO rules (rule_id, kind, sku, " + "detail) VALUES (?, ?, ?, ?)", ( + "r-pct-all", "percentage", "", + json.dumps({"percent": "5"}))) connection.commit() connection.close() @@ -2409,7 +2331,7 @@ def add_jurisdiction(self, connection, code, name, rate, rates, code, name, rate, rates] if VERSION == 2 and "caps" in columns(connection, "jurisdictions"): names.append("caps") - values.append(caps or "{}") + values.append(caps or "") connection.execute("INSERT INTO jurisdictions (%s) VALUES (%s)" % ( ", ".join(names), ", ".join("?" for _ in names)), values) @@ -2458,7 +2380,12 @@ def dispatch(self, connection, path, method, data): parts = path.strip("/").split("/") if path == "/": return Response(200, "dashboard") - if parts[0] in ("products", "rules", "jurisdictions") \\ + if parts[0] == "rules" and parts[2:] == ["delete"]: + if MODE != "undeletable": + connection.execute("DELETE FROM rules WHERE rule_id = ?", + (parts[1],)) + return Response(302, "", {"Location": "/rules"}) + if parts[0] in ("products", "rules", "jurisdictions") \ and len(parts) == 1: if method == "POST": return self.create(connection, parts[0], data) @@ -2475,34 +2402,17 @@ def listing(self, connection, table): rows = connection.execute("SELECT sku, name, unit_price FROM " "products") elif table == "rules": - minimum = VERSION == 2 and "minimum" in columns(connection, - "rules") - rows = [] - for found in connection.execute( - "SELECT rule_id, kind, sku, detail%s FROM rules" - % (", minimum" if minimum else "")): - row = (found[0], found[1], found[2] or "", - json.loads(found[3]).get("percent") or "") - rows.append(row + ((found[4] or "",) if minimum else ())) - elif VERSION == 2 and "caps" in columns(connection, "jurisdictions"): - rows = connection.execute("SELECT code, name, default_rate, " - "rates, caps FROM jurisdictions") + rows = connection.execute("SELECT rule_id, kind FROM rules") else: rows = connection.execute("SELECT code, name, default_rate, " "rates FROM jurisdictions") - if MARKUP == "terse": - rows = [tuple(terse(value) for value in row) for row in rows] + rows = list(rows) if MARKUP == "divs": return "".join("
    %s
    " % " ".join(str(value) for value in row) for row in rows) - if MODE == "items": - return "
      %s
    " % "".join( - "
  • %s
  • " % " ".join(str(value) for value in row) - for row in rows) - cell = "

    %s

    " if MARKUP == "pcells" else "%s" return "%s
    " % "".join( - "%s" % "".join(cell % value for value in row) + "%s" % "".join("%s" % value for value in row) for row in rows) def create(self, connection, table, data): @@ -2522,7 +2432,7 @@ def create(self, connection, table, data): ", ".join(names), ", ".join("?" for _ in names)), values) else: if MODE == "garbling": - data = dict(data, name="Garbled", rates="standard=0.9") + data = dict(data, rates="standard=0.9") self.app.add_jurisdiction(connection, data["code"], data["name"], data["default_rate"], data.get("rates") or "", @@ -2555,43 +2465,120 @@ def customers(self, connection, parts, method, data): "address": row[3], "invoices": invoices})) def priced(self, connection, jurisdiction, coupons, lines): + """An invoice priced as the specification orders it, to the keys + of its JSON export.""" found = connection.execute("SELECT * FROM jurisdictions WHERE code " "= ?", (jurisdiction,)).fetchone() if found is None: raise LookupError(jurisdiction) - rate = decimal.Decimal(found[2]) - if VERSION == 2: - caps = found[4] if len(found) > 4 else "{}" - json.loads(caps if MODE == "fragile" else caps or "{}") - rules = [(kind, sku, json.loads(detail)) for kind, sku, detail - in connection.execute("SELECT kind, sku, detail FROM rules")] - net = [] + default, rates = decimal.Decimal(found[2]), pairs(found[3]) + # Version 2 reads the columns it added, which an old file lacks + # unless they were added to it; `fresh` looks before it reads. + caps, has_minimum = {}, VERSION == 2 + if VERSION == 2 and MODE == "fresh": + has_minimum = "minimum" in columns(connection, "rules") + if has_minimum: + text = connection.execute("SELECT caps FROM jurisdictions WHERE " + "code = ?", (jurisdiction,)).fetchone() + caps = pairs(text[0].strip() if MODE == "fragile" + else text[0] or "") + rules = [(row[0], row[1], row[2], json.loads(row[3]), + row[4] if has_minimum else None) + for row in connection.execute( + "SELECT rule_id, kind, sku, detail%s FROM rules " + "ORDER BY rule_id" % (", minimum" if has_minimum + else ""))] + priced = [] for sku, quantity in lines: - price = connection.execute("SELECT unit_price FROM products " - "WHERE sku = ?", (sku,)).fetchone() - amount = decimal.Decimal(price[0]) * quantity - for kind, scope, detail in rules: - if kind == "percentage" and scope == sku: - amount -= amount * decimal.Decimal(detail["percent"]) / 100 - net.append((sku, quantity, amount.quantize(CENT))) - subtotal = sum((amount for _, _, amount in net), - decimal.Decimal("0")) - for kind, _, detail in rules: - if (kind == "coupon" and detail.get("code") in coupons - and detail.get("amount")): - subtotal -= decimal.Decimal(detail["amount"]) - total = (subtotal * (1 + rate)).quantize(CENT) - return net, str(total) + name, price, category = connection.execute( + "SELECT name, unit_price, tax_category FROM products WHERE " + "sku = ?", (sku,)).fetchone() + price = decimal.Decimal(price) + gross = price * quantity + discount, applied = decimal.Decimal("0"), [] + for rule_id, kind, scope, detail, _ in rules: + if scope != sku: + continue + if kind == "percentage": + discount += gross * decimal.Decimal(detail["percent"]) \ + / 100 + applied.append(rule_id) + elif kind == "bulk": + buy, pay = int(detail["buy"]), int(detail["pay"]) + if quantity >= buy: + discount += price * (quantity // buy) * (buy - pay) + applied.append(rule_id) + priced.append({"sku": sku, "name": name, "quantity": quantity, + "unit_price": price, "gross": gross, + "line_discount": discount, + "net": gross - discount, "applied": applied, + "category": category}) + subtotal = sum((line["net"] for line in priced), decimal.Decimal("0")) + + # One slot for the invoice percentage and the threshold, the lowest + # result taking it; a threshold with no minimum is always eligible. + slot, applied = None, [] + for rule_id, kind, scope, detail, minimum in rules: + if scope or kind not in ("percentage", "threshold"): + continue + if kind == "threshold" and (VERSION != 2 or subtotal + < decimal.Decimal(minimum or "0")): + continue + result = subtotal * (100 - decimal.Decimal(detail["percent"])) \ + / 100 + if slot is None or result < slot[1]: + slot = (rule_id, result) + running = subtotal + if slot: + running = slot[1] + applied.append(slot[0]) + for rule_id, kind, scope, detail, _ in rules: + if kind == "coupon" and detail.get("code") in coupons \ + and detail.get("amount"): + running -= min(decimal.Decimal(detail["amount"]), running) + applied.append(rule_id) + discount_total = subtotal - running + standard = rates.get("standard", default) + taxable_total = tax_total = decimal.Decimal("0") + for line in priced: + share = (discount_total * line["net"] / subtotal if subtotal + else decimal.Decimal("0")) + line["invoice_discount"] = share + taxable = line["net"] - share + rate = rates.get(line["category"], default) + cap = caps.get(line["category"]) + if cap is None: + tax = taxable * rate + else: + tax = min(taxable, cap) * rate + max( + decimal.Decimal("0"), taxable - cap) * standard + tax = decimal.Decimal(money(tax)) + line.update(taxable=taxable, tax=tax, total=taxable + tax) + taxable_total += taxable + tax_total += tax + return { + "currency": "EUR", "jurisdiction": jurisdiction, + "lines": [{key: (money(line[key]) if isinstance( + line[key], decimal.Decimal) else line[key]) + for key in ("sku", "name", "quantity", "unit_price", + "gross", "line_discount", "net", + "invoice_discount", "taxable", "tax", "total", + "applied")} for line in priced], + "subtotal": money(subtotal), + "discount_total": money(discount_total), + "taxable_total": money(taxable_total), + "tax_total": money(tax_total), + "total": money(taxable_total + tax_total), "applied": applied} def invoices(self, connection, parts, method, data): if parts[1:] in (["preview"], []) and method == "POST": lines = [(sku, int(quantity)) for sku, quantity in zip( listed(data.get("sku")), listed(data.get("quantity")))] coupons = (data.get("coupon_codes") or "").split(",") - _, total = self.priced(connection, data["jurisdiction"], coupons, - lines) + priced = self.priced(connection, data["jurisdiction"], coupons, + lines) if parts[1:] == ["preview"]: - return Response(200, "

    Total %s

    " % total) + return Response(200, "

    Total %s

    " % priced["total"]) invoice = connection.execute( "INSERT INTO invoices (jurisdiction, customer, coupons) " "VALUES (?, ?, ?)", (data["jurisdiction"], @@ -2612,38 +2599,38 @@ def invoices(self, connection, parts, method, data): lines = connection.execute("SELECT sku, quantity FROM lines WHERE " "invoice = ? ORDER BY position", (parts[1],)).fetchall() - net, total = self.priced(connection, row[0], row[1].split(","), - lines) + priced = self.priced(connection, row[0], row[1].split(","), lines) if parts[2:] == ["export.json"]: - export = {"invoice_id": int(parts[1]), "jurisdiction": row[0], - "lines": [{"sku": sku, "quantity": quantity, - "net": str(amount)} - for sku, quantity, amount in net], - "total": total} + export = dict({"invoice_id": int(parts[1])}, **priced) if VERSION == 2: - export["caps"] = {} + export["caps_read"] = True return Response(500 if MARKUP == "erring" else 200, json.dumps(export)) - if parts[2:] == ["export.csv"] and MARKUP == "newcsv" \\ - and int(parts[1]) > 2: - return Response(500, "Internal Server Error") if parts[2:] == ["export.csv"]: - head = "sku,quantity,net" + (",cap" if VERSION == 2 else "") - return Response(200, "\\n".join([head] + [ - "%s,%d,%s" % (sku, quantity, amount) + if MARKUP == "newcsv" and int(parts[1]) > 2: + return Response(500, "Internal Server Error") + extra = ",cap" if VERSION == 2 else "" + rows = [CSV_HEAD + extra] + [ + ",".join(str(line[key]) for key in CSV_HEAD.split(",")) + ("," if VERSION == 2 else "") - for sku, quantity, amount in net]) + "\\n") + for line in priced["lines"]] + rows.append("TOTAL,,,,,,%s,%s,%s,%s,%s" % ( + priced["subtotal"], priced["discount_total"], + priced["taxable_total"], priced["tax_total"], + priced["total"]) + ("," if VERSION == 2 else "")) + return Response(200, "\n".join(rows) + "\n") return Response(200, "

    Invoice %s

    Total %s

    " - % (parts[1], total)) + % (parts[1], priced["total"])) def create_app(database): return App(database) ''' -# The faults the data upgrade must catch at version 2, and what each loses. +# The faults the data upgrade must catch at version 2. UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", - "extending", "fresh", "garbling", "fragile", "refusing") + "extending", "readdressing", "fresh", "garbling", + "undeletable", "fragile", "refusing") def plant_upgrade(where, version, mode): @@ -2674,95 +2661,60 @@ def upgrade_reading(scratch, fixture, changed): def upgrade_self_checks(scratch): - """A sound upgrade passes; each planted fault fails or loses the probe; - a fixture that cannot seed leaves it missing.""" + """A sound upgrade passes; each planted fault fails or loses the probe + through the exports it reads; a fixture that cannot seed leaves it + missing; the list pages are read for presence whatever their markup.""" sound = upgrade_reading(scratch, "sound", "sound") faults = {mode: upgrade_reading(scratch, "sound", mode) for mode in UPGRADE_FAULTS} unseeded = upgrade_reading(scratch, "unlisting", "sound") - items = upgrade_reading(scratch, "items", "items") - hidden = upgrade_reading(scratch, "sound+divs", "rerating+divs") - wrapped = upgrade_reading(scratch, "sound+pcells", "sound+pcells") - rewrapped = upgrade_reading(scratch, "sound+pcells", "rerating+pcells") - terse_read = upgrade_reading(scratch, "sound", "sound+terse") + divs = upgrade_reading(scratch, "sound+divs", "sound+divs") erring = upgrade_reading(scratch, "sound", "sound+erring") new_csv = upgrade_reading(scratch, "sound", "sound+newcsv") failed = sorted(mode for mode, reading in faults.items() if reading.get("passed") is False) + + def says(reading, text): + return any(text in failure + for failure in reading.get("failures") or []) return [ ("a version 2 that migrates the old database keeps every record", sound.get("passed") is True and not sound.get("failures") and len(sound.get("seeded_sha256") or "") == 64), ("a schema change shipped without a migration fails the upgrade", faults["unmigrated"].get("passed") is False - and any("/jurisdictions" in failure for failure in - faults["unmigrated"].get("failures") or [])), + and says(faults["unmigrated"], "/invoices/1 answered 500")), ("an old database rebuilt empty fails the upgrade", faults["dropping"].get("passed") is False - and any("no longer lists" in failure for failure in - faults["dropping"].get("failures") or [])), - ("rows all kept with their values changed fail the upgrade", + and says(faults["dropping"], "/rules no longer names u-pct-lamp")), + ("a rate the migration changes fails the invoices saved again too", faults["rewriting"].get("passed") is False - and any("no longer reads the same" in failure for failure in - faults["rewriting"].get("failures") or [])), - ("a listed field changed by the migration, no invoice priced by it, " - "fails the upgrade", - faults["rerating"].get("passed") is False - and faults["rerating"].get("failures") == [ - "/jurisdictions no longer shows 'standard=0.2' for UP", - "/jurisdictions no longer shows 'reduced=0.05' for UP"]), - ("a listed field kept only inside a longer one fails the upgrade", - faults["extending"].get("passed") is False - and faults["extending"].get("failures") == [ - "/jurisdictions no longer shows 'reduced=0.05' for UP"]), - ("a table row whose cells are paragraphs is read whole: kept when " - "sound, its cleared values named", - wrapped.get("passed") is True - and rewrapped.get("passed") is False - and rewrapped.get("failures") == [ - "/jurisdictions no longer shows 'standard=0.2' for UP", - "/jurisdictions no longer shows 'reduced=0.05' for UP"]), - ("a value written as another amount, a sign before it or no " - "trailing zeros, reads as the same value", - terse_read.get("passed") is True and not terse_read.get("failures")), - ("an export answering an error fails the upgrade, naming its status", - erring.get("passed") is False - and erring.get("failures") == [ - "/invoices/1/export.json answered 500", - "/invoices/2/export.json answered 500", - "/invoices/3/export.json answered 500"]), - ("an invoice saved after the upgrade whose CSV export errs fails " - "it", - new_csv.get("passed") is False - and new_csv.get("failures") == ["/invoices/3/export.csv answered " - "500"]), - ("a row found by no key leaves the upgrade missing, never passed", - hidden.get("passed") is None - and hidden.get("missing", "").startswith("row for ") - and hidden["missing"].endswith(" not found")), - ("a new record stored with other values than it was posted with " - "fails the upgrade", - faults["garbling"].get("passed") is False - and faults["garbling"].get("failures") == [ - "/jurisdictions lists %s without the %s it was posted with" - % (code, value) for code, value in ( - ("U2", "Upgradia Nova"), ("U2", "standard=0.1"), - ("U3", "Upgradia Capped"), - ("U3", "standard=0.2,reduced=0.05"))]), - ("a list-item row with a value the change adds keeps every old one", - items.get("passed") is True and not items.get("failures")), - ("a schema changed for new files alone fails on the change's own " - "fields", + and says(faults["rewriting"], "saved again as /invoices/3")), + ("category rates cleared or changed by the migration fail the " + "upgrade through the exports", + all(faults[mode].get("passed") is False + and says(faults[mode], "export.json no longer reads the same") + for mode in ("rerating", "extending"))), + ("a customer the migration rewrites fails through the customer's " + "export alone", + faults["readdressing"].get("failures") == [ + "the customer's export no longer reads the same at $.address"]), + ("a change's field dropped on an old file fails through the " + "invoices that exercise it", faults["fresh"].get("passed") is False - and faults["fresh"].get("failures") == [ - "/jurisdictions lists U3 without the reduced=50.00 it was " - "posted with", - "/rules lists u-threshold without the 200.00 it was posted " - "with"]), + and says(faults["fresh"], "the threshold below invoice reads") + and says(faults["fresh"], "the cap above invoice reads")), + ("a new jurisdiction stored with other rates fails through its " + "invoices", + faults["garbling"].get("passed") is False + and says(faults["garbling"], "the threshold at invoice reads")), + ("a seeded rule that will not be deleted stops the change's " + "invoices, never passes", + faults["undeletable"].get("passed") is False + and says(faults["undeletable"], "r-pct-all could not be deleted")), ("old invoices that break on the new field fail the upgrade", faults["fragile"].get("passed") is False - and any("/invoices/" in failure for failure in - faults["fragile"].get("failures") or [])), + and says(faults["fragile"], "/invoices/1 answered 500")), ("a version 2 that will not open the old database loses the upgrade", faults["refusing"].get("passed") is False and bool(faults["refusing"].get("lost"))), @@ -2770,6 +2722,17 @@ def upgrade_self_checks(scratch): failed == sorted(UPGRADE_FAULTS)), ("a fixture that cannot seed leaves the upgrade missing, not failed", unseeded.get("passed") is None and bool(unseeded.get("missing"))), + ("the list pages are read for the seeded identifiers alone, " + "whatever their markup", + divs.get("passed") is True and not divs.get("failures")), + ("an export answering an error fails the upgrade, naming its status", + erring.get("passed") is False + and (erring.get("failures") or [""])[0] + == "/invoices/1/export.json answered 500"), + ("an invoice saved after the upgrade whose CSV export errs fails it", + new_csv.get("passed") is False + and says(new_csv, "/invoices/3/export.csv answered 500") + and not says(new_csv, "/invoices/1/")), ] From 63893811e8191fe8abfe7505fe21da9ec092cab1 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:12:32 +0200 Subject: [PATCH 17/18] fix(efficacy): a changed tree that breaks fails only Reliability on its radar - read as the change task's own tree, a tree that does not install or boot is the change's: it fails Reliability's first target and is left out of every other axis, as a broken build is - a named round's change read beside its build keeps reading its targets whatever the build did Refs #178. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- tests/efficacy/report.py | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 6a273d7..9c3133d 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -241,7 +241,7 @@ when: | FR-16-03 | Self-test | `security.py` "a change task is read from its own scores into security-scores-change"
    `security.py` "a changed tree that does not install loses its probes, as a build's does"
    `quality.py` "a change task is read from its own scores into quality-scores-change" | | FR-16-04 | Self-test | `quality.py` "a version 2 that migrates the old database keeps every record"
    `quality.py` "a schema change shipped without a migration fails the upgrade"
    `quality.py` "an old database rebuilt empty fails the upgrade"
    `quality.py` "a rate the migration changes fails the invoices saved again too"
    `quality.py` "category rates cleared or changed by the migration fail the upgrade through the exports"
    `quality.py` "a customer the migration rewrites fails through the customer's export alone"
    `quality.py` "a change's field dropped on an old file fails through the invoices that exercise it"
    `quality.py` "a new jurisdiction stored with other rates fails through its invoices"
    `quality.py` "a seeded rule that will not be deleted stops the change's invoices, never passes"
    `quality.py` "old invoices that break on the new field fail the upgrade"
    `quality.py` "a version 2 that will not open the old database loses the upgrade"
    `quality.py` "every planted upgrade fault fails"
    `quality.py` "a fixture that cannot seed leaves the upgrade missing, not failed"
    `quality.py` "the list pages are read for the seeded identifiers alone, whatever their markup"
    `quality.py` "an export answering an error fails the upgrade, naming its status"
    `quality.py` "an invoice saved after the upgrade whose CSV export errs fails it"
    `quality.py` "a change task with no starting commit leaves the upgrade missing"
    `quality.py` "a changed tree that does not install loses the upgrade, its fixture named" | | FR-16-05 | Self-test | `judge.py` "a changed tree that did not install goes unjudged, read from its own scores"
    `judge.py` "a change task's trees are found by their trial, apart from the build's"
    `judge.py` "a changed tree's bundle naming its trial in a path leaks"
    `judge.py` "a changed tree's bundle carries the pinned change requirements, a build's none"
    `judge.py` "a changed tree's judge is told the change extends the spec, after the build's prompt unchanged"
    `judge.py` "a change task's judging run hands the judge the change's note and the bundle its requirements" | -| FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did" | +| FR-16-06 | Self-test | `report.py` "a change task's security, quality and judgings go with its change score, apart from the build's"
    `report.py` "a change reading left out takes its own readings along"
    `report.py` "the interfaces sit on Interoperability and the data upgrade on Adaptability, once each"
    `report.py` "a pilot round's table reads no change-task target"
    `report.py` "a change kept, broken, lost or unread reads met, not met, not met and not measured"
    `report.py` "a named round's change targets read whatever its build did"
    `report.py` "a changed tree that does not install is left out of every axis but Reliability on its own radar" | | FR-16-07 | Self-test | `archive.py` "a change task's security and quality readings and judgings are archived beside its score"
    `archive.py` "a C1 change task's quality reading flipped in the archive fails the verify"
    `reuse.py` "a change task comes with its arm's build trials, in a change run naming its round's fixtures"
    `reuse.py` "a change task's score, security and quality readings and judgings come along under their own folders"
    `reuse.py` "change tasks join a target only from the manifest its change runs took" | | FR-16-08 | Self-test | `report.py` "a named round reads the ISO radar once a task, the build's first"
    `report.py` "a C1 run gives lazysections and lazyrefold a verdict and a cost on each task, against none"
    `report.py` "each task's radar reads that task's trees against `none` on the same task"
    `report.py` "the change task's radar reads its own security, not the build's"
    `report.py` "a named round's build radar leaves the change targets to the change task's"
    `report.py` "each task's radar shows its own mean billed cost per trial"
    `report.py` "a pilot round draws one radar, its trials as they are"
    `report.py` "the summary gives a radar, a verdict and a cost for each task, each named"
    `report.py` "a named round's report draws the change task's radar beside the build's and tables each task's axes"
    `report.py` "a named round with no build reads its finding table from the change task's own trials and cost"
    `report.py` "named pairs are read for every metric of a table" | | FR-16-09 | Self-test | `report.py` "the check loop is kept on a 10 % cost drop on each task with no axis worse"
    `report.py` "the check loop is not kept on the build task's readings alone"
    `report.py` "a cost drop under 10 % on one task does not keep the check loop"
    `report.py` "an axis worse on either task does not keep the check loop"
    `report.py` "nothing flagged worse reads no degradation detected, beside the non-inferiority read apart"
    `report.py` "an interval crossing the margin is inconclusive, never non-inferior"
    `report.py` "the report and its full record print the registered readings"
    `report.py` "a cost drop of exactly 10 % keeps the gate, read from the unrounded differences"
    `report.py` "a cost drop a float's error under 10 % meets the gate"
    `report.py` "a cost drop a float's error under 10 % reads yes in the table and keeps the loop"
    `report.py` "C1 reads an axis non-inferior only with its lower bound strictly above minus the margin"
    `report.py` "a round running none of the registered pairs prints none of them" | diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index be22800..535f08c 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -5842,6 +5842,22 @@ def reading(interfaces, data_upgrade, install=True): and unread == (None, None))) checks.append(("a named round's change targets read whatever its build " "did", gated == (1.0, True))) + + # Read as the change task's own tree, a changed tree that did not + # install is a broken tree: Reliability reads it, no other axis does. + failed = change_view({"round": "C1", "change": { + "name": "none-1", "install": {"value": False, "missing": None}, + "interfaces": {"value": 0.0, "missing": None}, + "change_suite": {"value": 0.0, "missing": None}}, + "change_quality": {"probes": {"data_upgrade": { + "passed": False, "lost": "would not install"}}}}) + scores = iso_trial_scores(failed) + checks.append(("a changed tree that does not install is left out of " + "every axis but Reliability on its own radar", + scores["Reliability"]["Faultlessness"] == 0.0 + and all(value is None for axis, subs in scores.items() + if axis != BROKEN_AXIS + for value in subs.values()))) return checks @@ -7417,8 +7433,11 @@ def iso_trial_scores(trial, withdrawn=(), axes=ISO_AXES): broken = works(trial) != 1.0 # A named round's change task never ran on this trial's build, so a - # build broken, or not scored at all, says nothing of the change. - apart = trial.get("round") is not None or trial.get("change_only") + # build broken, or not scored at all, says nothing of the change. Read + # as the change task's own tree, the broken tree is the change's, and is + # left out of every axis but Reliability as a broken build is. + apart = ((trial.get("round") is not None or trial.get("change_only")) + and trial.get("task") != "change") scores = {} for axis, subs in axes: per_sub = {} From c37c5458a6568d69563a0f72860028dbb8c6ba50 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:29:50 +0200 Subject: [PATCH 18/18] fix(efficacy): the archive's C1 fixture plants a changed tree that works - the verify's C1 root planted a change score with no install or boot reading, which its task's radar now reads as a broken tree, left out of every axis but Reliability; the flipped data upgrade then moved nothing - the planted change score installs and boots, as the check means it to Refs #178. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/archive.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index 98f55db..28d8ee1 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -582,9 +582,14 @@ def self_test(): "frozen": {"head": "h", "tarball": tarball}}], "change", identity={"round": "C1", "registration": registration_digest(REGISTRATIONS["C1"])}) + # A changed tree that installed and booted, so every axis of its task's + # radar reads its readings. dump_json(os.path.join(scoring_area(named), "scores-change", "none-1.json"), - {"name": "none-1", "change_suite": {"value": 0.9}}) + {"name": "none-1", "change_suite": {"value": 0.9}, + "install": {"value": True, "missing": None}, + "boot": {"value": {"factory": True, "index_status": 200}, + "missing": None}}) dump_json(os.path.join(scoring_area(named), "quality-scores-change", "none-1.json"), {"name": "none-1", "probes": {"data_upgrade": {