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 812e547..b29947b 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -361,6 +361,53 @@ 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). 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 +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 | 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). +- **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 + 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 @@ -623,8 +670,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 @@ -639,10 +686,44 @@ 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. +**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. + +**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 3699edd..9c3133d 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -231,3 +231,18 @@ 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"
`quality.py` "a trial whose source tree is gone is missing, not lost" | + +## 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"
`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` "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"
`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" | +| 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/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/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 1aacbf8..16ed641 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -245,6 +245,21 @@ | 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; a trial whose source tree is not present has every probe missing. | 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 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, 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 | +| 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 | + ## Quality requirements - **Numbering:** characteristics follow ISO/IEC 25010:2023 order, 01 @@ -338,8 +353,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 +381,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 +453,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 cbb1713..28d8ee1 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")) @@ -303,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() @@ -361,8 +380,10 @@ 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")) - folders += glob.glob(os.path.join(area, "quality", "*", "venv*")) + for reader in ("security", "security-change"): + folders += glob.glob(os.path.join(area, reader, "*", "venv")) + for reader in ("quality", "quality-change"): + folders += glob.glob(os.path.join(area, reader, "*", "venv*")) for folder in folders: remove_tree(folder) return len(folders) @@ -450,6 +471,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: @@ -497,6 +523,15 @@ def self_test(): "scoring/scores-change/none-1.json", "scoring/judge/T1.json", "scoring/judge/map.json", "scoring/tool-lock.txt"} <= set(files) and not any("bundle" in key for key in 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], @@ -547,9 +582,18 @@ 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": { + "passed": True}}}) named_into = os.path.join(scratch, "runs", "c1") archive(named, named_into) clean = verify(named, named_into, seed) == [] @@ -561,6 +605,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/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 4e92595..5c9a566 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -475,6 +475,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" @@ -1868,6 +1882,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.""" @@ -1899,6 +1920,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" @@ -2219,7 +2250,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")}, # The fixtures' directory, which the trial's deny rules and # every scan of its transcript fence off, and its archives' @@ -4555,8 +4587,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))] @@ -4565,6 +4599,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..25d59e1 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, read_change_prompt, + release_area, task_folder) HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPT = os.path.basename(__file__) @@ -258,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. @@ -343,8 +364,10 @@ 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, 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, 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 @@ -385,9 +408,21 @@ def build_bundle(tree, target): if spec: with io.open(os.path.join(target, "SPEC.md"), "wb") as handle: handle.write(spec.pop("text")) - return {"removed": removed, "markers_masked": masked, "spec": spec, - "leaks": surviving_markers(target, os.path.basename(tree)), - "digest": digest(target)} + 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)] + 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): @@ -542,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. @@ -552,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 @@ -570,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)} @@ -594,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 @@ -626,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. @@ -692,24 +727,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 +831,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 +850,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 +879,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") @@ -886,20 +931,24 @@ 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) + 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, "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, @@ -1157,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. @@ -1212,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) @@ -1226,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" @@ -1353,8 +1447,51 @@ 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", 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"])), + ("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): @@ -1388,6 +1525,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 +1546,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/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/quality.py b/tests/efficacy/quality.py index 529d364..814ad7c 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -4,7 +4,10 @@ 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, 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 @@ -15,12 +18,14 @@ import argparse import datetime +import hashlib import io import json import os import shutil import sqlite3 import sys +import tarfile import tempfile sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -28,7 +33,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) @@ -41,6 +46,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") @@ -72,7 +81,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, 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 @@ -248,10 +257,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] @@ -994,6 +1007,369 @@ def fuzz_robustness(): statuses=[entry.get("status") for entry in answers]) +# 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/])") +TAG = 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): + return {"jurisdiction": jurisdiction, "currency": "EUR", + "customer": customer, "coupon_codes": coupons, + "sku": [sku for sku, _ in lines], + "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): + """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, 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 + +VERSION = __VERSION__ +MODE, _, MARKUP = "__MODE__".partition("+") +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")) +CSV_HEAD = ("sku,name,quantity,unit_price,gross,line_discount,net," + "invoice_discount,taxable,tax,total") + + +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)] + + +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 + 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, 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 " + "INTEGER, sku TEXT, quantity INTEGER);" % (added, capped)) + 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)) + if MODE == "rewriting": + connection.execute("UPDATE jurisdictions SET " + "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 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"),)) + 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.execute("INSERT INTO rules (rule_id, kind, sku, " + "detail) VALUES (?, ?, ?, ?)", ( + "r-pct-all", "percentage", "", + json.dumps({"percent": "5"}))) + connection.commit() + connection.close() + + def connect(self): + return sqlite3.connect(self.database) + + 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" 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) + + +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] == "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) + 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, unit_price FROM " + "products") + elif table == "rules": + rows = connection.execute("SELECT rule_id, kind FROM rules") + else: + rows = connection.execute("SELECT code, name, default_rate, " + "rates FROM jurisdictions") + rows = list(rows) + if MARKUP == "divs": + return "".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) + + 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")}) + names, values = ["rule_id", "kind", "sku", "detail"], [ + data["rule_id"], data["kind"], data.get("sku"), detail] + 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)" % ( + ", ".join(names), ", ".join("?" for _ in names)), values) + else: + if MODE == "garbling": + data = dict(data, rates="standard=0.9") + self.app.add_jurisdiction(connection, data["code"], data["name"], + data["default_rate"], + data.get("rates") or "", + data.get("caps")) + 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): + """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) + 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: + 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(",") + priced = self.priced(connection, data["jurisdiction"], coupons, + lines) + if parts[1:] == ["preview"]: + return Response(200, "

Total %s

" % priced["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() + priced = self.priced(connection, row[0], row[1].split(","), lines) + if parts[2:] == ["export.json"]: + export = dict({"invoice_id": int(parts[1])}, **priced) + if VERSION == 2: + export["caps_read"] = True + return Response(500 if MARKUP == "erring" else 200, + json.dumps(export)) + if parts[2:] == ["export.csv"]: + 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 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], priced["total"])) + + +def create_app(database): + return App(database) +''' + +# The faults the data upgrade must catch at version 2. +UPGRADE_FAULTS = ("unmigrated", "dropping", "rewriting", "rerating", + "extending", "readdressing", "fresh", "garbling", + "undeletable", "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 + 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") + 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 says(faults["unmigrated"], "/invoices/1 answered 500")), + ("an old database rebuilt empty fails the upgrade", + faults["dropping"].get("passed") is False + 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 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 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 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"))), + ("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"))), + ("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/")), + ] + + FAULTS = {"fragile": "fuzz_robustness", "brittle": "fuzz_robustness", "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", @@ -1951,6 +3051,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), ] @@ -1963,7 +3104,7 @@ def self_test(): checks = (runtime_self_checks(scratch) + reading_self_checks() + portability_self_checks(scratch) + claim_self_checks(scratch) + absent_tree_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) @@ -1989,6 +3130,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") @@ -2003,20 +3148,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 @@ -2032,9 +3171,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: @@ -2052,7 +3206,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 055fdf2..535f08c 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, @@ -660,9 +661,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).""" @@ -1196,13 +1230,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. @@ -1210,10 +1245,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 CONTRASTS: + for treatment, baseline in selected: label = "%s-%s" % (treatment, baseline) if only and label not in only: continue @@ -1226,19 +1264,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"]) @@ -1249,8 +1287,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( @@ -1730,7 +1768,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) @@ -1851,7 +1889,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 @@ -1862,7 +1900,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}] @@ -1898,6 +1937,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: @@ -1906,18 +1950,28 @@ 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, + finding_reading(tasks, trials, table, + results, iso, seed, + withdrawn))) 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. + by_task = task_uses(root, tasks) if tasks else {} + registered = registered_lines(tasks, seed, by_task) if tasks else [] + lines.extend(registered) + lines.extend(["## What produced these numbers", ""]) lines.extend(provenance_lines(trials, names, arms, k, seed, generation)) @@ -1983,11 +2037,13 @@ def write_report(root, trials, table, results, seed, out_dir, lines.append("") # A named round reads its on-demand arms' use of their maps too, with - # no pilot hypothesis beside it. - if named_round(trials) is not None: - uses = report_uses(root, trials) if uses is None else uses - if uses and map_use_rows(trials, uses): - lines.extend(map_use_lines(trials, uses, "## Use of the map", + # no pilot hypothesis beside it, once a task, each over that task's own + # trials and transcripts. + for task, label, view, _, _ in tasks: + found = by_task.get(task) or {} + if found and map_use_rows(view, found): + lines.extend(map_use_lines(view, found, + "## Use of the map, %s" % label, h7=False)) lines.append("") @@ -2071,9 +2127,10 @@ 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, + registered)} for document, text in documents.items(): with io.open(os.path.join(out_dir, document), "w", encoding="utf-8", newline="\n") as handle: @@ -2081,6 +2138,43 @@ 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 + 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.""" + 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 @@ -2555,10 +2649,12 @@ 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=(), 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.""" + 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, + 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]) @@ -2575,22 +2671,27 @@ 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)) + lines.extend(registered) + 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 @@ -2642,6 +2743,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.""" @@ -2663,10 +2788,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) @@ -2679,7 +2805,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. @@ -2690,7 +2824,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 " @@ -3175,6 +3309,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.*?\[\]-]+/[\w.*?\[\]-]+)") +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( @@ -3654,6 +3794,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): @@ -3666,24 +3812,51 @@ def mapped(templates): else None, "by_subagent": by_subagent} -def report_uses(root, trials): - """The map uses a report reads: every trial's, wherever the run holds an - arm whose file points at a map, named round or not; None where it holds - none.""" +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 in files] + found = [] + for index, read in shell_reads(command, files, SKILL_OPERAND): + skill = read.split("/")[0] + if read in files: + 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 + it holds none.""" if not any(mapped_templates(arm_of(name)) for name in trials): return None - return map_uses(root, trials) + return map_uses(root, trials, task) -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) @@ -5598,6 +5771,450 @@ 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))) + + # 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 + + +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 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}) + 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) + 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()}) + + # 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 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), + ("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 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() + 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") + every = mapped_templates("lazysections") + sections = every[:2] + + # A listing reads nothing; a wildcard read reads each file it matches. + folder = posixpath.dirname(sections[0]) + last = posixpath.dirname(every[-1]) + matched = [name for name in every if posixpath.dirname(name) == last] + + 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\\" + + sections[0].replace("/", "\\"))], + "change": [call("Read", file_path="/pen/" + sections[0]), + call("Bash", command="ls " + folder), + call("Bash", command="cat %s/*.md | head" % last), + call("Read", file_path="/pen/src/app.py")]} + records = [] + 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, 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: + json.dump({"trials": records}, handle) + 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)}), + ("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): + """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])] + + @contextlib.contextmanager def planted_repository(path, documents=()): """While inside, the report reads registrations from a git repository @@ -5637,6 +6254,100 @@ 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"}), + ("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): + 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"]), + ("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" + 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 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 @@ -6361,10 +7072,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", ( @@ -6401,9 +7113,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", ()), @@ -6519,12 +7233,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", @@ -6578,8 +7294,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(): @@ -6665,6 +7383,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: @@ -6678,6 +7398,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.""" @@ -6701,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 = {} @@ -6717,7 +7452,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) @@ -7038,7 +7774,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, @@ -7049,6 +7785,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"], @@ -7071,6 +7815,368 @@ 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 + + +# 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 + +# 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" + + +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 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 {} + 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 or low is None: + state = None + elif low > -ISO_MARGINS[axis]: + 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 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 (-statistics.fmean(contrast["pairs"]) / 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. + 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 not meets_cost_drop(read["cost"][0])) + 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 True + + +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_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 + 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 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 " + "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 " @@ -7094,17 +8200,31 @@ 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=(), 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. + 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; `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. """ active = active_contrasts(trials) lines = ["## Executive summary", ""] + if tasks: + for reading, images in tasks: + lines.extend(task_lines(reading, images) + [""]) + 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 if radar: for theme, image in sorted(radar.items()): lines.append("![Radar per arm](%s#gh-%s-mode-only)" @@ -7122,13 +8242,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] @@ -7139,12 +8260,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)]) @@ -8553,15 +9674,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): @@ -8822,7 +9945,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] @@ -9169,7 +10292,7 @@ def named_map_use_checks(seed): total = len(mapped_templates("lazysections")) return [ ("a named round's report prints its sections arm's use of the map", - "## Use of the map" in text and "Beside H7" not in text + "## Use of the map, build task" in text and "Beside H7" not in text and row == "| lazysections | 1 | %d | 2.0 | 2.0 | 1 | 0 of 1 |" % total and "| lazysections-1 | 3 | 0 | 1: %s, 2: %s |" % (first, second) in text, row), @@ -9393,6 +10516,15 @@ 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()) + 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 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: print(" %-52s %s" % (label, "ok" if ok else "FAILED, got %r" % (got,))) @@ -9592,15 +10724,26 @@ 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) - uses = report_uses(options.root, trials) + + # 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] + + # A named round reads each task's map use over that task's own trials; + # the build's is the one the aggregate keeps. + uses = (task_uses(options.root, tasks).get("build") if tasks + else report_uses(options.root, trials)) 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) diff --git a/tests/efficacy/reuse.py b/tests/efficacy/reuse.py index a1a1c34..e22532b 100644 --- a/tests/efficacy/reuse.py +++ b/tests/efficacy/reuse.py @@ -24,14 +24,18 @@ import lib # noqa: E402 from harness import (ARMS, PROMPT, REGISTRATIONS, TrialError, # noqa: E402 - assert_outside_repository, canonical, identity_problem, - now, project_folder, recorded_round, + assert_outside_repository, canonical, fixtures_problem, + identity_problem, + 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 +73,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 +90,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 +116,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 +135,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 +199,25 @@ 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) + + # 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: + 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 +236,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 +276,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.""" @@ -278,9 +339,105 @@ 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"}), + ("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.""" @@ -390,6 +547,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..003f711 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -38,10 +38,11 @@ import lib # noqa: E402 import probes # noqa: E402 -from harness import (SCORABLE, LiveRunError, TrialError, # noqa: E402 - canonical, claim_area, claim_refusal_check, - frozen_top, name_of, release_area, remove_tree, - scorable_trials, scoring_area) +from harness import (INTERFACE_MODULES, SCORABLE, LiveRunError, # noqa: E402 + TrialError, canonical, claim_area, claim_refusal_check, + 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__) @@ -335,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" @@ -358,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): @@ -1095,13 +1105,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)] @@ -1235,7 +1255,21 @@ 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, + 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; the + public surface is read against `required`.""" + 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 @@ -1268,7 +1302,7 @@ def score_trial(record, options, suite, lock): 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: @@ -1278,13 +1312,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 +1355,50 @@ 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) + + # 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 + # 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 +1413,90 @@ 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["churn"] = (churn(workspace, record["base"]) if record.get("base") - else absent("the change record names no starting " - "commit")) + scores["interfaces"] = interfaces(scores["build_suite"], + record.get("fixture")) + + scores["churn"] = changed + 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 + 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") + # 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"]) + modules = {} + for module in INTERFACE_MODULES: + 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)]) + 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 +1811,214 @@ 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)) + + # 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"]), + ("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"), + ("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 + 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, 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 + 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, 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, folder), + 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))] + + +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 @@ -1736,6 +2068,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" @@ -2068,13 +2447,16 @@ 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) + + 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", 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) @@ -2203,11 +2585,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 +2635,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 +2678,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 +2692,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)